@accountnujen

Как в PHP выполнить запрос, который постоянно (?) отвечает?

Есть API камеры, который содержит такие параметры
API документация

Syntax
http:///cgi-bin/eventManager.cgi?action=attach&codes=[, Code>,…][&keepalive = 20][&heartbeat=]
Method GET
Description Subscribe to messages that event of code eventCode happens
Example
http://192.168.1.108/cgi-bin/eventManager.cgi?acti...]
http://192.168.1.108/cgi-bin/eventManager.cgi?acti...
Success Return
HTTP Code: 200 OK\r\n
Cache-Control: no-cache\r\n
Pragma: no-cache\r\n
Expires: Thu, 01 Dec 2099 16:00:00 GMT\r\n
Connection: close\r\n
Content-Type: multipart/x-mixed-replace; boundary=\r\n
Body:
--\r\n
Content-Type: text/plain\r\n
Content-Length: \r\n
\r\n\r\n
--\r\n
Content-Type: text/plain\r\n
Content-Length: \r\n
\r\n\r\n
For example:
HTTP Code: 200 OK\r\n
Cache-Control: no-cache\r\n
Pragma: no-cache\r\n
Expires: Thu, 01 Dec 2099 16:00:00 GMT\r\n
Connection: close\r\n
Content-Type: multipart/x-mixed-replace; boundary=myboundary\r\n\r\n
Body:
--myboundary\r\n
Content-Type: text/plain\r\n
Content-Length: 39\r\n
Code=VideoMotion;action=Start;index=0\r\n\r\n
--myboundary\r\n
Content-Type: text/plain\r\n
Content-Length: 38\r\n
Code=VideoBlind;action=Start;index=0\r\n\r\n
--myboundary\r\n
Content-Type: text/plain\r\n
Content-Length: 9\r\n
Heartbeat\r\n\r\n
--myboundary\r\n

Comment
eventCode can be any one of the standard codes defined in DHIIF, or "All".
All means all kinds of the eventcode.
eventcode include:
VideoMotion: motion detection event
SmartMotionHuman: human smart motion detection
SmartMotionVehicle:Vehicle smart motion detection
VideoLoss: video loss detection event
VideoBlind: video blind detection event.
AlarmLocal: alarm detection event.
CrossLineDetection: tripwire event
CrossRegionDetection: intrusion event
LeftDetection: abandoned object detection
TakenAwayDetection: missing object detection
VideoAbnormalDetection: scene change event
FaceDetection: face detect event
AudioMutation: intensity change
AudioAnomaly: input abnormal
VideoUnFocus: defocus detect event
WanderDetection: loitering detection event
RioterDetection: People Gathering event
ParkingDetection: parking detection event
MoveDetection: fast moving event
StorageNotExist: storage not exist event.
StorageFailure: storage failure event.
StorageLowSpace: storage low space event.
AlarmOutput: alarm output event.
MDResult: motion detection data reporting event. The motion detect window
contains 18 rows and 22 columns. The event info contains motion detect data with
mask of every row.
HeatImagingTemper: temperature alarm event
CrowdDetection: crowd density overrun event
FireWarning: fire warning event
FireWarningInfo: fire warning specific data info
In the example, you can see most event info is like "Code=eventcode; action=Start;
index=0", but for some specific events, they will contain an another parameter named
"data", the event info is like "Code=eventcode; action=Start; index=0; data=datainfo",
the datainfo's fomat is JSON(JavaScript Object Notation). The detail information about
the specific events and datainfo are listed in the appendix below this table.
keepalive: If this param exist, the client must send any data to device by this
connection in cycle. The keepalive is in range
of [1,60] second.


Я сделал через POSTMAN просто запрос
my-ip/cgi-bin/eventManager.cgi?action=attach&codes=[All]&heartbeat=5

Event в камере настроен на движение. Движение произошло, камера это записала, однако POSTMAN как висел 3 часа, так и висит.

Я не до конца могу понять, каким образом они получают множественные ответы. В моём понимании ты делаешь запрос - сервер ответил - запрос завершён. Здесь же ответы разделены каким-то --myboundary\r\n. То есть это какое-то потоковое вещание. Как тогда работать с ним? Если я просто curl запрос в PHP выполняю, то получаю снова вечную загрузку (если timeout выключу).
  • Вопрос задан
  • 139 просмотров
Пригласить эксперта
Ответы на вопрос 1
Anastasia2306
@Anastasia2306
PHP-разработчик.
Работа с потоками данных может быть сложной задачей, особенно если вы хотите обработать каждый отдельный ответ независимо. Тут без фреймворка или какой-то спец библиотеки будет тяжело.

Но, я бы на основе этих данных вот так сделала, а вдруг прокатит?)))

<?php
$url = 'http://my-ip/cgi-bin/eventManager.cgi?action=attach&codes=[All]&heartbeat=5';

$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => 'Connection: close\r\n'
    ]
]);

$resource = fopen($url, 'r', false, $context);

while (!feof($resource)) {
    $line = fgets($resource);
    if (strpos($line, '--myboundary') !== false) {
        // Начало нового ответа
        $response = '';
        while (!feof($resource)) {
            $line = fgets($resource);
            if (strpos($line, '--myboundary') !== false) {
                // Конец ответа
                break;
            }
            $response .= $line;
        }
        // Обработка ответа
        echo $response;
    }
}

fclose($resource);
?>
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы