e00ad69 로 늘어난 표면(라우트 17, 표 6종+컬럼 4, CLI 도구 5, 엣지 모듈 4, 통보 발송 경로,
감사 해시체인)을 8개 관점으로 재감사. 후보는 반증 시도 후 확정된 것만 채택.
CRITICAL
- A1 신규 감지 유형이 EventValidator 허용 목록에 없어 서버가 전부 400 으로 거부했다.
edge/queue.py 는 20회 재시도 후 그 행을 버리므로, 카메라 무결성 감지는 구현·테스트·배포가
끝난 상태로 end-to-end 무력화되어 있었다. DB CHECK 와 프런트 라벨은 갱신했는데 가운데
검증 계층만 빠진 형태 — 파이썬 테스트도 PHP 테스트도 각자 절반만 보기 때문에 둘 다 통과한다.
허용 목록을 고치고, 언어 경계를 넘는 회귀 테스트를 신설했다
(tests/test_event_type_parity.py: edge/events.py ↔ EventValidator ↔ schema.sql ↔
프런트 라벨 5종 ↔ 유형 필터). 실제로 A4 를 이 테스트가 잡았다.
- A2 seed_demo --purge 가 위험성평가를 reviewed_by='안전관리자' AND site='factory-a' 로
지웠다. 전자는 이 제품의 기본 관리자 계정명이고 후자는 흔한 현장명이다 — 운영 DB 에서
한 번 돌리면 실제 위험성평가가 복구 불가능하게 사라진다. 데모 행은 이제 전용 표식으로만
식별하고, 표식 없는 행은 어떤 경우에도 건드리지 않는다.
- A3 backup.php 의 웹 공개 경로 차단이 '/www/' 부분문자열이라 docroot 자체
(/home/acct/www)는 뒤에 슬래시가 없어 통과했다 — 가장 흔한 오사용이 정확히 그 경우다.
전 현장 사고 기록 + 작업자 이미지가 웹에서 내려받히고, 파일명은 하루 범위만 알면 추측된다.
경로를 세그먼트로 쪼개 웹 루트 이름(www/public_html/htdocs/html/web/public)을 거부한다.
HIGH
- A4 신규 유형이 app.js/detail.js/report.js 라벨 맵과 유형 필터에 없어 화면에 원시 코드가
그대로 떴고, 조사자가 그 유형만 걸러 볼 방법도 없었다.
- A5 서버 타임존 미설정. 대시보드는 브라우저 시각을 쓰지만 통보 메일은 PHP 가 만들고,
공유호스팅은 date.timezone 이 흔히 UTC 다 — 콘솔이 13:01 로 보여준 넘어짐을 메일이
04:01 로 적는다. 응급 대응에서 읽는 유일한 문장이 9시간 어긋나는 문제.
Config::timezone() 신설(기본 Asia/Seoul), 잘못된 값이면 폴백하되 발송은 막지 않는다.
- A6 ALTER TABLE … DROP CHECK 는 MySQL 8.0.16+ 전용이다. 카페24에 흔한 MariaDB 는
DROP CONSTRAINT 를 쓰므로 마이그레이션이 통째로 실패한다. 엔진별 분기를 명시하고,
이 CHECK 가 2차 방어선(1차는 EventValidator)임을 적어 실패해도 판단할 수 있게 했다.
MEDIUM
- A7 디스패처가 매분 창 전체를 재-claim 해 비용이 '새 이벤트'가 아니라 '창 길이'에 비례했다.
크론이 불안정해 창을 넓힌 현장일수록 나빠지는 방향이다. 원장을 한 번에 읽어 사전 필터하고,
claim() 은 경합 시 최종 권위로 남긴다.
- A8 move_alert_log 에 보존 정책이 없어 유일하게 무한 증가하는 표였다. 해소된 전달만
정리하고 failed 는 남긴다 — "아무에게도 닿지 않았다"가 조사에서 필요한 발견이다.
- A9 전역 관리자가 현장 채널을 수정하면 site 가 NULL 로 덮여 그 채널이 모든 현장에
발화했다. 폼에는 그런 안내가 없다. 수정 시 기존 site 보존.
- A10 일괄 확인이 대상마다 fetch 를 띄웠다. HTTP/2 는 직렬화하지 않으므로 수백 건이
공유호스팅에 한꺼번에 떨어진다. 동시 4개 제한 + 진행 중 목록 갱신.
LOW
- A11 패키지 테스트가 tools/ 배치를 검사하지 않았다. 이 도구들은 메일을 보내고 DB 전체를
읽으므로 www/ 아래로 새면 인증 없는 표면이 된다. CLI 가드 require·private 배치·웹 루트
PHP 화이트리스트 3종 검사 추가.
- A12 판정 배너와 CLAUDE.md 의 "43/43" 표기 갱신.
수정하지 않고 판단만 기록한 3건(웹훅 SSRF·서버가 지정하는 GPIO 핀·/setup 첫 카메라 한정)은
리포트 "확인만 하고 수정하지 않은 항목" 절 참조.
부수 효과: 기존 config 템플릿 가드가 timezone 키 누락을 잡아 두 템플릿도 함께 갱신됐다.
검증: PHPUnit 224 (skip 0, +3) · pytest 통과(skip 3 = 하드웨어·환경) · 산출물 패리티 통과.
backup 경로 가드는 docroot 자체/하위/비공개 3케이스로 회귀 확인. 감사로그 변조 탐지는
실제 UPDATE 후 verify_audit_chain.php exit 1 로 확인.
cafe24 번들 + Pi 오프라인 번들 재생성.
381 lines
21 KiB
PHP
381 lines
21 KiB
PHP
<?php
|
|
/**
|
|
* 데모/QA 시드 생성기.
|
|
*
|
|
* php -d extension=pdo_sqlite server/tools/seed_demo.php --days=45 --force
|
|
*
|
|
* WHY THIS EXISTS: every demo, every UI review and every regression check needs a database that
|
|
* looks like a real site — several devices, cameras with different risk profiles, an incident
|
|
* cascade (fall → no_motion on the same track), acknowledged and unacknowledged rows, false
|
|
* positives, evidence images, zones with rules, improvement actions. Building that by hand each
|
|
* time is how screens get signed off against data that never occurs in production (a single
|
|
* severity, no empty states, no long tail).
|
|
*
|
|
* SAFETY: this writes demo rows. It refuses to touch a database that already holds events
|
|
* unless --force is given, and it never runs over HTTP (see bootstrap.php). Every row it writes
|
|
* is tagged so --purge can remove exactly those rows and nothing else.
|
|
*
|
|
* Images need ext-gd. Without it the seeder still runs and the rows simply have no snapshot,
|
|
* which is itself a state worth seeing (PIPA retention purges produce it in production).
|
|
*/
|
|
declare(strict_types=1);
|
|
|
|
require __DIR__ . '/bootstrap.php';
|
|
|
|
[$cfg, $pdo] = tool_boot();
|
|
$args = tool_args($argv);
|
|
|
|
// Demo rows carry a marker in a field no real path ever writes, so --purge can target exactly
|
|
// those rows and nothing else. This is not cosmetic: a purge that matches on a plausible real
|
|
// value (an operator name, a site name) will one day be run against a production database and
|
|
// delete records nobody can reconstruct.
|
|
const DEMO_PREFIX = 'demo-'; // device_id prefix
|
|
const DEMO_ACTOR = 'demo-seed'; // created_by / reviewed_by
|
|
const DEMO_LABEL = '[데모] '; // name prefix on channels
|
|
|
|
$days = max(1, min(365, (int)($args['days'] ?? 45)));
|
|
$force = isset($args['force']);
|
|
$purge = isset($args['purge']);
|
|
$withImgs = !isset($args['no-images']) && function_exists('imagecreatetruecolor');
|
|
|
|
$snapshotDir = rtrim($cfg->snapshotDir(), '/\\');
|
|
|
|
function say(string $m): void { fwrite(STDOUT, $m . "\n"); }
|
|
|
|
// ---------------------------------------------------------------- purge
|
|
function purge(PDO $pdo, string $snapshotDir): void
|
|
{
|
|
$like = DEMO_PREFIX . '%';
|
|
// Snapshot files first: once the rows go, the uuids are unrecoverable and the jpgs would
|
|
// sit orphaned on disk forever.
|
|
$st = $pdo->prepare(
|
|
'SELECT s.file_uuid FROM move_event_snapshots s
|
|
JOIN move_events e ON e.event_id = s.event_id
|
|
WHERE e.device_id LIKE ?'
|
|
);
|
|
$st->execute([$like]);
|
|
$removed = 0;
|
|
foreach ($st->fetchAll(PDO::FETCH_COLUMN) as $uuid) {
|
|
$p = $snapshotDir . '/' . $uuid . '.jpg';
|
|
if (is_file($p) && @unlink($p)) $removed++;
|
|
}
|
|
$pdo->prepare('DELETE FROM move_event_snapshots WHERE event_id IN
|
|
(SELECT event_id FROM move_events WHERE device_id LIKE ?)')->execute([$like]);
|
|
$pdo->prepare('DELETE FROM move_events WHERE device_id LIKE ?')->execute([$like]);
|
|
$pdo->prepare('DELETE FROM move_zones WHERE device_id LIKE ?')->execute([$like]);
|
|
$pdo->prepare('DELETE FROM move_devices WHERE device_id LIKE ?')->execute([$like]);
|
|
$pdo->prepare('DELETE FROM move_cameras WHERE device_id LIKE ?')->execute([$like]);
|
|
$pdo->prepare('DELETE FROM move_device_metrics WHERE device_id LIKE ?')->execute([$like]);
|
|
$pdo->prepare("DELETE FROM move_actions WHERE created_by = ?")->execute([DEMO_ACTOR]);
|
|
// 데모 행은 반드시 DEMO_ACTOR / DEMO_PREFIX 표식으로만 식별한다.
|
|
//
|
|
// 감사 지적(A2): 예전에는 위험요인을 `reviewed_by='안전관리자' AND site='factory-a'` 로
|
|
// 지웠다. '안전관리자'는 이 제품의 기본 관리자 계정명이고 'factory-a'는 흔한 현장명이라,
|
|
// 운영 DB 에서 --purge 를 한 번 돌리면 **실제 위험성평가가 통째로 사라진다.** 표식 없는
|
|
// 행은 이제 어떤 경우에도 건드리지 않는다.
|
|
$pdo->prepare("DELETE FROM move_alert_channels WHERE name LIKE ?")->execute([DEMO_LABEL . '%']);
|
|
$pdo->prepare("DELETE FROM move_risk_controls WHERE reviewed_by = ?")->execute([DEMO_ACTOR]);
|
|
say("purged demo rows (snapshot files removed: $removed)");
|
|
}
|
|
|
|
if ($purge) { purge($pdo, $snapshotDir); if (!$force) exit(0); }
|
|
|
|
$existing = (int)$pdo->query('SELECT COUNT(*) FROM move_events')->fetchColumn();
|
|
if ($existing > 0 && !$force) {
|
|
fwrite(STDERR, "이미 이벤트 {$existing}건이 있는 DB입니다. 데모 데이터를 섞으려면 --force,\n"
|
|
. "기존 데모 행만 지우려면 --purge 를 쓰세요.\n");
|
|
exit(1);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- fixtures
|
|
$now = time();
|
|
|
|
/** A workplace, not a test fixture: each camera has a different risk profile so the report,
|
|
* the ranking bars and the FP panel all have something real to say. */
|
|
$devices = [
|
|
['id' => DEMO_PREFIX . 'press', 'name' => '1공장 프레스라인', 'site' => 'factory-a',
|
|
'fps' => 24.8, 'temp' => 58.2, 'throttle' => 0, 'beat' => $now - 8],
|
|
['id' => DEMO_PREFIX . 'wh', 'name' => '1공장 자재창고', 'site' => 'factory-a',
|
|
'fps' => 23.9, 'temp' => 61.4, 'throttle' => 1, 'beat' => $now - 21],
|
|
['id' => DEMO_PREFIX . 'paint', 'name' => '2공장 도장부스', 'site' => 'factory-a',
|
|
'fps' => null, 'temp' => null, 'throttle' => null, 'beat' => $now - 5400], // offline
|
|
];
|
|
$cameras = [
|
|
DEMO_PREFIX . 'press' => ['cam-press-01', 'cam-press-02'],
|
|
DEMO_PREFIX . 'wh' => ['cam-wh-01', 'cam-wh-02'],
|
|
DEMO_PREFIX . 'paint' => ['cam-paint-01'],
|
|
];
|
|
// Per camera: how often it fires, and what it tends to fire. A press line falls; a warehouse
|
|
// has zone and occupancy traffic; a paint booth is quiet but degrades.
|
|
$profile = [
|
|
'cam-press-01' => ['weight' => 4, 'types' => ['fall', 'near_fall', 'immobility', 'ergo_report', 'no_motion']],
|
|
'cam-press-02' => ['weight' => 3, 'types' => ['near_fall', 'ergo_report', 'pinch', 'ghost']],
|
|
'cam-wh-01' => ['weight' => 2, 'types' => ['zone_warning', 'overstay', 'lone_worker']],
|
|
'cam-wh-02' => ['weight' => 3, 'types' => ['zone_restricted', 'overcapacity', 'overstay', 'zone_warning']],
|
|
'cam-paint-01' => ['weight' => 1, 'types' => ['monitoring_degraded', 'device_fault', 'zone_warning']],
|
|
];
|
|
$severityOf = [
|
|
'fall' => 'critical', 'no_motion' => 'critical', 'pinch' => 'critical',
|
|
'immobility' => 'high', 'ghost' => 'high', 'zone_restricted' => 'high', 'lone_worker' => 'high',
|
|
'near_fall' => 'warning', 'zone_warning' => 'warning', 'overcapacity' => 'warning', 'overstay' => 'warning',
|
|
'ergo_report' => 'info', 'monitoring_degraded' => 'info', 'device_fault' => 'info',
|
|
];
|
|
|
|
$pdo->beginTransaction();
|
|
|
|
// devices + cameras
|
|
$dev = $pdo->prepare('INSERT INTO move_devices (device_id,name,site,secret,config_version,last_fps,last_temp,
|
|
last_throttle,reported_config_version,last_heartbeat_at,created_at)
|
|
VALUES (?,?,?,?,3,?,?,?,3,?,?)');
|
|
$cam = $pdo->prepare('INSERT INTO move_cameras (camera_id,device_id,name,role,created_at) VALUES (?,?,?,?,?)');
|
|
foreach ($devices as $d) {
|
|
// A demo secret that is obviously not a credential. Never a plausible-looking one: a demo
|
|
// row that looks provisioned invites someone to point a real device at it.
|
|
$dev->execute([$d['id'], $d['name'], $d['site'], 'DEMO-NOT-A-REAL-SECRET',
|
|
$d['fps'], $d['temp'], $d['throttle'], $d['beat'], $now - 86400 * 90]);
|
|
foreach ($cameras[$d['id']] as $c) {
|
|
$cam->execute([$c, $d['id'], $c, str_starts_with($c, 'cam-press') ? 'fall_critical' : 'zone', $now - 86400 * 90]);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- events
|
|
$ins = $pdo->prepare(
|
|
'INSERT INTO move_events (event_uuid,device_id,site,camera_id,event_type,severity,track_id,zone_id,
|
|
occurred_at,duration_s,metrics_json,spatial_x,spatial_y,acknowledged_by,acknowledged_at,
|
|
false_positive_by,false_positive_at,received_at)
|
|
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
|
|
);
|
|
|
|
$deviceOf = [];
|
|
foreach ($cameras as $devId => $list) foreach ($list as $c) $deviceOf[$c] = $devId;
|
|
$siteOf = [];
|
|
foreach ($devices as $d) $siteOf[$d['id']] = $d['site'];
|
|
|
|
$seq = 0;
|
|
$made = 0;
|
|
mt_srand(20260809); // deterministic: two runs produce the same board, so screenshots diff cleanly
|
|
|
|
function metricsFor(string $type, float $dur): ?string
|
|
{
|
|
$m = ['confidence' => round(0.72 + mt_rand(0, 260) / 1000, 2)];
|
|
if ($type === 'immobility') $m['immobility_s'] = round($dur, 1);
|
|
if ($type === 'no_motion') $m['prone_s'] = round($dur, 1);
|
|
if ($type === 'overstay') { $m['dwell_s'] = round($dur, 1); $m['limit_s'] = 1800; }
|
|
if ($type === 'lone_worker') { $m['alone_s'] = round($dur, 1); $m['workers'] = 1; $m['required'] = 2; }
|
|
if ($type === 'overcapacity'){ $m['workers'] = 5; $m['limit'] = 4; }
|
|
if ($type === 'ghost') { $m['waited_s'] = round($dur, 1); $m['last_state'] = 'FALLEN'; }
|
|
if ($type === 'fall') { $m['torso_angle'] = mt_rand(62, 88); $m['aspect_ratio'] = round(mt_rand(150, 260) / 100, 2); }
|
|
if ($type === 'ergo_report') {
|
|
$m['observed_s'] = 3600; $m['trunk_high_s'] = mt_rand(120, 900);
|
|
$m['trunk_mod_s'] = mt_rand(400, 1800); $m['arm_high_s'] = mt_rand(60, 600);
|
|
$m['squat_s'] = mt_rand(30, 400);
|
|
}
|
|
return json_encode($m, JSON_UNESCAPED_UNICODE);
|
|
}
|
|
|
|
/** One event row. Returns the inserted event_id. */
|
|
function emit(PDO $pdo, PDOStatement $ins, array $ctx): int
|
|
{
|
|
$ins->execute([
|
|
$ctx['uuid'], $ctx['device'], $ctx['site'], $ctx['camera'], $ctx['type'], $ctx['severity'],
|
|
$ctx['track'], null, $ctx['at'], $ctx['dur'], $ctx['metrics'], $ctx['x'], $ctx['y'],
|
|
$ctx['ackBy'], $ctx['ackAt'], $ctx['fpBy'], $ctx['fpAt'], (int)$ctx['at'],
|
|
]);
|
|
return (int)$pdo->lastInsertId();
|
|
}
|
|
|
|
$eventIds = []; // newest-first, for snapshot attachment
|
|
|
|
// Weighted camera picker.
|
|
$bag = [];
|
|
foreach ($profile as $c => $p) for ($i = 0; $i < $p['weight']; $i++) $bag[] = $c;
|
|
|
|
for ($d = 0; $d < $days; $d++) {
|
|
// Fewer events per day the further back we go? No — keep the rate flat but let the
|
|
// hour-of-day distribution be realistic: a day shift peak, a smaller night peak.
|
|
$perDay = mt_rand(1, 5);
|
|
for ($k = 0; $k < $perDay; $k++) {
|
|
$camera = $bag[array_rand($bag)];
|
|
$type = $profile[$camera]['types'][array_rand($profile[$camera]['types'])];
|
|
$sev = $severityOf[$type] ?? 'info';
|
|
// Shift-shaped hours: 07-17 heavy, 22-02 light, rest sparse.
|
|
$roll = mt_rand(1, 100);
|
|
$hour = $roll <= 65 ? mt_rand(7, 17) : ($roll <= 85 ? mt_rand(22, 25) % 24 : mt_rand(0, 23));
|
|
$at = $now - $d * 86400;
|
|
$at = mktime($hour, mt_rand(0, 59), mt_rand(0, 59), (int)date('n', $at), (int)date('j', $at), (int)date('Y', $at));
|
|
if ($at > $now) $at -= 86400;
|
|
|
|
$dur = match ($type) {
|
|
'immobility' => mt_rand(300, 900), 'overstay' => mt_rand(1800, 4200),
|
|
'lone_worker' => mt_rand(60, 600), 'ergo_report' => 3600,
|
|
'no_motion' => mt_rand(20, 90), default => round(mt_rand(4, 40) / 10, 1),
|
|
};
|
|
// Older events are mostly handled; recent ones mostly are not — that is what a real
|
|
// board looks like, and it is what makes the 미확인 view worth having.
|
|
$handled = $d === 0 ? mt_rand(1, 100) <= 25 : ($d <= 2 ? mt_rand(1, 100) <= 70 : mt_rand(1, 100) <= 95);
|
|
$isFp = $handled && mt_rand(1, 100) <= 14;
|
|
|
|
$seq++;
|
|
$ctx = [
|
|
'uuid' => substr(str_pad(DEMO_PREFIX . $seq, 32, '0', STR_PAD_LEFT), -32),
|
|
'device' => $deviceOf[$camera], 'site' => $siteOf[$deviceOf[$camera]], 'camera' => $camera,
|
|
'type' => $type, 'severity' => $sev, 'track' => 100 + $seq, 'at' => (float)$at, 'dur' => $dur,
|
|
'metrics' => metricsFor($type, (float)$dur),
|
|
'x' => round(mt_rand(120, 880) / 1000, 3), 'y' => round(mt_rand(200, 900) / 1000, 3),
|
|
'ackBy' => $handled ? '안전관리자' : null,
|
|
'ackAt' => $handled ? $at + mt_rand(40, 900) : null,
|
|
'fpBy' => $isFp ? '안전관리자' : null,
|
|
'fpAt' => $isFp ? $at + mt_rand(60, 1200) : null,
|
|
];
|
|
$eventIds[] = ['id' => emit($pdo, $ins, $ctx), 'camera' => $camera, 'at' => $at, 'type' => $type];
|
|
$made++;
|
|
|
|
// Incident cascade: a fall is followed by the no_motion the detector chain really emits
|
|
// seconds later, on the SAME track. This is the case the console has to render as two
|
|
// rows of one event — worth having in every demo.
|
|
if ($type === 'fall' && mt_rand(1, 100) <= 60) {
|
|
$seq++;
|
|
$ctx2 = $ctx;
|
|
$ctx2['uuid'] = substr(str_pad(DEMO_PREFIX . $seq, 32, '0', STR_PAD_LEFT), -32);
|
|
$ctx2['type'] = 'no_motion';
|
|
$ctx2['severity'] = 'critical';
|
|
$ctx2['at'] = (float)($at + mt_rand(20, 45));
|
|
$ctx2['dur'] = mt_rand(20, 60);
|
|
$ctx2['metrics'] = metricsFor('no_motion', (float)$ctx2['dur']);
|
|
$eventIds[] = ['id' => emit($pdo, $ins, $ctx2), 'camera' => $camera, 'at' => (int)$ctx2['at'], 'type' => 'no_motion'];
|
|
$made++;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- zones
|
|
$zone = $pdo->prepare('INSERT INTO move_zones (zone_id,device_id,camera_id,level,polygon_json,rules_json,updated_at)
|
|
VALUES (?,?,?,?,?,?,?)');
|
|
$zone->execute([bin2hex(random_bytes(16)), DEMO_PREFIX . 'press', 'cam-press-01', 'restricted',
|
|
json_encode([[0.18, 0.30], [0.66, 0.28], [0.70, 0.82], [0.20, 0.85]]),
|
|
json_encode(['min_workers' => 2]), $now]);
|
|
$zone->execute([bin2hex(random_bytes(16)), DEMO_PREFIX . 'press', 'cam-press-02', 'pinch',
|
|
json_encode([[0.55, 0.40], [0.86, 0.42], [0.84, 0.78], [0.53, 0.76]]), null, $now]);
|
|
$zone->execute([bin2hex(random_bytes(16)), DEMO_PREFIX . 'wh', 'cam-wh-02', 'warning',
|
|
json_encode([[0.08, 0.55], [0.92, 0.52], [0.94, 0.94], [0.06, 0.96]]),
|
|
json_encode(['max_workers' => 4, 'max_dwell_s' => 1800]), $now]);
|
|
|
|
// ---------------------------------------------------------------- improvement actions
|
|
$act = $pdo->prepare('INSERT INTO move_actions (camera_id,site,note,taken_at,created_by,created_at) VALUES (?,?,?,?,?,?)');
|
|
foreach ([
|
|
['cam-press-01', '프레스 진입로 미끄럼 방지 매트 설치', 34],
|
|
['cam-wh-02', '자재창고 통로 폭 확대 · 안전선 재도색', 12],
|
|
['cam-press-02', '협착 구역 광전센서 추가 · 방호덮개 교체', 5],
|
|
] as [$c, $note, $ago]) {
|
|
$act->execute([$c, 'factory-a', $note, $now - $ago * 86400, DEMO_ACTOR, $now - $ago * 86400]);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 통보 · 규정 · 성능
|
|
// 새 화면(시스템 설정 / 안전 관리)이 빈 상태로만 시연되면 그 기능이 없는 것처럼 보인다.
|
|
// 다만 어떤 것도 실제로 발송되지 않도록, 채널은 전부 비활성으로 넣는다.
|
|
$ch = $pdo->prepare('INSERT INTO move_alert_channels (site,kind,name,config_json,min_severity,enabled,step,escalate_after_s,created_at)
|
|
VALUES (?,?,?,?,?,?,?,?,?)');
|
|
$ch->execute(['factory-a', 'local', DEMO_LABEL . '1공장 경광등',
|
|
json_encode(['gpio_pin' => 17, 'mode' => 'latch', 'hold_s' => 45, 'active_high' => false]),
|
|
'high', 0, 0, 0, $now]);
|
|
// 메일/웹훅은 enabled=0. 데모 DB 로 실수로 크론을 돌려도 아무 데도 나가지 않는다.
|
|
$ch->execute(['factory-a', 'email', DEMO_LABEL . '안전관리자 메일 (사용 안 함)',
|
|
json_encode(['to' => ['safety@example.invalid']]), 'critical', 0, 0, 0, $now]);
|
|
$ch->execute(['factory-a', 'email', DEMO_LABEL . '공장장 에스컬레이션 (사용 안 함)',
|
|
json_encode(['to' => ['plant-manager@example.invalid']]), 'critical', 0, 1, 600, $now]);
|
|
|
|
$risk = $pdo->prepare('INSERT INTO move_risk_controls (site,event_type,hazard,control,severity_rating,likelihood_rating,reviewed_by,reviewed_at,updated_at)
|
|
VALUES (?,?,?,?,?,?,?,?,?)');
|
|
foreach ([
|
|
['fall', '프레스 진입로 유압유 누유로 인한 미끄럼 전도', '미끄럼 방지 매트 · 일일 누유 점검 · AI 넘어짐 감지', 5, 3],
|
|
['pinch', '금형 교체 중 상하 금형 사이 협착', '광전센서 · 방호덮개 · 협착구역 침입 감지', 5, 2],
|
|
['zone_restricted', '가동 중 프레스 방호구역 진입', '안전문 인터록 · 제한구역 침입 감지', 4, 3],
|
|
['lone_worker', '자재창고 야간 단독 작업 중 사고 시 발견 지연', '2인 1조 편성 · 단독 작업 감지', 4, 2],
|
|
['overstay', '도장부스 장시간 체류로 인한 유기용제 노출', '체류 상한 30분 · 국소배기 점검', 3, 3],
|
|
] as [$t, $hazard, $control, $sev, $like]) {
|
|
$risk->execute(['factory-a', $t, $hazard, $control, $sev, $like, DEMO_ACTOR, $now - 30 * 86400, $now - 30 * 86400]);
|
|
}
|
|
|
|
// 성능 시계열: 24시간치. pi-a2 는 오후부터 스로틀이 걸리며 프레임률이 흘러내린다 —
|
|
// "지금 살아 있는가"와 "점점 나빠지는가"의 차이를 한눈에 보여주는 것이 이 화면의 목적이다.
|
|
$met = $pdo->prepare('INSERT INTO move_device_metrics (device_id,ts,fps,temp,throttle,queue_pending,cameras_total,cameras_erroring,errors)
|
|
VALUES (?,?,?,?,?,?,?,?,?)');
|
|
for ($i = 288; $i >= 0; $i--) { // 5분 간격 24시간
|
|
$ts = $now - $i * 300;
|
|
$phase = 1.0 - $i / 288.0; // 0 = 24시간 전, 1 = 지금
|
|
$met->execute([DEMO_PREFIX . 'press', $ts, 24.5 + mt_rand(-4, 4) / 10, 56 + mt_rand(-15, 15) / 10, 0,
|
|
mt_rand(0, 2), 2, 0, 0]);
|
|
$hot = $phase > 0.55;
|
|
$met->execute([DEMO_PREFIX . 'wh', $ts,
|
|
$hot ? 24.0 - ($phase - 0.55) * 22 : 24.0 + mt_rand(-3, 3) / 10,
|
|
$hot ? 74 + ($phase - 0.55) * 14 : 60 + mt_rand(-15, 15) / 10,
|
|
$hot ? 1 : 0, $hot ? mt_rand(0, 40) : 0, 2, 0, $hot ? mt_rand(0, 3) : 0]);
|
|
}
|
|
|
|
$pdo->commit();
|
|
say("events: $made · devices: " . count($devices) . " · cameras: " . array_sum(array_map('count', $cameras)));
|
|
say('alert channels: 3 (전부 비활성 또는 로컬) · risk controls: 5 · device metrics: 24h');
|
|
|
|
// ---------------------------------------------------------------- snapshots
|
|
if (!$withImgs) {
|
|
say('snapshots: skipped (ext-gd 없음 또는 --no-images) — 행은 "무영상" 상태로 표시됩니다.');
|
|
exit(0);
|
|
}
|
|
if (!is_dir($snapshotDir) && !@mkdir($snapshotDir, 0775, true)) {
|
|
say("snapshots: {$snapshotDir} 생성 실패 — 건너뜁니다.");
|
|
exit(0);
|
|
}
|
|
|
|
/**
|
|
* A three-frame evidence timeline per event, for the newest N events only (a demo does not
|
|
* need 200 days of jpgs, and a shared-hosting quota does not want them). The worker is drawn
|
|
* post-blur — a flat silhouette — because that is what the delivered system actually stores:
|
|
* FaceBlurrer runs before anything is written. A demo image with a recognisable face would
|
|
* misrepresent the product's privacy behaviour.
|
|
*/
|
|
function drawFrame(string $camera, int $ts, int $step, string $type): \GdImage
|
|
{
|
|
$im = imagecreatetruecolor(640, 360);
|
|
for ($y = 0; $y < 360; $y++) {
|
|
$v = (int)(44 + $y * 0.20);
|
|
imagefilledrectangle($im, 0, $y, 640, $y, imagecolorallocate($im, $v, $v + 4, $v + 10));
|
|
}
|
|
imagefilledrectangle($im, 30, 70, 210, 300, imagecolorallocate($im, 74, 80, 89));
|
|
for ($x = 250; $x < 630; $x += 42) {
|
|
imagefilledpolygon($im, [$x, 322, $x + 20, 322, $x + 4, 352, $x - 16, 352],
|
|
imagecolorallocate($im, 186, 156, 42));
|
|
}
|
|
// Falling types tilt and descend across the three frames; others just drift.
|
|
$falling = in_array($type, ['fall', 'no_motion', 'near_fall'], true);
|
|
$drop = $falling ? $step * 30 : 0;
|
|
$cx = 380 + $step * 16;
|
|
$cy = 150 + $drop;
|
|
$skin = imagecolorallocate($im, 222, 224, 228); // flat: face blur already applied
|
|
$vest = imagecolorallocate($im, 236, 176, 40);
|
|
imagefilledellipse($im, $cx, $cy, 32, 32, $skin);
|
|
imagefilledrectangle($im, $cx - 21, $cy + 15, $cx + 21, $cy + max(24, 104 - $drop), $vest);
|
|
$box = imagecolorallocate($im, 226, 62, 62);
|
|
imagesetthickness($im, 3);
|
|
imagerectangle($im, $cx - 44, $cy - 28, $cx + 50, $cy + max(34, 118 - $drop), $box);
|
|
imagestring($im, 2, 12, 12, strtoupper($camera) . ' ' . date('Y-m-d H:i:s', $ts), imagecolorallocate($im, 198, 204, 212));
|
|
return $im;
|
|
}
|
|
|
|
$snapIns = $pdo->prepare('INSERT INTO move_event_snapshots (event_id,file_uuid,content_hash,created_at) VALUES (?,?,?,?)');
|
|
usort($eventIds, fn ($a, $b) => $b['at'] <=> $a['at']);
|
|
$withEvidence = array_slice($eventIds, 0, 40);
|
|
$files = 0;
|
|
$pdo->beginTransaction();
|
|
foreach ($withEvidence as $e) {
|
|
for ($f = 0; $f < 3; $f++) {
|
|
$uuid = bin2hex(random_bytes(16));
|
|
$im = drawFrame($e['camera'], $e['at'] - (2 - $f) * 2, $f, $e['type']);
|
|
imagejpeg($im, $snapshotDir . '/' . $uuid . '.jpg', 82);
|
|
imagedestroy($im);
|
|
$snapIns->execute([$e['id'], $uuid, hash('sha256', $uuid), $e['at'] - (2 - $f) * 2]);
|
|
$files++;
|
|
}
|
|
}
|
|
$pdo->commit();
|
|
say("snapshots: {$files}개 (" . count($withEvidence) . "건에 3프레임씩) -> {$snapshotDir}");
|
|
say('완료. 데모 행만 지우려면: --purge');
|