You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\PeopleCounting;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* 拉取海康客流 HTTP 接口PEOPLE_COUNTING_URL
*/
class HikPeopleCountingClient
{
public function peopleCountingUrl(): string
{
$url = trim((string) config('services.people_counting.url', ''));
if ($url === '') {
throw new RuntimeException('未配置 PEOPLE_COUNTING_URLservices.people_counting.url');
}
return rtrim($url, '/');
}
public function apiBase(): string
{
return (string) preg_replace('#/api/people-counting$#i', '', $this->peopleCountingUrl());
}
/**
* 单日快照:过去日期读归档 venues[],今天读内存。
*
* @return array<string, mixed>
*/
public function fetchDailySnapshot(Carbon $day): array
{
$d = $day->toDateString();
$url = $this->peopleCountingUrl();
$res = Http::timeout($this->timeout())
->acceptJson()
->get($url, [
'date' => $d,
'end_date' => $d,
]);
if (! $res->successful()) {
throw new RuntimeException("客流日接口 HTTP {$res->status()} {$url}: ".mb_substr($res->body(), 0, 400));
}
$json = $res->json();
if (! is_array($json) || (int) ($json['code'] ?? 0) !== 200) {
throw new RuntimeException('客流日接口业务失败: '.mb_substr((string) $res->body(), 0, 500));
}
return $json;
}
/**
* 全场馆 24 小时桶。
*
* @return array<string, mixed>
*/
public function fetchHourly(Carbon $day): array
{
$url = $this->apiBase().'/api/venues/hourly';
$res = Http::timeout($this->timeout())
->acceptJson()
->get($url, [
'date' => $day->toDateString(),
]);
if (! $res->successful()) {
throw new RuntimeException("客流小时接口 HTTP {$res->status()} {$url}: ".mb_substr($res->body(), 0, 400));
}
$json = $res->json();
if (! is_array($json) || (int) ($json['code'] ?? 0) !== 200) {
throw new RuntimeException('客流小时接口业务失败: '.mb_substr((string) $res->body(), 0, 500));
}
return $json;
}
private function timeout(): int
{
$n = (int) config('services.people_counting.timeout', 20);
return max(5, min($n, 120));
}
}