Browse Source

Merge pull request #26: kernel watchdog, sensor re-init, camera keeps node, ONVIF position limits

master
ClaudeAI 54 minutes ago
parent
commit
74d7cf9ed8
  1. 164
      Projects/watchDogDaemon/kernel.cpp
  2. 2
      Projects/watchDogDaemon/kernel.h
  3. 121
      lib/App/common/SQLite_dataBinder.cpp
  4. 7
      lib/App/common/deviceNode.cpp
  5. 7
      lib/App/common/deviceNode.h
  6. 16
      lib/App/common/deviceNode2D.cpp
  7. 1
      lib/App/common/deviceNode2D.h
  8. 179
      lib/App/common/deviceNodeCamera.cpp
  9. 20
      lib/App/common/deviceNodeCamera.h
  10. 21
      lib/App/common/deviceNodeEthernet2Serial.cpp
  11. 5
      lib/App/common/deviceNodeEthernet2Serial.h
  12. 4
      lib/App/common/hardwareManager.cpp
  13. 7
      lib/App/common/hardwareResource.h
  14. 46
      lib/App/common/hardwareResourceSerialProvider.cpp
  15. 4
      lib/App/common/hardwareResourceSerialProvider.h
  16. 15
      lib/App/common/kernelHelperMediaMTX.cpp
  17. 6
      lib/App/common/kernelHelperMediaMTX.h
  18. 146
      lib/App/common/kernelPrototype.cpp
  19. 37
      lib/App/common/kernelPrototype.h
  20. 28
      lib/App/common/streamHandler.cpp
  21. 8
      lib/App/common/streamHandler.h
  22. 3
      lib/App/common/targetPipeLine.cpp
  23. 3
      lib/App/common/targetPipeLine.h
  24. 41
      lib/App/mojo/mojoKernel.cpp
  25. 17
      lib/alg/generic/Transform.cpp
  26. 5
      lib/components/base/basicTransport.cpp
  27. 7
      lib/components/base/basicTransport.h
  28. 195
      lib/data/ponvif/ponvif.cpp
  29. 36
      lib/data/ponvif/ponvif.h
  30. 2
      lib/data/protocol/protocolPTZ_ONVIF.cpp

164
Projects/watchDogDaemon/kernel.cpp

@ -219,10 +219,9 @@ bool SP_KERNEL::create(void)
int x = fcntl(m_iServerSocket, F_GETFL, 0); int x = fcntl(m_iServerSocket, F_GETFL, 0);
fcntl(m_iServerSocket, F_SETFL, x | O_NONBLOCK); fcntl(m_iServerSocket, F_SETFL, x | O_NONBLOCK);
bind(m_iServerSocket, (struct sockaddr *) &server_addr, slen);
if (m_iServerSocket == INVALID_SOCKET)
if (m_iServerSocket == INVALID_SOCKET || bind(m_iServerSocket, (struct sockaddr *) &server_addr, slen) != 0)
{ {
LOG_ERROR("Could not bind to the UX socket!");
LOG_ERROR("Could not bind to the UX socket!"); // the bind() result was not checked
return false; return false;
}; };
listen(m_iServerSocket, 5); listen(m_iServerSocket, 5);
@ -234,69 +233,102 @@ void SP_KERNEL::WaitFinish(bool force)
waitThreadEnd(force); waitThreadEnd(force);
} }
/*
One client: first line = PID to kill, then "N" = next update within N ms, "-1" = stop monitoring.
- Lines are assembled in a buffer: readLine() on the non-blocking socket dropped the bytes of a line
that had only partly arrived.
- EOF (the client closed / crashed without "-1") ends the monitoring: before, EOF read as "no data"
and after the deadline kill(9) went to a PID that may belong to another process by then.
*/
void * SP_KERNEL::sw_proc(void * ptr) void * SP_KERNEL::sw_proc(void * ptr)
{ {
char tB[64];
uint64_t cMS;
uint64_t tMS;
WATCHDOG_PROC_REC * mR = (WATCHDOG_PROC_REC *) ptr;
WATCHDOG_PROC_REC * mR = (WATCHDOG_PROC_REC *) ptr;
pid_t CPID = 0; pid_t CPID = 0;
char tLine[128];
size_t tHave = 0;
char jB[192];
if (mR) if (mR)
{ {
cMS = getMilliseconds();
tMS = cMS + SW_DEFAULT_TIMEOUT;
while (1)
uint64_t tLastUpdate = getMilliseconds();
uint64_t tMS = tLastUpdate + SW_DEFAULT_TIMEOUT;
bool tRun = true;
while (tRun)
{ {
cMS = getMilliseconds();
int retVal = readLine(mR->client_socket, tB, 64);
if (retVal < 0)
{
if (errno != EAGAIN && errno != EINTR)
{
mR->master->m_pLog->Log("K_T", mR->master, "Peer Closes Connection!");
shutdown(mR->client_socket, 2);
close(mR->client_socket);
mR->client_socket = -1;
break; //-----> exit thread
};
}
else
uint64_t cMS = getMilliseconds();
// read what is there (non-blocking)
for (;;)
{ {
if (retVal)
char tB[64];
ssize_t tN = read(mR->client_socket, tB, sizeof(tB));
if (tN > 0)
{ {
// char jB[128];
// sprintf( jB, "Server: I recieved [%d] %s from client!", retVal, tB );
// mR->master->m_pLog->Log( "K_T", mR->master, jB );
if (CPID)
for (ssize_t k = 0; k < tN; k++)
{ {
int64_t nMS = atoll(tB);
// Stop WD and exit
if (nMS < 0)
if (tB[k] == '\n' || tB[k] == '\r')
{
if (tHave == 0)
{
continue;
};
tLine[tHave] = 0;
tHave = 0;
if (CPID == 0)
{
CPID = (pid_t) atoll(tLine);
snprintf(jB, sizeof(jB), "Watching PID %d", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB);
}
else
{
int64_t nMS = atoll(tLine);
if (nMS < 0)
{
snprintf(jB, sizeof(jB), "PID %d: monitoring stopped by the client", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB);
tRun = false; // Stop WD and exit
break;
};
tMS = cMS + nMS;
tLastUpdate = cMS;
};
}
else if (tHave < sizeof(tLine) - 1)
{ {
shutdown(mR->client_socket, 2);
close(mR->client_socket);
mR->client_socket = -1;
break;
tLine[tHave++] = tB[k];
}; };
// sprintf( jB, "Will Wait next [%d] milliseconds", nMS );
// mR->master->m_pLog->Log( "K_T", mR->master, jB );
tMS = cMS + nMS;
}
else
};
if (! tRun)
{ {
CPID = (pid_t) atoll(tB);
break;
}; };
continue;
}; };
if (tN == 0)
{
snprintf(jB, sizeof(jB), "PID %d: peer closed the connection - monitoring ended", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB);
tRun = false;
}
else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
{
mR->master->m_pLog->Log("K_T", mR->master, "Peer Closes Connection!");
tRun = false;
};
break;
};
if (! tRun)
{
break;
}; };
if (cMS > tMS) if (cMS > tMS)
{ {
// WD TO EXIT! // WD TO EXIT!
mR->master->m_pLog->Log("K_T", mR->master, "WD update STALLED!");
snprintf(jB, sizeof(jB), "WD update STALLED! (PID %d, last update %llu ms ago)", (int) CPID, (unsigned long long) (cMS - tLastUpdate));
mR->master->m_pLog->Log("K_T", mR->master, jB);
if (CPID) if (CPID)
{ {
// Try Kill Client Process; // Try Kill Client Process;
char jB[128];
sprintf(jB, "Try Killing Process[%lld] By Signal 9!", CPID);
snprintf(jB, sizeof(jB), "Try Killing Process[%d] By Signal 9!", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB); mR->master->m_pLog->Log("K_T", mR->master, jB);
kill(CPID, 9); kill(CPID, 9);
} }
@ -308,17 +340,13 @@ void * SP_KERNEL::sw_proc(void * ptr)
}; };
SLEEP(SW_TIMEOUT_PERCISION); SLEEP(SW_TIMEOUT_PERCISION);
}; };
shutdown(mR->client_socket, 2);
close(mR->client_socket);
mR->client_socket = -1;
mR->finished = true;
}; };
mR->finished = true;
pthread_exit(NULL); pthread_exit(NULL);
return NULL; return NULL;
/*
read(client_socket, &ch, 1);
printf("\nServer: I recieved %c from client!\n", ch);
ch++;
write(client_socket, &ch, 1);
close(client_socket);
*/
} }
void SP_KERNEL::m_fThreadProc(void) void SP_KERNEL::m_fThreadProc(void)
@ -338,20 +366,20 @@ void SP_KERNEL::m_fThreadProc(void)
{ {
case EAGAIN: case EAGAIN:
{ {
// Checkup client disconnection
if (m_vWPV.size())
// Checkup client disconnection: join and free finished handlers
// (erase() inside the for loop skipped the next handler; the records were never freed)
for (WATCHDOG_PROCS_VECTOR::iterator index = m_vWPV.begin(); index != m_vWPV.end();)
{ {
for (WATCHDOG_PROCS_VECTOR::iterator index = m_vWPV.begin(); index < m_vWPV.end(); index++)
if ((*index)->finished)
{ {
if ((*index)->finished)
{
LOG("Detach WD Procedure");
pthread_join((*index)->handler, NULL);
LOG("WD Procedure Detached");
// Remove Client Handler
LOG("Remove WD Procedure");
m_vWPV.erase(index);
};
pthread_join((*index)->handler, NULL);
LOG("WD Procedure Removed");
free(*index);
index = m_vWPV.erase(index);
}
else
{
++index;
}; };
}; };
SLEEP(10); SLEEP(10);
@ -391,14 +419,18 @@ void SP_KERNEL::m_fThreadProc(void)
int x = fcntl(ClientSocket, F_GETFL, 0); int x = fcntl(ClientSocket, F_GETFL, 0);
fcntl(ClientSocket, F_SETFL, x | O_NONBLOCK); fcntl(ClientSocket, F_SETFL, x | O_NONBLOCK);
memset(tPRC, 0, sizeof(WATCHDOG_PROC_REC)); // finished was uninitialized (malloc): a live handler
// could be joined - the accept loop blocked
tPRC->client_socket = ClientSocket; tPRC->client_socket = ClientSocket;
tPRC->master = this; tPRC->master = this;
tPRC->finished = false;
int RetVal = pthread_create(&tPRC->handler, NULL, sw_proc, (void *) tPRC); int RetVal = pthread_create(&tPRC->handler, NULL, sw_proc, (void *) tPRC);
if (RetVal == -1)
if (RetVal != 0) // pthread_create returns an error number, not -1
{ {
LOG_ERROR("No Client Thread Created!"); LOG_ERROR("No Client Thread Created!");
shutdown(ClientSocket, 2); shutdown(ClientSocket, 2);
close(ClientSocket); close(ClientSocket);
free(tPRC);
} }
else else
{ {

2
Projects/watchDogDaemon/kernel.h

@ -16,7 +16,7 @@ typedef struct S_WATCHDOG_PROC_REC
SP_KERNEL * master; SP_KERNEL * master;
int client_socket; int client_socket;
uint64_t timeout; uint64_t timeout;
bool finished;
volatile bool finished;
pthread_t handler; pthread_t handler;
} WATCHDOG_PROC_REC; } WATCHDOG_PROC_REC;

121
lib/App/common/SQLite_dataBinder.cpp

@ -1,5 +1,12 @@
#include "SQLite_dataBinder.h" #include "SQLite_dataBinder.h"
#include <atomic>
#include <string>
#include <thread>
// A report day is being deleted in the background (deleteReportDate)
static std::atomic<bool> s_bReportDayDeleting(false);
#include "../../components/base/basicEvent.h" #include "../../components/base/basicEvent.h"
#define LOG(X) m_pLog->Log("SDBC", this, X) #define LOG(X) m_pLog->Log("SDBC", this, X)
@ -109,6 +116,11 @@ sqliteDBC::sqliteDBC(config_setting_t * Settings) :
sqliteDBC::~sqliteDBC() sqliteDBC::~sqliteDBC()
{ {
// A report day still being deleted in the background uses this object (deleteReportStat)
for (int i = 0; i < 600 && s_bReportDayDeleting; i++)
{
SLEEP(100);
};
if (m_pDataStorage) if (m_pDataStorage)
{ {
delete(m_pDataStorage); delete(m_pDataStorage);
@ -2415,18 +2427,44 @@ uint32_t sqliteDBC::getFirstEventTS()
return rv; return rv;
} }
/*
Called from the kernel loop (validateReports: daily cleanup, or every second while the disk is above
preserve_empty). deleteRDFDir() runs "rm -f -R <whole day>" - many seconds (minutes on a big SD card):
the kernel loop stalled and the watchdog killed la_mojo. The day is deleted in a background thread;
while it runs, further calls return false (the oldest day is still listed until it is done).
*/
bool sqliteDBC::deleteReportDate(uint32_t ts) bool sqliteDBC::deleteReportDate(uint32_t ts)
{ {
if (ts) if (ts)
{ {
bool tFalse = false;
if (! s_bReportDayDeleting.compare_exchange_strong(tFalse, true))
{
return false; // a day is being deleted
};
REPORT_DIRINFO tRDF;// = {0}; REPORT_DIRINFO tRDF;// = {0};
fillRDF(ts, tRDF); fillRDF(ts, tRDF);
LOG("Delete RDF Dir");
if (deleteRDFDir(m_pDbReportBase, tRDF))
std::string tBase(m_pDbReportBase);
LOG("Delete RDF Dir (background)");
try
{
std::thread([this, tBase, tRDF]() mutable {
pthread_setname_np(pthread_self(), "ReportDelete");
if (deleteRDFDir((CSTR) tBase.c_str(), tRDF))
{
LOG("Dir Deleted OK");
deleteReportStat(tRDF);
};
s_bReportDayDeleting = false;
}).detach();
}
catch (const std::exception & e)
{ {
LOG("Dir Deleted OK");
return deleteReportStat(tRDF);
s_bReportDayDeleting = false;
LOG_ERROR("Can not start the report delete thread");
return false;
}; };
return true;
}; };
return false; return false;
} }
@ -5741,56 +5779,63 @@ bool sqliteDBC::updateIPCam(uint32_t CamID, CSTR Addr)
{ {
if (m_bStoIsConnected) if (m_bStoIsConnected)
{ {
// onvif_ctrl = path of the device service only (as la_mojo's own discovery INSERT and the web UI
// store it; la_mojo builds http://ip[:port]onvif_ctrl). The whole XAddrs list was stored: the record
// changed on every discovery round and the camera node was rebuilt (its stream dropped).
char tPath[256] = "/onvif/device_service";
{
const char * tH = strstr(Addr, "//");
if (tH != NULL)
{
const char * tP = strchr(tH + 2, '/');
if (tP != NULL)
{
size_t tLen = strcspn(tP, " \t\r\n"); // first XAddr only
if (tLen > 0 && tLen < sizeof(tPath) && memchr(tP, '\'', tLen) == NULL)
{
memcpy(tPath, tP, tLen);
tPath[tLen] = 0;
};
};
};
}
char tQBuf[MAX_PATH_LEN]; char tQBuf[MAX_PATH_LEN];
char tIpBuf[CTEXT]; char tIpBuf[CTEXT];
char * tPos;
char * tPos2;
uint16_t tPort = 0; uint16_t tPort = 0;
tPos = strstr(Addr, "//");
if (tPos != NULL)
// host[:port] of the FIRST XAddr only: the old parser searched ':' in the whole list (a second, IPv6
// XAddr or a ':' in the path gave a broken IP / port)
tIpBuf[0] = (char) 0;
{ {
tPos2 = strstr(tPos + 2, ":");
if (tPos2 != NULL)
const char * tH = strstr(Addr, "//");
if (tH != NULL)
{ {
//LOG("IP Port Defined!");
int len;//, len2, len3;
len = tPos2 - tPos - 2;
strncpy(tIpBuf, tPos + 2, len);
tIpBuf[len] = (char) 0;
tPort = atoi(tPos2 + 1);
// strncpy( tPath, tPos + 2 + len, CTEXT );
}
else
{
tPos2 = strstr(tPos + 2, "/");
if (tPos2 != NULL)
tH += 2;
size_t tLen = strcspn(tH, "/ \t\r\n");
if (tLen > 0 && tLen < sizeof(tIpBuf))
{ {
int len;//, len2, len3;
len = tPos2 - tPos - 2;
strncpy(tIpBuf, tPos + 2, len);
tIpBuf[len] = (char) 0;
// strncpy( tPath, tPos + 2 + len, CTEXT );
}
else
{
tPos2 = strstr(tPos + 2, "/");
//LOG_ERROR("Pos 2 - err");
tIpBuf[0] = (char) 0;
memcpy(tIpBuf, tH, tLen);
tIpBuf[tLen] = (char) 0;
char * tC = strrchr(tIpBuf, ':');
if (tC != NULL && strchr(tIpBuf, ']') == NULL) // not [IPv6]
{
*tC = (char) 0;
tPort = (uint16_t) atoi(tC + 1);
};
}; };
}; };
} }
else
if (tIpBuf[0] == (char) 0 || strchr(tIpBuf, '\'') != NULL)
{ {
//LOG_ERROR("Pos 0 - err");
tIpBuf[0] = (char) 0;
LOG_ERROR("updateIPCam: no address in the discovery result - camera not updated");
return false;
}; };
if (tPort) if (tPort)
{ {
sprintf(tQBuf, "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s', `port`=%d WHERE `id`=%d", Addr, tIpBuf, tPort, CamID);
snprintf(tQBuf, sizeof(tQBuf), "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s', `port`=%d WHERE `id`=%d", tPath, tIpBuf, tPort, CamID);
} }
else else
{ {
sprintf(tQBuf, "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s' WHERE `id`=%d", Addr, tIpBuf, CamID);
snprintf(tQBuf, sizeof(tQBuf), "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s' WHERE `id`=%d", tPath, tIpBuf, CamID);
} }
#ifdef DEBUG_ALL #ifdef DEBUG_ALL
LOG(tQBuf); LOG(tQBuf);

7
lib/App/common/deviceNode.cpp

@ -24,6 +24,7 @@ deviceNode::deviceNode(uint32_t id) :
basicEngine() basicEngine()
{ {
m_pLog = basicLogCollection::getInstance(); m_pLog = basicLogCollection::getInstance();
m_nNodeDataMisses = 0;
#ifdef USE_MYSQL #ifdef USE_MYSQL
m_pDBC = mysqlDBC::getInstance(); m_pDBC = mysqlDBC::getInstance();
#else #else
@ -58,6 +59,7 @@ deviceNode::deviceNode(DBC_NODE_DATA * Data) :
basicEngine() basicEngine()
{ {
m_pLog = basicLogCollection::getInstance(); m_pLog = basicLogCollection::getInstance();
m_nNodeDataMisses = 0;
#ifdef USE_MYSQL #ifdef USE_MYSQL
m_pDBC = mysqlDBC::getInstance(); m_pDBC = mysqlDBC::getInstance();
#else #else
@ -86,8 +88,13 @@ deviceNode::~deviceNode()
bool deviceNode::validate() bool deviceNode::validate()
{ {
DBC_NODE_DATA * tDATA = m_pDBC->getNodeData(m_sNodeData.node_id); DBC_NODE_DATA * tDATA = m_pDBC->getNodeData(m_sNodeData.node_id);
if (tDATA == NULL && ++m_nNodeDataMisses < NODE_DATA_MISSES_TO_REBUILD)
{
return true; // probably a failed read, not a deleted node: check again next time
};
if (tDATA) if (tDATA)
{ {
m_nNodeDataMisses = 0;
// Configuration only: "online" is written by every node object of this id (setNodeOnline / // Configuration only: "online" is written by every node object of this id (setNodeOnline /
// setNodeOffline) - deleting a second object of the same node made this one "changed" // setNodeOffline) - deleting a second object of the same node made this one "changed"
bool tChanged = (m_sNodeData.aux_id != tDATA->aux_id) || (m_sNodeData.aux_parameter != tDATA->aux_parameter) || (m_sNodeData.type != tDATA->type) || bool tChanged = (m_sNodeData.aux_id != tDATA->aux_id) || (m_sNodeData.aux_parameter != tDATA->aux_parameter) || (m_sNodeData.type != tDATA->type) ||

7
lib/App/common/deviceNode.h

@ -5,6 +5,12 @@
#include "../../components/base/basicEvent.h" #include "../../components/base/basicEvent.h"
#include "cmdNodeConveyor.h" #include "cmdNodeConveyor.h"
// The node record must be missing this many validations in a row before the node is deleted: a single failed
// read (SQLite busy - queries fail at once, no busy wait) deleted the node (a camera dropped its stream)
#ifndef NODE_DATA_MISSES_TO_REBUILD
#define NODE_DATA_MISSES_TO_REBUILD 3
#endif
class deviceNode : public cmdNodeConveyor, public basicEngine class deviceNode : public cmdNodeConveyor, public basicEngine
{ {
private: private:
@ -13,6 +19,7 @@ class deviceNode : public cmdNodeConveyor, public basicEngine
basicLogCollection * m_pLog; basicLogCollection * m_pLog;
dataBinder * m_pDBC; dataBinder * m_pDBC;
DBC_NODE_DATA m_sNodeData; DBC_NODE_DATA m_sNodeData;
uint8_t m_nNodeDataMisses; // validate(): node record not read N times in a row
public: public:

16
lib/App/common/deviceNode2D.cpp

@ -36,6 +36,7 @@ device2DSensor::device2DSensor(uint32_t id) :
protocolLGS_2D() protocolLGS_2D()
{ {
m_pPort = NULL; m_pPort = NULL;
m_nPortEpoch = 0;
m_bPortType = 0; m_bPortType = 0;
m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; m_bOpRetryCnt = LGS_CMD_RETRY_COUNT;
m_nProcessingCmdId = 0; m_nProcessingCmdId = 0;
@ -302,6 +303,7 @@ void device2DSensor::connectMode()
updateDataStatus(ARGUS_DS_CONNECTING); updateDataStatus(ARGUS_DS_CONNECTING);
m_bActualDeviceWM = MODE_NONE; m_bActualDeviceWM = MODE_NONE;
m_bRequestedDeviceWM = MODE_NONE; m_bRequestedDeviceWM = MODE_NONE;
m_nPortEpoch = m_pPort->getConnectEpoch();
transactionSetResult(TRANSACTION_RESULT_OK); transactionSetResult(TRANSACTION_RESULT_OK);
break; break;
}; };
@ -3302,6 +3304,20 @@ void device2DSensor::proceedDBCommands()
bool device2DSensor::validateCommunicationRessource() bool device2DSensor::validateCommunicationRessource()
{ {
/*
The transport (e.g. an Ethernet2UART gateway) reconnected since the sensor was initialised: run the
connection sequence again (MODE_DETECTOR + handshake). The sensor may have left detector mode while
the link was down; a fast reconnect was not seen here as CS_DISCONNECTED, so the sensor was only
polled in idle mode (getState2), believed to be in detector mode, and stayed "offline" until a restart.
*/
if (m_pPort != NULL && m_pPort->getConnectEpoch() != m_nPortEpoch)
{
LOG("Transport reconnected - re-initialising the sensor");
m_nPortEpoch = m_pPort->getConnectEpoch();
updateDataStatus(ARGUS_DS_DISCONNECTED);
setWM(LRF_WM_CONNECTION);
return false;
};
if (getConnectionStatus() != CS_CONNECTED) if (getConnectionStatus() != CS_CONNECTED)
{ {
#ifdef DEBUG_EXTRA #ifdef DEBUG_EXTRA

1
lib/App/common/deviceNode2D.h

@ -135,6 +135,7 @@ class device2DSensor : public deviceNodeSensor, public protocolLGS_2D
uint8_t m_bPortType; uint8_t m_bPortType;
basicTransport * m_pPort; basicTransport * m_pPort;
uint32_t m_nPortEpoch; // m_pPort->getConnectEpoch() when the sensor was (re)initialised
uint32_t m_nSleepTime; uint32_t m_nSleepTime;
uint8_t m_bInitialFlips; uint8_t m_bInitialFlips;
uint16_t m_nCurrentAngle; uint16_t m_nCurrentAngle;

179
lib/App/common/deviceNodeCamera.cpp

@ -50,6 +50,10 @@ deviceNodeCamera::deviceNodeCamera(uint32_t NodeID) :
m_sPtzHealth.state = PTZ_HEALTH_INIT; m_sPtzHealth.state = PTZ_HEALTH_INIT;
m_sPtzHealth.since = time(NULL); m_sPtzHealth.since = time(NULL);
m_tPtzLastProbe = 0; m_tPtzLastProbe = 0;
m_bPendingCamData = false;
m_bPendingProtoReinit = false;
m_bPtzEverOk = false;
memset(&m_sPendingCamData, 0, sizeof(m_sPendingCamData));
m_bNoAbsPositionning = false; m_bNoAbsPositionning = false;
m_bCameraOnHomePosition = false; m_bCameraOnHomePosition = false;
m_bCameraAIControled = false; m_bCameraAIControled = false;
@ -88,6 +92,10 @@ deviceNodeCamera::deviceNodeCamera(DBC_NODE_DATA * Data) :
m_sPtzHealth.state = PTZ_HEALTH_INIT; m_sPtzHealth.state = PTZ_HEALTH_INIT;
m_sPtzHealth.since = time(NULL); m_sPtzHealth.since = time(NULL);
m_tPtzLastProbe = 0; m_tPtzLastProbe = 0;
m_bPendingCamData = false;
m_bPendingProtoReinit = false;
m_bPtzEverOk = false;
memset(&m_sPendingCamData, 0, sizeof(m_sPendingCamData));
m_bNoAbsPositionning = false; m_bNoAbsPositionning = false;
m_bCameraOnHomePosition = false; m_bCameraOnHomePosition = false;
m_tTimeTSeconds = 0; m_tTimeTSeconds = 0;
@ -1256,6 +1264,7 @@ void deviceNodeCamera::m_fThreadProc(void)
if ((bNewSecondLoop = (cTimeSeconds != oTimeSeconds))) oTimeSeconds = cTimeSeconds; if ((bNewSecondLoop = (cTimeSeconds != oTimeSeconds))) oTimeSeconds = cTimeSeconds;
applyPendingCamData(); // settings changed in the DB that need no rebuild (validate)
uint8_t tState = getWM(); uint8_t tState = getWM();
ptzCheck(tState); ptzCheck(tState);
tState = getWM(); tState = getWM();
@ -1525,7 +1534,20 @@ void deviceNodeCamera::m_fThreadProc(void)
LOG_ERROR("No Kernel Instance!"); LOG_ERROR("No Kernel Instance!");
}; };
m_sCamData.online = true; m_sCamData.online = true;
setWM(CAM_WS_POWER_INIT);
m_mPtzHealth.lock();
bool tRecovery = m_bPtzEverOk && (m_sPtzHealth.state == PTZ_HEALTH_FAILED);
m_mPtzHealth.unlock();
if (tRecovery)
{
// The camera kept its settings: only the connection was lost - no full initialisation
// (power mode, WB, BLC, AF, home) in the middle of the work
LOG("PTZ protocol re-created - camera settings kept, back to ready");
setWM(CAM_WS_READY);
}
else
{
setWM(CAM_WS_POWER_INIT);
};
}; };
m_pDBC->updateCamOnlineStatus(m_sCamData.id, m_sCamData.online); m_pDBC->updateCamOnlineStatus(m_sCamData.id, m_sCamData.online);
if (m_sCamData.protocol == 0) if (m_sCamData.protocol == 0)
@ -1536,6 +1558,7 @@ void deviceNodeCamera::m_fThreadProc(void)
{ {
m_tPtzLastProbe = time(NULL); m_tPtzLastProbe = time(NULL);
ptzHealthSet(PTZ_HEALTH_OK); ptzHealthSet(PTZ_HEALTH_OK);
m_bPtzEverOk = true;
} }
else else
{ {
@ -1906,6 +1929,17 @@ void deviceNodeCamera::m_fThreadProc(void)
m_fCP_Tilt = m_pCurrentROI->cam_orientation.tilt; m_fCP_Tilt = m_pCurrentROI->cam_orientation.tilt;
m_fCP_Zoom = m_pCurrentROI->cam_orientation.zoom; m_fCP_Zoom = m_pCurrentROI->cam_orientation.zoom;
// Do Movement // Do Movement
{
char tB[CTEXT * 3];
snprintf(tB, sizeof(tB),
"Go to ROI (%u targets): pan=%0.6f tilt=%0.6f zoom=%0.6f (x zoom correction %0.4f = %0.6f); target fi=%0.2f tetta=%0.2f r=%0.1f; "
"camera pan model %u / %u deg, tilt model %u / %u deg",
(unsigned) m_pCurrentROI->targets.size(), m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt,
m_pCurrentROI->cam_orientation.zoom, m_fZoomCorrection, m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection,
m_pCurrentROI->cam_position.fi, m_pCurrentROI->cam_position.tetta, m_pCurrentROI->cam_position.r, (unsigned) m_sCamData.pan_model,
(unsigned) m_sCamData.pan_angles, (unsigned) m_sCamData.tilt_model, (unsigned) m_sCamData.tilt_angles);
LOG(tB);
}
if (! m_pProtocol->goAbsolute(m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt, m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection)) if (! m_pProtocol->goAbsolute(m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt, m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection))
{ {
ptzCommandFailed("goAbsolute"); ptzCommandFailed("goAbsolute");
@ -2880,6 +2914,113 @@ bool deviceNodeCamera::validateStream(void)
return true; return true;
} }
/*
Which camera fields changed (DB record a -> b)?
- runtime state written while running (online, status, session, max_range) and discovery data (uuid, mac):
ignored. Before, any difference rebuilt the node: CAM_WS_INIT set m_sCamData.online = false before
re-creating the PTZ protocol and wrote the DB only afterwards, so a validate() during a slow ONVIF
re-init deleted the camera (and dropped its video stream); so did the ONVIF discovery writing online=1.
- cosmetic (name, hardware): taken over, no action
- PTZ protocol only (onvif_ctrl, onvif_access, port, auth_mode, ptz_token): the protocol is re-created
- anything else (ip, credentials and stream_id used by the stream, type, geometry ...): node rebuilt
*/
typedef enum E_CAM_DATA_CHANGE
{
CAM_CHANGE_NONE = 0,
CAM_CHANGE_COSMETIC = 1,
CAM_CHANGE_PROTOCOL = 2,
CAM_CHANGE_NODE = 3
} CAM_DATA_CHANGE;
static CAM_DATA_CHANGE camDataChange(const DBC_CAM_DATA * a, const DBC_CAM_DATA * b, const char ** what)
{
DBC_CAM_DATA tA, tB;
memcpy(&tA, a, sizeof(tA));
memcpy(&tB, b, sizeof(tB));
*what = "";
// runtime / discovery fields: never a change
tA.online = tB.online;
tA.status = tB.status;
memcpy(tA.session, tB.session, sizeof(tA.session));
tA.max_range = tB.max_range;
memcpy(tA.uuid, tB.uuid, sizeof(tA.uuid));
memcpy(tA.mac, tB.mac, sizeof(tA.mac));
// PTZ protocol fields
bool tProto = (tA.port != tB.port) || (tA.auth_mode != tB.auth_mode) || strncmp(tA.onvif_ctrl, tB.onvif_ctrl, sizeof(tA.onvif_ctrl)) != 0 ||
strncmp(tA.onvif_access, tB.onvif_access, sizeof(tA.onvif_access)) != 0 || strncmp(tA.ptz_token, tB.ptz_token, sizeof(tA.ptz_token)) != 0;
tA.port = tB.port;
tA.auth_mode = tB.auth_mode;
memcpy(tA.onvif_ctrl, tB.onvif_ctrl, sizeof(tA.onvif_ctrl));
memcpy(tA.onvif_access, tB.onvif_access, sizeof(tA.onvif_access));
memcpy(tA.ptz_token, tB.ptz_token, sizeof(tA.ptz_token));
// cosmetic fields
bool tCosm = strncmp(tA.name, tB.name, sizeof(tA.name)) != 0 || strncmp(tA.hardware, tB.hardware, sizeof(tA.hardware)) != 0;
memcpy(tA.name, tB.name, sizeof(tA.name));
memcpy(tA.hardware, tB.hardware, sizeof(tA.hardware));
// everything else (also fields added later) needs the node rebuilt
if (memcmp(&tA, &tB, sizeof(tA)) != 0)
{
if (strncmp(a->ip, b->ip, sizeof(a->ip)) != 0)
{
*what = "ip";
}
else if (strncmp(a->username, b->username, sizeof(a->username)) != 0 || strncmp(a->password, b->password, sizeof(a->password)) != 0)
{
*what = "credentials";
}
else if (a->stream_id != b->stream_id)
{
*what = "stream";
}
else if (a->protocol != b->protocol)
{
*what = "control protocol";
}
else
{
*what = "camera parameters";
};
return CAM_CHANGE_NODE;
};
if (tProto)
{
*what = "PTZ access";
return CAM_CHANGE_PROTOCOL;
};
return tCosm ? CAM_CHANGE_COSMETIC : CAM_CHANGE_NONE;
}
// Camera thread: take over the fields validate() found changed (only cosmetic / PTZ protocol fields)
void deviceNodeCamera::applyPendingCamData(void)
{
if (! m_bPendingCamData)
{
return;
};
m_mPendingCamData.lock();
DBC_CAM_DATA * tN = &m_sPendingCamData;
memcpy(m_sCamData.name, tN->name, sizeof(m_sCamData.name));
memcpy(m_sCamData.hardware, tN->hardware, sizeof(m_sCamData.hardware));
m_sCamData.port = tN->port;
m_sCamData.auth_mode = tN->auth_mode;
memcpy(m_sCamData.onvif_ctrl, tN->onvif_ctrl, sizeof(m_sCamData.onvif_ctrl));
memcpy(m_sCamData.onvif_access, tN->onvif_access, sizeof(m_sCamData.onvif_access));
memcpy(m_sCamData.ptz_token, tN->ptz_token, sizeof(m_sCamData.ptz_token));
bool tReinit = m_bPendingProtoReinit;
m_bPendingCamData = false;
m_bPendingProtoReinit = false;
m_mPendingCamData.unlock();
if (tReinit && m_sCamData.protocol != 0)
{
LOG("PTZ access settings changed - re-initialising the PTZ protocol (camera and stream kept)");
m_mPtzHealth.lock();
m_sPtzHealth.next_retry = 0; // new settings: no back-off
m_sPtzHealth.failed_inits = 0;
m_mPtzHealth.unlock();
setWM(CAM_WS_INIT);
};
}
bool deviceNodeCamera::validate() bool deviceNodeCamera::validate()
{ {
if (m_pDBC == NULL) if (m_pDBC == NULL)
@ -2889,16 +3030,46 @@ bool deviceNodeCamera::validate()
DBC_CAM_DATA * tDATA = m_pDBC->getCamData(m_sCamData.id); DBC_CAM_DATA * tDATA = m_pDBC->getCamData(m_sCamData.id);
if (tDATA == NULL) if (tDATA == NULL)
{ {
// Probably a failed read (SQLite busy), not a deleted camera: rebuild only when it stays missing
if (++m_nNodeDataMisses < NODE_DATA_MISSES_TO_REBUILD)
{
return true;
};
LOG_ERROR("Camera record not found - rebuilding the camera");
return false; return false;
} }
if (memcmp(tDATA, &m_sCamData, sizeof(DBC_CAM_DATA)) != 0)
const char * tWhat = "";
CAM_DATA_CHANGE tChange = camDataChange(&m_sCamData, tDATA, &tWhat);
if (tChange == CAM_CHANGE_NODE)
{ {
// Settings Changed
// memcpy(&m_sCamData, tDATA, sizeof(DBC_CAM_DATA) );
char tB[128];
snprintf(tB, sizeof(tB), "Camera settings changed (%s) - rebuilding the camera", tWhat);
LOG(tB);
free(tDATA); free(tDATA);
return false; return false;
}; };
if (tChange != CAM_CHANGE_NONE)
{
m_mPendingCamData.lock();
memcpy(&m_sPendingCamData, tDATA, sizeof(DBC_CAM_DATA));
m_bPendingProtoReinit = m_bPendingProtoReinit || (tChange == CAM_CHANGE_PROTOCOL);
m_bPendingCamData = true;
m_mPendingCamData.unlock();
};
free(tDATA); free(tDATA);
// A major PTZ problem (the protocol worked, then CAM_REBUILD_AFTER_FAILED_INITS re-creations failed in a
// row: power supply / network) rebuilds the camera - the new node fully initialises it
m_mPtzHealth.lock();
bool tGiveUp = m_bPtzEverOk && (m_sPtzHealth.state == PTZ_HEALTH_FAILED) && (m_sPtzHealth.failed_inits >= CAM_REBUILD_AFTER_FAILED_INITS);
uint32_t tFails = m_sPtzHealth.failed_inits;
m_mPtzHealth.unlock();
if (tGiveUp)
{
char tB[160];
snprintf(tB, sizeof(tB), "PTZ protocol re-creation failed %u times in a row (camera power / network?) - rebuilding the camera", tFails);
LOG_ERROR(tB);
return false;
};
if (! validateStream()) if (! validateStream())
{ {
return false; return false;

20
lib/App/common/deviceNodeCamera.h

@ -130,6 +130,17 @@ typedef struct S_PTZ_HEALTH_INFO
#define CAM_PTZ_PROBE_INTERVAL_S 30 // idle liveness check of the PTZ protocol (protocolPTZ::probe) #define CAM_PTZ_PROBE_INTERVAL_S 30 // idle liveness check of the PTZ protocol (protocolPTZ::probe)
#define CAM_PTZ_RETRY_MIN_S 5 // first re-initialisation delay after a failure #define CAM_PTZ_RETRY_MIN_S 5 // first re-initialisation delay after a failure
#define CAM_PTZ_RETRY_MAX_S 60 // delay doubles per failed attempt up to this #define CAM_PTZ_RETRY_MAX_S 60 // delay doubles per failed attempt up to this
/*
PTZ trouble:
- the protocol is re-created; when it works again within a few attempts the camera goes straight back to
CAM_WS_READY (no power mode / WB / BLC / AF / home again: its settings are unchanged)
- CAM_REBUILD_AFTER_FAILED_INITS failed re-creations in a row (with the back-off 0, 5, 10 s ...) are a major
problem (camera power supply, network): the node is rebuilt and the new node fully initialises the camera.
Only for a camera whose protocol worked in this node - one that never worked keeps retrying (back-off).
*/
#ifndef CAM_REBUILD_AFTER_FAILED_INITS
#define CAM_REBUILD_AFTER_FAILED_INITS 3
#endif
typedef struct S_CAM_TASK typedef struct S_CAM_TASK
{ {
@ -207,6 +218,15 @@ class deviceNodeCamera : public deviceNode, public basicThread
void ptzCheck(uint8_t tState); void ptzCheck(uint8_t tState);
void ptzLost(const char * reason); void ptzLost(const char * reason);
void ptzCommandFailed(const char * command); void ptzCommandFailed(const char * command);
// Camera settings changed in the DB (validate, node factory thread) that need only a PTZ protocol
// re-initialisation or no action: applied by the camera thread (it owns m_sCamData)
basicMutex m_mPendingCamData;
DBC_CAM_DATA m_sPendingCamData;
volatile bool m_bPendingCamData;
volatile bool m_bPendingProtoReinit;
volatile bool m_bPtzEverOk; // the PTZ protocol worked in this node (re-creation = recovery)
void applyPendingCamData(void);
// basicTransport * m_pTransport; // basicTransport * m_pTransport;
CAM_TASK_QUEUE m_qCAM_TASK; CAM_TASK_QUEUE m_qCAM_TASK;

21
lib/App/common/deviceNodeEthernet2Serial.cpp

@ -1311,7 +1311,26 @@ int deviceETH2UART::recptBlock(unsigned char * Buffer, int * BufferLength)
{ {
if (RetVal == 0 || (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) if (RetVal == 0 || (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR))
{ {
LOG_ERROR("Peer Closes Connection!");
// Closed by the gateway (FIN) or an error - e.g. ETIMEDOUT: sent data not acknowledged
// within E2UART_TCP_USER_TIMEOUT_MS, ECONNRESET: reset by the gateway / a NAT on the way
char tWhy[96];
if (RetVal == 0)
{
snprintf(tWhy, sizeof(tWhy), "closed by the gateway");
}
else
{
snprintf(tWhy, sizeof(tWhy), "error: %s", strerror(errno));
};
char tTcp[160];
#ifdef SERIAL_PING_PONG
tcpInfoText(tTcp, sizeof(tTcp));
#else
tTcp[0] = 0;
#endif
char tB[320];
snprintf(tB, sizeof(tB), "Peer Closes Connection! (%s; %s)", tWhy, tTcp);
LOG_ERROR(tB);
shutdown(m_iDeviceFD, 2); shutdown(m_iDeviceFD, 2);
close(m_iDeviceFD); close(m_iDeviceFD);
*BufferLength = 0; *BufferLength = 0;

5
lib/App/common/deviceNodeEthernet2Serial.h

@ -121,6 +121,11 @@
{ {
return true; return true;
} }
// validated and reconnected by the node factory (deviceNode::validate) - not by the hardware manager
virtual bool selfValidating(void)
{
return true;
}
}; };
#endif #endif

4
lib/App/common/hardwareManager.cpp

@ -451,6 +451,10 @@ bool hardwareManager::validate(void)
{ {
for (VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++) for (VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++)
{ {
if ((*idx)->selfValidating())
{
continue; // its node validates / reconnects it (node factory thread)
};
if (! (*idx)->validate()) if (! (*idx)->validate())
{ {
// recreate Resource // recreate Resource

7
lib/App/common/hardwareResource.h

@ -64,6 +64,13 @@ class hardwareResource : public basicObject
virtual bool create(uint32_t id, HARDWARE_PROVIDERS type); virtual bool create(uint32_t id, HARDWARE_PROVIDERS type);
// true: the resource is validated / reconnected by its owner (e.g. a deviceNode in the node factory
// thread) - the hardware manager (kernel loop) must not do it again: a gateway connect blocked the
// kernel loop for seconds, and two threads reconnected the same object
virtual bool selfValidating(void){
return false;
}
virtual bool validate(void){ virtual bool validate(void){
return m_bValid; return m_bValid;
} }

46
lib/App/common/hardwareResourceSerialProvider.cpp

@ -229,6 +229,43 @@ bool hardwareResourceSerialProvider::pingDevice()
return RetVal; return RetVal;
} }
#include <poll.h>
// connect() bounded by timeoutMs (the socket is left in blocking mode as before). false: errno set
static bool connectWithTimeout(int fd, struct sockaddr * addr, socklen_t len, int timeoutMs)
{
int tFlags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, tFlags | O_NONBLOCK);
int tRc = connect(fd, addr, len);
if (tRc != 0 && errno == EINPROGRESS)
{
struct pollfd tPfd;
tPfd.fd = fd;
tPfd.events = POLLOUT;
do
{
tRc = poll(&tPfd, 1, timeoutMs);
}
while (tRc < 0 && errno == EINTR);
if (tRc == 0)
{
errno = ETIMEDOUT;
tRc = -1;
}
else if (tRc > 0)
{
int tErr = 0;
socklen_t tL = sizeof(tErr);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &tErr, &tL);
errno = tErr;
tRc = (tErr == 0) ? 0 : -1;
};
};
int tErrno = errno;
fcntl(fd, F_SETFL, tFlags); // back to the caller's mode in every case
errno = tErrno;
return tRc == 0;
}
bool hardwareResourceSerialProvider::create_SOL() bool hardwareResourceSerialProvider::create_SOL()
{ {
@ -392,12 +429,15 @@ bool hardwareResourceSerialProvider::create_SOL()
tServerAddr.sin_addr.s_addr = inet_addr(m_sUartData.path); tServerAddr.sin_addr.s_addr = inet_addr(m_sUartData.path);
tServerAddr.sin_port = htons(m_sUartData.port); tServerAddr.sin_port = htons(m_sUartData.port);
// connect the client socket to server socket
if (connect(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr)) != 0)
// connect the client socket to server socket - with a timeout: a blocking connect() to an address
// that does not answer took ~2 min (SYN retries) inside hardwareManager::validate() = the kernel loop
if (! connectWithTimeout(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr), SERIAL_SOL_CONNECT_TIMEOUT_MS))
{ {
char cBuffer[256]; char cBuffer[256];
sprintf(cBuffer, "ERROR connect to [%s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno));
snprintf(cBuffer, sizeof(cBuffer), "ERROR connect to [%.64s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno));
LOG_ERROR(cBuffer); LOG_ERROR(cBuffer);
close(m_iDeviceFD); // was leaked
m_iDeviceFD = -1;
return false; return false;
} }
#ifdef DEBUG #ifdef DEBUG

4
lib/App/common/hardwareResourceSerialProvider.h

@ -43,6 +43,10 @@
// #define DEBUG_SERIAL_COMMUNICATION // #define DEBUG_SERIAL_COMMUNICATION
#endif #endif
#ifndef SERIAL_SOL_CONNECT_TIMEOUT_MS
#define SERIAL_SOL_CONNECT_TIMEOUT_MS 5000 // TCP connect to an IP UART (serial over LAN / Internet)
#endif
#if defined( HALF_DUPLEX ) || defined( SERIAL_PING_PONG ) #if defined( HALF_DUPLEX ) || defined( SERIAL_PING_PONG )
class hardwareResourceSerialProvider : public hardwareResource, public basicTransport, public basicThread class hardwareResourceSerialProvider : public hardwareResource, public basicTransport, public basicThread

15
lib/App/common/kernelHelperMediaMTX.cpp

@ -28,6 +28,7 @@ kernelHelperMediaMTX::kernelHelperMediaMTX(): basicThread() {
memset( m_sAppConfigFile, 0, 512 ); memset( m_sAppConfigFile, 0, 512 );
m_nLastLogSize = 0; m_nLastLogSize = 0;
m_bRecordMode = false; m_bRecordMode = false;
m_tLastRestart = 0;
if( loadConfig() ) m_bStatus = KH_STATUS_MTX_INIT; if( loadConfig() ) m_bStatus = KH_STATUS_MTX_INIT;
} }
@ -49,8 +50,20 @@ bool kernelHelperMediaMTX::create(){
return init(); return init();
} }
/*
Called from the kernel loop (validateService, every second when the config does not validate).
"systemctl restart" waited for the service to stop and start (many seconds) - the kernel loop stalled
and the watchdog killed la_mojo. --no-block only queues the restart job; at most one restart per
KH_MTX_RESTART_MIN_S (a config that keeps failing validation restarted MediaMTX every second).
*/
bool kernelHelperMediaMTX::restart(){ bool kernelHelperMediaMTX::restart(){
int RetVal = system( "systemctl restart mediamtx.service" );
time_t tNow = time( NULL );
if ( m_tLastRestart != 0 && ( tNow - m_tLastRestart ) < KH_MTX_RESTART_MIN_S ) {
return true; // restarted a moment ago: the config is re-checked after the period
};
m_tLastRestart = tNow;
LOG( "Restart MediaMTX (queued)" );
int RetVal = system( "systemctl --no-block restart mediamtx.service" );
if ( RetVal == -1 ) return false; if ( RetVal == -1 ) return false;
return true; return true;
} }

6
lib/App/common/kernelHelperMediaMTX.h

@ -44,6 +44,11 @@ typedef std::map<uint64_t, StreamSegmentRecord *> M_StreamMap; // inodes -> info
typedef std::map<uint64_t, M_StreamMap *> M_VideoSegmentInfo; // stream_id -> map typedef std::map<uint64_t, M_StreamMap *> M_VideoSegmentInfo; // stream_id -> map
// At most one MediaMTX restart per this period (a config that keeps failing validation restarted it every second)
#ifndef KH_MTX_RESTART_MIN_S
#define KH_MTX_RESTART_MIN_S 30
#endif
class kernelHelperMediaMTX: public basicThread { class kernelHelperMediaMTX: public basicThread {
private: private:
basicLogCollection * m_pLog; basicLogCollection * m_pLog;
@ -57,6 +62,7 @@ class kernelHelperMediaMTX: public basicThread {
char m_sRecordsBase[MAX_PATH_LEN]; char m_sRecordsBase[MAX_PATH_LEN];
off_t m_nLastLogSize; off_t m_nLastLogSize;
bool m_bRecordMode; bool m_bRecordMode;
time_t m_tLastRestart; // last restart() (rate limit)
bool loadConfig(); bool loadConfig();
bool loadStreams(); bool loadStreams();
StreamSegmentRecord * createSSR( uint32_t stream_id, uint32_t streamTSS, uint32_t streamTMS, CSTR path ); StreamSegmentRecord * createSSR( uint32_t stream_id, uint32_t streamTSS, uint32_t streamTMS, CSTR path );

146
lib/App/common/kernelPrototype.cpp

@ -14,6 +14,16 @@
kernelPrototype * kernelPrototype::_instance = NULL; kernelPrototype * kernelPrototype::_instance = NULL;
#ifdef LINUX_KERNEL_WATCHDOG
#include <time.h>
static uint64_t wdNowMs(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
#endif
kernelPrototype * kernelPrototype::getInstance() kernelPrototype * kernelPrototype::getInstance()
{ {
return _instance; return _instance;
@ -25,7 +35,12 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
{ {
m_pLog = basicLogCollection::getInstance(); m_pLog = basicLogCollection::getInstance();
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
m_iWatchdogFd = -1;
m_iWatchdogFd = -1;
m_pWdThread = NULL;
m_bWdRun = false;
m_nWdProgressMs = wdNowMs();
m_nWdStepStartMs = wdNowMs();
m_pWdStep = "init";
struct sockaddr_un server_addr; struct sockaddr_un server_addr;
int connection_result; int connection_result;
@ -39,6 +54,10 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
if (connection_result == -1) if (connection_result == -1)
{ {
LOG_ERROR("WD Connection Error"); LOG_ERROR("WD Connection Error");
if (m_iWatchdogFd > -1)
{
close(m_iWatchdogFd); // was leaked
};
m_iWatchdogFd = -1; m_iWatchdogFd = -1;
}; };
if (m_iWatchdogFd < 0) if (m_iWatchdogFd < 0)
@ -61,10 +80,13 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
// LOG( (char *) ident.identity ); // LOG( (char *) ident.identity );
// LOG( ident.firmware_version ); // LOG( ident.firmware_version );
char tB[64]; char tB[64];
sprintf(tB, "%d\n", gettid());
sprintf(tB, "%d\n", (int) getpid()); // the process to kill (was gettid(): same value only in the main thread)
LOG("PID SENT TO WD!"); LOG("PID SENT TO WD!");
// ToDo: Make Error Handling here!
write(m_iWatchdogFd, &tB, strlen(tB));
// MSG_NOSIGNAL: a daemon that restarted must not kill us with SIGPIPE
if (send(m_iWatchdogFd, tB, strlen(tB), MSG_NOSIGNAL) < 0)
{
LOG_ERROR("Watchdog: PID not sent");
};
}; };
#endif #endif
m_pSettings = basicSettingsProvider::getInstance()->getSubNode(ptr, "KERNEL"); m_pSettings = basicSettingsProvider::getInstance()->getSubNode(ptr, "KERNEL");
@ -89,6 +111,7 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
kernelPrototype::~kernelPrototype() kernelPrototype::~kernelPrototype()
{ {
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
wdStop();
LOG("Closing WD!"); LOG("Closing WD!");
if (! (m_iWatchdogFd < 0)) if (! (m_iWatchdogFd < 0))
{ {
@ -98,6 +121,121 @@ kernelPrototype::~kernelPrototype()
#endif #endif
} }
#ifdef LINUX_KERNEL_WATCHDOG
bool kernelPrototype::wdSend(int64_t ms)
{
bool tOk = false;
m_mWdWrite.lock();
if (m_iWatchdogFd > -1)
{
char tB[32];
int tLen = snprintf(tB, sizeof(tB), "%lld\n", (long long) ms);
if (send(m_iWatchdogFd, tB, tLen, MSG_NOSIGNAL) == tLen)
{
tOk = true;
}
else
{
// Daemon gone (restarted / stopped): not monitored any more - and no SIGPIPE
LOG_ERROR("Watchdog connection lost - not monitored any more");
close(m_iWatchdogFd);
m_iWatchdogFd = -1;
};
};
m_mWdWrite.unlock();
return tOk;
}
void kernelPrototype::wdStep(const char * step)
{
uint64_t tNow = wdNowMs();
const char * tPrev = m_pWdStep.exchange(step);
uint64_t tTook = tNow - m_nWdStepStartMs.exchange(tNow);
m_nWdProgressMs = tNow;
if (tTook > KERNEL_WD_SLOW_STEP_MS && tPrev != NULL && strcmp(tPrev, "idle") != 0)
{
char tB[128];
snprintf(tB, sizeof(tB), "Kernel step '%s' took %llu ms", tPrev, (unsigned long long) tTook);
LOG_ERROR(tB);
};
}
void kernelPrototype::wdFeederProc(void)
{
pthread_setname_np(pthread_self(), "KernelWD");
uint64_t tLastSend = 0;
uint64_t tLastBusyLog = 0;
bool tStalled = false;
while (m_bWdRun)
{
uint64_t tNow = wdNowMs();
uint64_t tIdle = tNow - m_nWdProgressMs;
uint64_t tBusy = tNow - m_nWdStepStartMs;
const char * tStep = m_pWdStep;
if (tIdle < KERNEL_WD_STALL_MS)
{
if (tStalled)
{
LOG("Kernel loop running again - watchdog fed");
tStalled = false;
};
if (tNow - tLastSend >= 1000)
{
wdSend(KERNEL_WD_FEED_MS);
tLastSend = tNow;
};
if (tBusy >= KERNEL_WD_BUSY_LOG_MS && strcmp(tStep, "idle") != 0 && tNow - tLastBusyLog >= KERNEL_WD_BUSY_LOG_MS)
{
char tB[128];
snprintf(tB, sizeof(tB), "Kernel loop busy in '%s' for %llu s", tStep, (unsigned long long) (tBusy / 1000));
LOG_ERROR(tB);
tLastBusyLog = tNow;
};
}
else if (! tStalled)
{
// A hang: stop feeding, the daemon kills the process after the last deadline
char tB[160];
snprintf(tB, sizeof(tB), "Kernel loop stalled in '%s' for %llu s - watchdog no longer fed", tStep, (unsigned long long) (tIdle / 1000));
LOG_ERROR(tB);
tStalled = true;
};
SLEEP(100);
};
}
void kernelPrototype::wdStart(void)
{
if (m_iWatchdogFd < 0 || m_pWdThread != NULL)
{
return;
};
wdStep("start");
m_bWdRun = true;
m_pWdThread = new std::thread(&kernelPrototype::wdFeederProc, this);
}
void kernelPrototype::wdStop(void)
{
if (m_pWdThread != NULL)
{
m_bWdRun = false;
if (m_pWdThread->joinable())
{
m_pWdThread->join();
};
delete m_pWdThread;
m_pWdThread = NULL;
};
}
void kernelPrototype::wdExtend(uint32_t ms)
{
wdStop();
wdSend(ms);
}
#endif
void kernelPrototype::setWM(uint8_t mode) void kernelPrototype::setWM(uint8_t mode)
{ {
m_mWMProtector.lock(); m_mWMProtector.lock();

37
lib/App/common/kernelPrototype.h

@ -28,7 +28,26 @@
#include <linux/watchdog.h> #include <linux/watchdog.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
#include <atomic>
#include <thread>
#endif
/*
Watchdog (watchDogDaemon, UNIX socket /srv/etc/watchdog): a client sends its PID, then "N\n" = next update
within N ms; without it the daemon kills the process (signal 9), "-1" ends the monitoring.
The kernel loop fed it itself ("4000" at the start of each pass): a pass of ~3 s (gateway connect, rm -rf of
a report day, systemctl restart ...) got la_mojo killed. Now a feeder thread sends KERNEL_WD_FEED_MS every
second as long as the kernel loop reports progress (wdStep); a loop without progress for KERNEL_WD_STALL_MS
is a hang: the feeding stops (logged with the step it hangs in) and the daemon kills the process.
*/
#define KERNEL_WD_FEED_MS 4000 // deadline sent every second
#ifndef KERNEL_WD_STALL_MS
#define KERNEL_WD_STALL_MS 60000 // kernel loop without progress this long = hung
#endif #endif
#define KERNEL_WD_SLOW_STEP_MS 1000 // steps slower than this are logged
#define KERNEL_WD_BUSY_LOG_MS 5000 // a step running longer is logged every 5 s (before the kill)
#define KERNEL_WD_SHUTDOWN_MS 120000 // deadline for the kernel shutdown (deleting factories / nodes / threads)
#define EXIT_CODE_KERNEL_CLEAR 0 #define EXIT_CODE_KERNEL_CLEAR 0
#define EXIT_CODE_RELOAD_SERVICES 1 #define EXIT_CODE_RELOAD_SERVICES 1
@ -51,6 +70,24 @@ class kernelPrototype : public basicThread, public basicEventHandler
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
int m_iWatchdogFd; int m_iWatchdogFd;
private:
std::thread * m_pWdThread;
std::atomic<bool> m_bWdRun;
std::atomic<uint64_t> m_nWdProgressMs; // last wdStep()
std::atomic<uint64_t> m_nWdStepStartMs; // start of the current step
std::atomic<const char *> m_pWdStep; // current step (string literal)
basicMutex m_mWdWrite;
void wdFeederProc(void);
protected:
bool wdSend(int64_t ms); // "ms\n" to the daemon (-1 = stop monitoring); false if not connected
void wdStart(void); // start the feeder thread (the kernel loop must call wdStep())
void wdStop(void); // stop feeding (the last deadline sent stays)
void wdStep(const char * step); // kernel loop progress: a new step begins (string literal!)
void wdExtend(uint32_t ms); // stop feeding and grant ms (e.g. for the shutdown)
#endif #endif
/* basic */ /* basic */
basicLogCollection * m_pLog; basicLogCollection * m_pLog;

28
lib/App/common/streamHandler.cpp

@ -69,6 +69,9 @@ streamHandler::streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M, uint8
memset(&m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA)); memset(&m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA));
m_pSource = NULL; m_pSource = NULL;
m_nValidatorFrameCounter = 0;
m_nStallChecks = 0;
m_tLastFrameProgress = time(NULL);
m_bEvtMarkerCounter = 0; m_bEvtMarkerCounter = 0;
m_bCamMoveCounter = 0; m_bCamMoveCounter = 0;
m_bFlipMode = flip_mode; m_bFlipMode = flip_mode;
@ -3751,12 +3754,31 @@ bool streamHandler::validate(void)
{ // Frames Received from a source { // Frames Received from a source
if (m_nGlobalFrameCounter == m_nValidatorFrameCounter) if (m_nGlobalFrameCounter == m_nValidatorFrameCounter)
{ {
// Video Stalled!
LOG_ERROR("Video Stalled");
return false; // Try use System to recuperate
// No new frame since the last validation: restart only when it lasts (STREAM_STALL_CHECKS)
char tB[128];
long tSec = (long) (time(NULL) - m_tLastFrameProgress);
if (++m_nStallChecks < STREAM_STALL_CHECKS)
{
snprintf(tB, sizeof(tB), "Video: no new frame for %ld s (%u/%u)", tSec, (unsigned) m_nStallChecks, (unsigned) STREAM_STALL_CHECKS);
LOG(tB);
}
else
{
snprintf(tB, sizeof(tB), "Video Stalled (no frame for %ld s) - restarting the stream", tSec);
LOG_ERROR(tB);
return false; // Try use System to recuperate
};
} }
else else
{ {
if (m_nStallChecks)
{
char tB[96];
snprintf(tB, sizeof(tB), "Video: frames again after %ld s", (long) (time(NULL) - m_tLastFrameProgress));
LOG(tB);
};
m_nStallChecks = 0;
m_tLastFrameProgress = time(NULL);
m_nValidatorFrameCounter = m_nGlobalFrameCounter; m_nValidatorFrameCounter = m_nGlobalFrameCounter;
} }
}; };

8
lib/App/common/streamHandler.h

@ -27,6 +27,12 @@
//Predefine Classess //Predefine Classess
class kernelModuleEmbedVideo; class kernelModuleEmbedVideo;
// A stream is restarted only after this many validations in a row (module factory: every ~5 s) without a
// new frame. One gap of ~5 s (a camera on a mobile link) restarted the stream and cut the recording.
#ifndef STREAM_STALL_CHECKS
#define STREAM_STALL_CHECKS 3
#endif
class streamHandler; class streamHandler;
#define FILESTREAMBUFFERSZ 1048576 #define FILESTREAMBUFFERSZ 1048576
@ -241,6 +247,8 @@ class streamHandler :
basicMutex m_mFrameCounterProtector; basicMutex m_mFrameCounterProtector;
uint64_t m_nGlobalFrameCounter; uint64_t m_nGlobalFrameCounter;
uint64_t m_nValidatorFrameCounter; uint64_t m_nValidatorFrameCounter;
uint8_t m_nStallChecks; // validate() calls in a row without a new frame
time_t m_tLastFrameProgress; // last validate() that saw new frames
#ifndef EVE_SEQUENTAL_OUTPUT #ifndef EVE_SEQUENTAL_OUTPUT
uint32_t m_nSegAFrameCounter; uint32_t m_nSegAFrameCounter;
uint32_t m_nSegBFrameCounter; uint32_t m_nSegBFrameCounter;

3
lib/App/common/targetPipeLine.cpp

@ -122,7 +122,7 @@ bool targetPipeLine::inject( kernelEventFilter *instance, TARGET_DATA * tData ){
if ( (*idx) == instance ) { if ( (*idx) == instance ) {
DownStreamFilter = true; DownStreamFilter = true;
} else { } else {
if ( DownstreamFilter ) {
if ( DownStreamFilter ) {
if ((*idx)->isActive()) { if ((*idx)->isActive()) {
if ((*idx)->validateTarget(m_nNodeId, tData)){ if ((*idx)->validateTarget(m_nNodeId, tData)){
propogateTarget = false; propogateTarget = false;
@ -159,7 +159,6 @@ bool targetPipeLine::inject( kernelEventFilter *instance, TARGET_DATA * tData ){
#endif #endif
free(tData); free(tData);
}; };
};
return false; return false;
} }

3
lib/App/common/targetPipeLine.h

@ -37,8 +37,7 @@ class targetPipeLine : public basicThread
explicit targetPipeLine(uint32_t node_id, uint32_t bind_cam_id = 0); explicit targetPipeLine(uint32_t node_id, uint32_t bind_cam_id = 0);
virtual ~targetPipeLine(); virtual ~targetPipeLine();
bool push( TARGET_DATA * ptr ); bool push( TARGET_DATA * ptr );
friend:
class kernelEventFilter;
friend class kernelEventFilter;
}; };
#endif #endif

41
lib/App/mojo/mojoKernel.cpp

@ -100,6 +100,11 @@ mojoKernel::mojoKernel(config_setting_t * ptr) :
mojoKernel::~mojoKernel() mojoKernel::~mojoKernel()
{ {
#ifdef LINUX_KERNEL_WATCHDOG
// Deleting the factories / nodes / threads takes longer than one feed period: grant the shutdown its
// own deadline instead of the last 4 s (the daemon killed la_mojo in the middle of a reload / exit)
wdExtend(KERNEL_WD_SHUTDOWN_MS);
#endif
WaitFinish(true); WaitFinish(true);
stopSession(false); stopSession(false);
@ -183,13 +188,7 @@ mojoKernel::~mojoKernel()
} }
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
LOG("Disable WD!"); LOG("Disable WD!");
if (m_iWatchdogFd > -1)
{
char tB[64];
sprintf(tB, "-1\n");
// ToDo: Make Error Handling here!
write(m_iWatchdogFd, &tB, strlen(tB));
};
wdSend(-1); // MSG_NOSIGNAL: no SIGPIPE if the daemon is gone
LOG("WatchDog turned Off!"); LOG("WatchDog turned Off!");
#endif #endif
// Events broadcast while the components were deleted must not reach the next kernel (restart) // Events broadcast while the components were deleted must not reach the next kernel (restart)
@ -786,7 +785,14 @@ void mojoKernel::m_fThreadProc(void){
time_t tTimeTSeconds = 0; time_t tTimeTSeconds = 0;
m_bThreadStatus = TH_WORKING; m_bThreadStatus = TH_WORKING;
pthread_setname_np( pthread_self(), "Kernel" ); pthread_setname_np( pthread_self(), "Kernel" );
#ifdef LINUX_KERNEL_WATCHDOG
wdStart(); // the watchdog is fed by its own thread while this loop reports progress (wdStep)
#define KWD_STEP(X) wdStep(X)
#else
#define KWD_STEP(X)
#endif
while (m_bThreadStatus < TH_ENDED){ while (m_bThreadStatus < TH_ENDED){
KWD_STEP("idle");
m_tTimeTSeconds = time(NULL); m_tTimeTSeconds = time(NULL);
// Each Second // Each Second
if (m_tTimeTSeconds != tTimeTSeconds){ if (m_tTimeTSeconds != tTimeTSeconds){
@ -800,34 +806,33 @@ void mojoKernel::m_fThreadProc(void){
continue; continue;
}; };
}; };
#ifdef LINUX_KERNEL_WATCHDOG
if (m_iWatchdogFd > -1){
char tB[64];
sprintf(tB, "4000\n");
// ToDo: Make Error Handling here!
write(m_iWatchdogFd, &tB, strlen(tB));
};
#endif
KWD_STEP("debug mode");
m_bDebugMode = m_pDBC->getAppDebugMode(); m_bDebugMode = m_pDBC->getAppDebugMode();
KWD_STEP("validateFilters");
validateFilters(); validateFilters();
KWD_STEP("validateSession");
validateSession(); validateSession();
KWD_STEP("validateReports");
validateReports(); validateReports();
//??
KWD_STEP("hardwareManager::validate");
if (! m_pHardwareManager->validate()){ if (! m_pHardwareManager->validate()){
LOG("Reload Mojo Node Due to Memory Consumption!"); LOG("Reload Mojo Node Due to Memory Consumption!");
m_bThreadStatus = TH_ENDED; m_bThreadStatus = TH_ENDED;
setExitCause(EXIT_CODE_KERNEL_CLEAR); setExitCause(EXIT_CODE_KERNEL_CLEAR);
continue; continue;
}; };
KWD_STEP("updateSysInfo");
m_mSysInfoProtector.lock(); m_mSysInfoProtector.lock();
m_pHardwareManager->updateSysInfo(&m_sSysInfo); m_pHardwareManager->updateSysInfo(&m_sSysInfo);
m_mSysInfoProtector.unlock(); m_mSysInfoProtector.unlock();
#ifndef LRF_PROXY_ONLY #ifndef LRF_PROXY_ONLY
if ( m_pMediaHelper ) { if ( m_pMediaHelper ) {
KWD_STEP("mediaHelper::validateService");
m_pMediaHelper->validateService(); m_pMediaHelper->validateService();
}; };
#endif #endif
KWD_STEP("remote server");
if (m_sSiteData.use_remote_server){ if (m_sSiteData.use_remote_server){
if (m_pRPC){ if (m_pRPC){
m_pRPC->validate(); m_pRPC->validate();
@ -848,6 +853,7 @@ void mojoKernel::m_fThreadProc(void){
}; };
}; };
}; };
KWD_STEP("kernel commands");
DBC_PUSHED_CMD * tCMD = m_pDBC->getNodePushedCMD(m_nServerNodeID); // Kernel DBC_PUSHED_CMD * tCMD = m_pDBC->getNodePushedCMD(m_nServerNodeID); // Kernel
if (tCMD != NULL) { if (tCMD != NULL) {
m_pDBC->updateNodePushedCMD(tCMD->id, DBC_CMD_STARTED); m_pDBC->updateNodePushedCMD(tCMD->id, DBC_CMD_STARTED);
@ -1030,11 +1036,14 @@ void mojoKernel::m_fThreadProc(void){
free(tCMD); free(tCMD);
}; };
if ( m_pDBC ){ if ( m_pDBC ){
KWD_STEP("cleanNodePushedCMD");
m_pDBC->cleanNodePushedCMD(); m_pDBC->cleanNodePushedCMD();
} }
}; };
SLEEP(SLEEP_KERNEL_INTERVAL); SLEEP(SLEEP_KERNEL_INTERVAL);
}; };
KWD_STEP("exit"); // the destructor grants the shutdown its own deadline (wdExtend)
#undef KWD_STEP
} }
void mojoKernel::loadFilters() void mojoKernel::loadFilters()

17
lib/alg/generic/Transform.cpp

@ -141,6 +141,16 @@ void spherical2onvif(C3D_SPH_DEGREES in, C3D_ORIENT_ONVIF & out, float maxR, uin
out.zoom = .0f; out.zoom = .0f;
} }
// Endless pan: the azimuth may come as -180..180 or above 360, bring it into 0..360
if (panAngles >= 360.0f)
{
in.fi = fmodf(in.fi, 360.0f);
if (in.fi < 0.0f)
{
in.fi += 360.0f;
};
};
switch (panMode) switch (panMode)
{ {
case 1: case 1:
@ -174,6 +184,13 @@ void spherical2onvif(C3D_SPH_DEGREES in, C3D_ORIENT_ONVIF & out, float maxR, uin
break; break;
}; };
}; };
// A target is accepted up to half a field of view outside the mechanical range (isInRange), and a camera
// that can tilt 90 degrees accepts any elevation: the camera must then go to its end position, where the
// target is still in the picture. A value outside -1..1 (generic ONVIF space) is rejected by the camera
// with ter:InvalidPosition ("The requested destination is out of bounds").
out.pan = (out.pan < -1.0f) ? -1.0f : ((out.pan > 1.0f) ? 1.0f : out.pan);
out.tilt = (out.tilt < -1.0f) ? -1.0f : ((out.tilt > 1.0f) ? 1.0f : out.tilt);
out.zoom = (out.zoom < 0.0f) ? 0.0f : ((out.zoom > 1.0f) ? 1.0f : out.zoom);
} }
void spherical2onvif(C3D_SPH_RADIANS inr, C3D_ORIENT_ONVIF & out, float maxR, uint8_t panMode, float panAngles, uint8_t tiltMode, float tiltAngles) void spherical2onvif(C3D_SPH_RADIANS inr, C3D_ORIENT_ONVIF & out, float maxR, uint8_t panMode, float panAngles, uint8_t tiltMode, float tiltAngles)

5
lib/components/base/basicTransport.cpp

@ -11,6 +11,7 @@ basicTransport::basicTransport() :
{ {
m_pLog = basicLogCollection::getInstance(); m_pLog = basicLogCollection::getInstance();
m_eConnectionStatus = CS_UNKNOWN; m_eConnectionStatus = CS_UNKNOWN;
m_nConnectEpoch = 0;
} }
basicTransport::~basicTransport() basicTransport::~basicTransport()
@ -48,6 +49,10 @@ bool basicTransport::removeRecipient(protocolParser * ProtoParser)
void basicTransport::setConnectionStatus(CONNECTION_STATUS CS) void basicTransport::setConnectionStatus(CONNECTION_STATUS CS)
{ {
m_mQueueProtectorMutex.lock(); m_mQueueProtectorMutex.lock();
if (CS == CS_CONNECTED && m_eConnectionStatus != CS_CONNECTED)
{
m_nConnectEpoch = m_nConnectEpoch + 1;
};
m_eConnectionStatus = CS; m_eConnectionStatus = CS;
for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++) for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++)
{ {

7
lib/components/base/basicTransport.h

@ -57,6 +57,7 @@ class basicTransport
basicMutex m_mBufferProtectorMutex; basicMutex m_mBufferProtectorMutex;
CONNECTION_STATUS m_eConnectionStatus; CONNECTION_STATUS m_eConnectionStatus;
volatile uint32_t m_nConnectEpoch; // +1 on every change to CS_CONNECTED (a reconnect)
public: public:
@ -93,6 +94,12 @@ class basicTransport
} }
void setConnectionStatus(CONNECTION_STATUS ES); void setConnectionStatus(CONNECTION_STATUS ES);
// Changes on every (re)connect: a user bound to this transport sees a reconnect it did not notice
// as a short CS_DISCONNECTED (a device behind it may have lost its state meanwhile)
uint32_t getConnectEpoch(void)
{
return m_nConnectEpoch;
}
CONNECTION_STATUS getConnectionStatus(void); CONNECTION_STATUS getConnectionStatus(void);
virtual int getRawHandle(void) virtual int getRawHandle(void)

195
lib/data/ponvif/ponvif.cpp

@ -1647,6 +1647,8 @@ bool pOnvif::media_GetVideoSources(void)
return false; return false;
} }
static bool readPtzRange(XMLNode & node, ptzRange * out);
bool pOnvif::media_GetProfiles(void) bool pOnvif::media_GetProfiles(void)
{ {
char tBuffer[DEFAULT_BUFFER_SIZE]; char tBuffer[DEFAULT_BUFFER_SIZE];
@ -1737,6 +1739,16 @@ bool pOnvif::media_GetProfiles(void)
{ {
tPtr->ptz = true; tPtr->ptz = true;
safeCopy(tPtr->ptznodetoken, sizeof(tPtr->ptznodetoken), nNode.getChildNode("NodeToken", 0).getText(0)); safeCopy(tPtr->ptznodetoken, sizeof(tPtr->ptznodetoken), nNode.getChildNode("NodeToken", 0).getText(0));
safeCopy(tPtr->ptzdefaultptspace, sizeof(tPtr->ptzdefaultptspace), nNode.getChildNode("DefaultAbsolutePantTiltPositionSpace", 0).getText(0));
safeCopy(tPtr->ptzdefaultzoomspace, sizeof(tPtr->ptzdefaultzoomspace), nNode.getChildNode("DefaultAbsoluteZoomPositionSpace", 0).getText(0));
{
XMLNode tL = nNode.getChildNode("PanTiltLimits", 0).getChildNode("Range", 0);
readPtzRange(tL, &tPtr->ptzpantiltlimits);
}
{
XMLNode tL = nNode.getChildNode("ZoomLimits", 0).getChildNode("Range", 0);
readPtzRange(tL, &tPtr->ptzzoomlimits);
}
}; };
} }
m_vVideoProfiles.push_back(tPtr); m_vVideoProfiles.push_back(tPtr);
@ -2059,6 +2071,95 @@ void pOnvif::setGenericSpeedSpaces(void)
safeCopy(m_sPanTiltSpeedSpace.uri, sizeof(m_sPanTiltSpeedSpace.uri), PONVIF_SPACE_PT_GENERIC_SPEED); safeCopy(m_sPanTiltSpeedSpace.uri, sizeof(m_sPanTiltSpeedSpace.uri), PONVIF_SPACE_PT_GENERIC_SPEED);
safeCopy(m_sZoomSpeedSpace.uri, sizeof(m_sZoomSpeedSpace.uri), PONVIF_SPACE_ZOOM_GENERIC_SPEED); safeCopy(m_sZoomSpeedSpace.uri, sizeof(m_sZoomSpeedSpace.uri), PONVIF_SPACE_ZOOM_GENERIC_SPEED);
m_sPanTiltSpeedSpace.max = m_sZoomSpeedSpace.max = 1.0f; m_sPanTiltSpeedSpace.max = m_sZoomSpeedSpace.max = 1.0f;
memset(&m_sPanTiltPosSpace, 0, sizeof(m_sPanTiltPosSpace));
memset(&m_sZoomPosSpace, 0, sizeof(m_sZoomPosSpace));
}
/*
Reads a <...> element with <URI>, <XRange><Min/Max></XRange> and optional <YRange> (a node's position space
or the Range of a PTZConfiguration's PanTiltLimits / ZoomLimits).
*/
static bool readPtzRange(XMLNode & node, ptzRange * out)
{
memset(out, 0, sizeof(ptzRange));
if (node.isEmpty())
{
return false;
};
LPCTSTR tUri = node.getChildNode("URI", 0).getText(0);
if (tUri != NULL)
{
safeCopy(out->uri, sizeof(out->uri), tUri);
};
XMLNode tX = node.getChildNode("XRange", 0);
LPCTSTR tXMin = tX.getChildNode("Min", 0).getText(0);
LPCTSTR tXMax = tX.getChildNode("Max", 0).getText(0);
if (tXMin == NULL || tXMax == NULL)
{
return false;
};
out->xmin = (float) atof(tXMin);
out->xmax = (float) atof(tXMax);
XMLNode tY = node.getChildNode("YRange", 0);
LPCTSTR tYMin = tY.getChildNode("Min", 0).getText(0);
LPCTSTR tYMax = tY.getChildNode("Max", 0).getText(0);
if (tYMin != NULL && tYMax != NULL)
{
out->ymin = (float) atof(tYMin);
out->ymax = (float) atof(tYMax);
out->hasY = true;
};
out->valid = true;
return true;
}
// The position space of the node: the generic one if offered, otherwise the first one
static void pickPositionSpace(XMLNode & spaces, LPCTSTR name, LPCTSTR genericUri, ptzRange * out)
{
memset(out, 0, sizeof(ptzRange));
for (int i = 0;; i++)
{
XMLNode tSpace = spaces.getChildNode(name, i);
if (tSpace.isEmpty())
{
break;
};
ptzRange tR;
if (! readPtzRange(tSpace, &tR))
{
continue;
};
if (! out->valid || strcmp(tR.uri, genericUri) == 0)
{
*out = tR;
};
if (strcmp(tR.uri, genericUri) == 0)
{
break;
};
};
}
static void ptzRangeText(char * buf, size_t size, const ptzRange & r)
{
if (! r.valid)
{
snprintf(buf, size, "n/a");
}
else if (r.hasY)
{
snprintf(buf, size, "x [%.4f .. %.4f] y [%.4f .. %.4f] (%.100s)", r.xmin, r.xmax, r.ymin, r.ymax, r.uri);
}
else
{
snprintf(buf, size, "[%.4f .. %.4f] (%.100s)", r.xmin, r.xmax, r.uri);
};
}
// Small tolerance: values read back from the device are printed with limited precision
static bool ptzInRange(float v, float vmin, float vmax)
{
return (v >= vmin - 0.0001f) && (v <= vmax + 0.0001f);
} }
/* /*
@ -2139,6 +2240,8 @@ bool pOnvif::ptz_GetNode(CSTR ptzNodeToken)
}; };
bool tPT = pickSpeedSpace(tSpaces, "PanTiltSpeedSpace", PONVIF_SPACE_PT_GENERIC_SPEED, &m_sPanTiltSpeedSpace); bool tPT = pickSpeedSpace(tSpaces, "PanTiltSpeedSpace", PONVIF_SPACE_PT_GENERIC_SPEED, &m_sPanTiltSpeedSpace);
bool tZM = pickSpeedSpace(tSpaces, "ZoomSpeedSpace", PONVIF_SPACE_ZOOM_GENERIC_SPEED, &m_sZoomSpeedSpace); bool tZM = pickSpeedSpace(tSpaces, "ZoomSpeedSpace", PONVIF_SPACE_ZOOM_GENERIC_SPEED, &m_sZoomSpeedSpace);
pickPositionSpace(tSpaces, "AbsolutePanTiltPositionSpace", PONVIF_SPACE_PT_GENERIC_POS, &m_sPanTiltPosSpace);
pickPositionSpace(tSpaces, "AbsoluteZoomPositionSpace", PONVIF_SPACE_ZOOM_GENERIC_POS, &m_sZoomPosSpace);
return tPT || tZM; return tPT || tZM;
} }
@ -2208,11 +2311,99 @@ bool pOnvif::ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float
// The generic pan/tilt speed is a scalar (x); y is sent with the same value for devices reading it. // The generic pan/tilt speed is a scalar (x); y is sent with the same value for devices reading it.
float tPT = (speed < 0.0f) ? m_sPanTiltSpeedSpace.max : m_sPanTiltSpeedSpace.min + speed * (m_sPanTiltSpeedSpace.max - m_sPanTiltSpeedSpace.min); float tPT = (speed < 0.0f) ? m_sPanTiltSpeedSpace.max : m_sPanTiltSpeedSpace.min + speed * (m_sPanTiltSpeedSpace.max - m_sPanTiltSpeedSpace.min);
float tZM = (speed < 0.0f) ? m_sZoomSpeedSpace.max : m_sZoomSpeedSpace.min + speed * (m_sZoomSpeedSpace.max - m_sZoomSpeedSpace.min); float tZM = (speed < 0.0f) ? m_sZoomSpeedSpace.max : m_sZoomSpeedSpace.min + speed * (m_sZoomSpeedSpace.max - m_sZoomSpeedSpace.min);
char tBuffer[DEFAULT_BUFFER_SIZE];
// Limits that apply to this move: the profile's PTZConfiguration limits, else the node's position spaces
const videoSourceProfile * tProfile = NULL;
for (size_t i = 0; i < m_vVideoProfiles.size(); i++)
{
if (m_vVideoProfiles[i] != NULL && strcmp(m_vVideoProfiles[i]->profiletoken, profileToken) == 0)
{
tProfile = m_vVideoProfiles[i];
break;
};
};
const ptzRange & tPTR = (tProfile != NULL && tProfile->ptzpantiltlimits.valid) ? tProfile->ptzpantiltlimits : m_sPanTiltPosSpace;
const ptzRange & tZR = (tProfile != NULL && tProfile->ptzzoomlimits.valid) ? tProfile->ptzzoomlimits : m_sZoomPosSpace;
char tOut[64];
tOut[0] = (char) 0;
int tLen = 0;
if (tPTR.valid && ! ptzInRange(position_pantilt_x, tPTR.xmin, tPTR.xmax))
{
tLen += snprintf(tOut + tLen, sizeof(tOut) - tLen, " PAN");
};
if (tPTR.valid && tPTR.hasY && ! ptzInRange(position_pantilt_y, tPTR.ymin, tPTR.ymax) && tLen < (int) sizeof(tOut))
{
tLen += snprintf(tOut + tLen, sizeof(tOut) - tLen, " TILT");
};
if (tZR.valid && ! ptzInRange(zoom, tZR.xmin, tZR.xmax) && tLen < (int) sizeof(tOut))
{
tLen += snprintf(tOut + tLen, sizeof(tOut) - tLen, " ZOOM");
};
if (tOut[0] != 0)
{
char tB[CTEXT * 2];
snprintf(tB, sizeof(tB), "AbsoluteMove pan=%0.6f tilt=%0.6f zoom=%0.6f: OUT OF CAMERA LIMITS:%s - clamped to the limits", position_pantilt_x, position_pantilt_y,
zoom, tOut);
LOG_ERROR(tB);
if (tPTR.valid)
{
position_pantilt_x = (position_pantilt_x < tPTR.xmin) ? tPTR.xmin : ((position_pantilt_x > tPTR.xmax) ? tPTR.xmax : position_pantilt_x);
if (tPTR.hasY)
{
position_pantilt_y = (position_pantilt_y < tPTR.ymin) ? tPTR.ymin : ((position_pantilt_y > tPTR.ymax) ? tPTR.ymax : position_pantilt_y);
};
};
if (tZR.valid)
{
zoom = (zoom < tZR.xmin) ? tZR.xmin : ((zoom > tZR.xmax) ? tZR.xmax : zoom);
};
};
char tMove[CTEXT * 2];
snprintf(tMove, sizeof(tMove), "AbsoluteMove pan=%0.6f tilt=%0.6f zoom=%0.6f (speed pt=%0.4f zoom=%0.4f)", position_pantilt_x, position_pantilt_y, zoom, tPT, tZM);
#ifdef DEBUG_PONVIF_PTZ
LOG(tMove);
#endif
char tBuffer[DEFAULT_BUFFER_SIZE];
_buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_ABSOLUTE_MOVE, xesc(profileToken).c_str(), position_pantilt_x, position_pantilt_y, zoom, tPT, tPT, _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_ABSOLUTE_MOVE, xesc(profileToken).c_str(), position_pantilt_x, position_pantilt_y, zoom, tPT, tPT,
xesc(m_sPanTiltSpeedSpace.uri).c_str(), tZM, xesc(m_sZoomSpeedSpace.uri).c_str()); xesc(m_sPanTiltSpeedSpace.uri).c_str(), tZM, xesc(m_sZoomSpeedSpace.uri).c_str());
// Wait for the answer so that a SOAP Fault (e.g. position out of range) is detected // Wait for the answer so that a SOAP Fault (e.g. position out of range) is detected
return _send_request(m_pPTZURI, tBuffer, true);
bool tOk = _send_request(m_pPTZURI, tBuffer, true);
if (! tOk)
{
char tB[CTEXT * 4];
snprintf(tB, sizeof(tB), "%s REJECTED (%s)", tMove, (m_cLastFault[0] != 0) ? m_cLastFault : "no answer");
LOG_ERROR(tB);
if (m_eLastError == PONVIF_ERR_FAULT)
{
ptz_LogRanges(profileToken);
};
};
return tOk;
}
void pOnvif::ptz_LogRanges(CSTR profileToken)
{
char tR1[CTEXT * 2];
char tR2[CTEXT * 2];
char tB[CTEXT * 6];
ptzRangeText(tR1, sizeof(tR1), m_sPanTiltPosSpace);
ptzRangeText(tR2, sizeof(tR2), m_sZoomPosSpace);
snprintf(tB, sizeof(tB), "PTZ node position space: PanTilt %s, Zoom %s", tR1, tR2);
LOG(tB);
for (size_t i = 0; i < m_vVideoProfiles.size(); i++)
{
const videoSourceProfile * tP = m_vVideoProfiles[i];
if (tP == NULL || ! tP->ptz || (profileToken != NULL && strcmp(tP->profiletoken, profileToken) != 0))
{
continue;
};
ptzRangeText(tR1, sizeof(tR1), tP->ptzpantiltlimits);
ptzRangeText(tR2, sizeof(tR2), tP->ptzzoomlimits);
snprintf(tB, sizeof(tB), "PTZ profile %.60s limits: PanTilt %s, Zoom %s", tP->profiletoken, tR1, tR2);
LOG(tB);
snprintf(tB, sizeof(tB), "PTZ profile %.60s default spaces: PanTilt %.120s, Zoom %.120s (the PanTilt position is sent without a space)", tP->profiletoken,
tP->ptzdefaultptspace[0] ? tP->ptzdefaultptspace : "n/a", tP->ptzdefaultzoomspace[0] ? tP->ptzdefaultzoomspace : "n/a");
LOG(tB);
};
} }
bool pOnvif::ptz_ContinuousMove(CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y) bool pOnvif::ptz_ContinuousMove(CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y)

36
lib/data/ponvif/ponvif.h

@ -80,6 +80,10 @@
// the PTZConfiguration's DefaultPTZSpeed): there "1" can be a slow speed. // the PTZConfiguration's DefaultPTZSpeed): there "1" can be a slow speed.
#define PONVIF_SPACE_PT_GENERIC_SPEED "http://www.onvif.org/ver10/tptz/PanTiltSpaces/GenericSpeedSpace" #define PONVIF_SPACE_PT_GENERIC_SPEED "http://www.onvif.org/ver10/tptz/PanTiltSpaces/GenericSpeedSpace"
#define PONVIF_SPACE_ZOOM_GENERIC_SPEED "http://www.onvif.org/ver10/tptz/ZoomSpaces/ZoomGenericSpeedSpace" #define PONVIF_SPACE_ZOOM_GENERIC_SPEED "http://www.onvif.org/ver10/tptz/ZoomSpaces/ZoomGenericSpeedSpace"
#define PONVIF_SPACE_PT_GENERIC_POS "http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace"
#define PONVIF_SPACE_ZOOM_GENERIC_POS "http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace"
// Log every AbsoluteMove with its coordinates (a rejected move is always logged with them)
#define DEBUG_PONVIF_PTZ
// ContinuousMove is assembled from these parts (pan/tilt and zoom in one request) // ContinuousMove is assembled from these parts (pan/tilt and zoom in one request)
#define PONVIF_BODY_CONTINUOUS_MOVE_BEGIN "<ContinuousMove xmlns=\"" PONVIF_NS_PTZ "\"><ProfileToken>%s</ProfileToken><Velocity>" #define PONVIF_BODY_CONTINUOUS_MOVE_BEGIN "<ContinuousMove xmlns=\"" PONVIF_NS_PTZ "\"><ProfileToken>%s</ProfileToken><Velocity>"
#define PONVIF_BODY_CONTINUOUS_MOVE_PT \ #define PONVIF_BODY_CONTINUOUS_MOVE_PT \
@ -107,6 +111,18 @@
#define PONVIF_PCK_GET_CAPABILITIES (CSTR) "<GetCapabilities xmlns=\"http://www.onvif.org/ver10/device/wsdl\"><Category>All</Category></GetCapabilities>" #define PONVIF_PCK_GET_CAPABILITIES (CSTR) "<GetCapabilities xmlns=\"http://www.onvif.org/ver10/device/wsdl\"><Category>All</Category></GetCapabilities>"
// A position range of the PTZ node or a PTZConfiguration limit (URI + X range, Y range for pan/tilt)
typedef struct S_ptzRange
{
char uri[CTEXT];
float xmin;
float xmax;
float ymin;
float ymax;
bool hasY;
bool valid; // read from the device
} ptzRange;
typedef struct S_videoSourceProfile typedef struct S_videoSourceProfile
{ {
char sourcetoken[CTEXT]; char sourcetoken[CTEXT];
@ -119,6 +135,12 @@ typedef struct S_videoSourceProfile
int bitrate; int bitrate;
bool ptz; // profile has a PTZConfiguration (PTZ commands need such a profile) bool ptz; // profile has a PTZConfiguration (PTZ commands need such a profile)
char ptznodetoken[CTEXT]; // PTZConfiguration/NodeToken char ptznodetoken[CTEXT]; // PTZConfiguration/NodeToken
// PTZConfiguration: default absolute position spaces (used when a Position has no space attribute)
// and the configured limits (a move outside them is answered with ter:InvalidPosition)
char ptzdefaultptspace[CTEXT];
char ptzdefaultzoomspace[CTEXT];
ptzRange ptzpantiltlimits;
ptzRange ptzzoomlimits;
} videoSourceProfile; } videoSourceProfile;
// A speed space of the PTZ node (GetNode -> SupportedPTZSpaces/PanTiltSpeedSpace | ZoomSpeedSpace) // A speed space of the PTZ node (GetNode -> SupportedPTZSpaces/PanTiltSpeedSpace | ZoomSpeedSpace)
@ -561,6 +583,8 @@ class pOnvif
char m_cLastFault[CTEXT]; char m_cLastFault[CTEXT];
ptzSpeedSpace m_sPanTiltSpeedSpace; // speed space used for AbsoluteMove (generic 0..1 by default) ptzSpeedSpace m_sPanTiltSpeedSpace; // speed space used for AbsoluteMove (generic 0..1 by default)
ptzSpeedSpace m_sZoomSpeedSpace; ptzSpeedSpace m_sZoomSpeedSpace;
ptzRange m_sPanTiltPosSpace; // node: absolute pan/tilt position space (generic one if offered)
ptzRange m_sZoomPosSpace; // node: absolute zoom position space
#ifndef CURL_MANAGER #ifndef CURL_MANAGER
static int _writer(char * data, size_t size, size_t nmemb, pOnvif * Ptr); static int _writer(char * data, size_t size, size_t nmemb, pOnvif * Ptr);
#endif #endif
@ -634,6 +658,18 @@ class pOnvif
{ {
return m_sZoomSpeedSpace; return m_sZoomSpeedSpace;
} }
const ptzRange & getPanTiltPositionSpace(void) const
{
return m_sPanTiltPosSpace;
}
const ptzRange & getZoomPositionSpace(void) const
{
return m_sZoomPosSpace;
}
// Logs the position spaces of the node and the limits of the profile (debug of out-of-bounds moves)
void ptz_LogRanges(CSTR profileToken);
bool ptz_GetStatus(CSTR profileToken, ptzStatus * tStatus); bool ptz_GetStatus(CSTR profileToken, ptzStatus * tStatus);
// PTZ service capabilities (ONVIF PTZ GetServiceCapabilities). // PTZ service capabilities (ONVIF PTZ GetServiceCapabilities).
// Each output is 1 = supported, 0 = not supported, -1 = not reported by the device. // Each output is 1 = supported, 0 = not supported, -1 = not reported by the device.

2
lib/data/protocol/protocolPTZ_ONVIF.cpp

@ -226,6 +226,8 @@ bool protocolPTZ_ONVIF::create(void)
snprintf(tB, sizeof(tB), "PTZ speed (%s): PanTilt %.120s max %.3f, Zoom %.120s max %.3f", tRead ? "from node" : "generic default", tPT.uri, tPT.max, tZM.uri, tZM.max); snprintf(tB, sizeof(tB), "PTZ speed (%s): PanTilt %.120s max %.3f, Zoom %.120s max %.3f", tRead ? "from node" : "generic default", tPT.uri, tPT.max, tZM.uri, tZM.max);
LOG(tB); LOG(tB);
} }
// Camera ranges, to compare with the coordinates of the AbsoluteMove requests
m_pOnVif->ptz_LogRanges(m_pProfile->profiletoken);
LOG("DONE"); LOG("DONE");
m_bStatus = 1; m_bStatus = 1;
return true; return true;

Loading…
Cancel
Save