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');