UI/UX 점검에서 시작해 "이 제품이 안전 시스템으로서 무엇이 없나"까지 내려간 작업. 두 덩어리를 한 커밋으로 둔다 — 뒤쪽 기능들이 앞쪽에서 고친 화면 위에 얹혀 있다. ━━ 1부: UI/UX 감사 21건 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 동선 — 확인(ack) 경로가 위험했다 - 스트림 정렬을 '미확인 우선'에서 엄격 시간순으로 되돌린다. 확인 상태가 연대기를 뒤집어 사고 재구성이 불가능했고, 확인하면 그 행이 목록 밖으로 사라지며 아래 행이 밀려 올라와 같은 좌표를 두 번 누르면 다른 이벤트가 확인 처리됐다. 이제 제자리에서 '확인됨'으로 전환되고 확정 토스트가 뜬다. 처리 큐는 정렬이 아니라 뷰모드 필터로 분리 (전환해도 행끼리 상대 순서는 절대 안 바뀐다). - 실행취소는 넣지 않았다. acknowledged_by는 감사로그가 함께 남는 추가 전용 기록이라 무음 되돌리기가 안전 시스템에서 더 나쁜 속성이다. 대신 오탐·구역삭제를 2단계 확정으로. - 이벤트 상세에 확인/오탐 신설. 판단하는 화면에 판단 도구가 없었다. - 구역 설정에 장치·카메라 선택기. 시스템이 아는 값을 사람에게 묻고 있었고, 플레이스홀더(device-01)마저 실제와 다른 포맷을 가르쳤다. - 날짜 조회(키셋 커서 시딩). 사고 조사 진입로가 아예 없어 '더 보기'를 반복해야 했다. - 경보음 세션 음소거(새 위급 도착 시 자동 해제). 끌 수 없는 반복음은 안전 콘솔이 통째로 꺼지는 경로다. 전달 — 같은 단어가 화면마다 다른 숫자를 가리켰다 - KPI '미확인'(최근 200건)과 24시간 브리프 '미확인'이 40px 간격으로 충돌했다. KPI에 실제 집계 범위를 명시. 중대=위급+높음을 인라인 정의. - 페이지 명칭 3종·날짜 포맷 3종 통일. '확인 필요' 칩을 전 심각도로 확장 (그전엔 확인 여부가 먼 컬럼의 버튼 유무로만 구분됐다). - 표본 게이트: 오탐율 '100% (1/1)'이 '33% (5/15)'보다 위에 뜨던 것, 최다 3건짜리 시간패턴 히트맵, 6→8건에 붙던 빨간 ▲33%. 개선조치 효과는 푸아송 잡음 범위(√before)를 넘어야 방향을 주장한다 — 안전회의에서 한 번 반박당하면 카드 전체가 신뢰를 잃는다. - 카메라 위험 순위가 중대>0이면 전부 빨강이라 순위 노릇을 못 했다. 상대 기준으로. 시각 — 화면마다 완성도가 달랐다 - 구역 설정·이벤트 상세를 카드 셸로 재구성. 둘 다 스타일 없는 기본 폼이었고, 납품 심사에서 "덜 만든 티"는 정확히 거기서 났다. - 히트맵 토글은 aria-pressed만 있고 CSS 규칙이 없어 켜졌는지 눈으로 알 수 없었다. - 존 색을 팔레트와 정합(팔레트 어디에도 없던 보라 제거), 채움+라벨칩+협착 점선. 캔버스에 1px 외곽선만 그리면 실제 공장 프레임에서 사라진다. ━━ 2부: 안전 플랫폼 (마이그레이션 2026-08-09-safety-platform.sql) ━━━ 통보 — 이 제품의 정의에 해당하는 구멍 지금까지 감지는 브라우저 탭이 열려 있고 사람이 보고 있어야만 전달됐다. 새벽 3시에 넘어진 작업자는 DB에 행 하나를 남기고 아침을 맞았다. - 엣지 GPIO 경광등(edge/beacon.py). 인터넷·서버 없이 동작하는 유일한 경로라 어떤 현장이든 이것부터 설정한다. /api/config의 beacons로 배선을 받고, 하드웨어가 없거나 핀이 안 열리면 NullBeacon으로 떨어지되 그 사실은 반드시 로그로 남긴다. - 메일·웹훅 채널 + 크론 디스패처(tools/dispatch_alerts.php). 중복 발송은 읽고-쓰기가 아니라 (event,channel) UNIQUE로 막는다 — 크론 중첩 실행은 공유호스팅의 상수다. - 미확인 위급은 unacked_escalation 이벤트가 되어 상위 채널로 올라간다(event_uuid로 멱등). '아무도 보지 않았다'는 사실 자체를 사건으로 만든다. - 통보에 이미지는 싣지 않는다. 스냅샷은 PIPA 대상이고 메일링 리스트로 나가는 순간 인증 프록시가 지키던 통제를 벗어난다 — 링크만 보낸다. 조용한 실패 제거 - 카메라 화각 이동·가림·조도 저하 감지(detectors/integrity.py). 존 판정은 화각 고정을 전제로 서 있는데, 삼각대를 스치면 제한구역이 엉뚱한 바닥을 가리키면서 시스템은 계속 초록불이었다. numpy만 사용하고, 지나가는 사람과 구분하기 위해 지속시간을 요구한다. - 스토리지 여유 감시. 디스크가 차면 이미지 저장만 조용히 실패하고 보드는 멀쩡해 보인다. 끊겨 있던 배선 2건 - thresholds_from_config()가 정의만 있고 어디서도 호출되지 않았다. 서버에 표가 있고 /api/config가 성실히 실어 보내고 엣지가 파싱한 뒤 버렸다 — 관리자가 무엇을 바꿔도 장비는 부팅 시 edge.env 값으로 영원히 돌았다(edge/tuning.py). - 존·임계값 저장이 config_version을 올리지 않아 '설정 지연' 표시가 애초에 켜질 수 없었다. 지표는 있는데 그것을 켜는 사건이 없었다. 관리 화면 (그전에는 phpMyAdmin이 유일한 방법이었다) - 임계값 편집: 자유 텍스트가 아니라 카탈로그(범위·단위·설명)로 렌더한다. 범위 밖 값은 엣지가 기동 시 거부하는데 그때는 이미 공장 안 장비가 재시작 루프다. 키보드 앞에서 막는다. 목록에 없는 키는 저장 불가 — 장비가 조용히 무시할 값이 '설정됨'으로 보이면 안 된다. - 정비 억제: 사유 필수, 최대 8시간(한 교대), 자동 만료. 감지와 기록은 그대로 계속되고 통보만 보류되며 그 보류도 원장에 status='suppressed'로 남는다 — 조사에서 '경보가 났지만 의도적으로 withheld됐다'를 볼 수 있어야 한다. - 교대 인수인계, 위험성평가, 설비 성능 추이, 설치 점검(/setup — 실제 상태 조회 기반). 증거·규정 - 감사로그 해시체인. 공유호스팅은 append-only 권한을 줄 수 없으니 '막는' 대신 '숨길 수 없게' 만든다. 수정·삭제·우회삽입이 전부 탐지되고(tools/verify_audit_chain.php, 손상 시 exit 1), 체인 이전 행은 손상이 아니라 '검증 불가 구간'으로 따로 센다 — 정상 시스템이 매번 빨간불을 켜면 아무도 이 도구를 안 본다. - 사고조사 패키지 1클릭: 전후 타임라인 + 통보 이력(누구에게 닿았는가) + 위험요인 + 조치 이력 + 서명란. 인쇄 CSS로 그대로 제출 가능. 사고 다음 날 반나절을 쓸 사람은 없다. - 이벤트→조치 직접 기록, 현장별 롤업(전역 계정만). 운영 - 일괄 확인(위급은 의도적으로 제외·2단계 확정), 키보드 트리아지(J/K/A/F/Enter), 모바일 레이아웃(44px 타깃), 보존기간 정리(tools/maintain.php), 백업/복구(tools/backup.php — www 안 출력은 거부), 데모 시드(tools/seed_demo.php). - tools/는 전부 CLI 전용이고 납품 시 move_detect_app/tools/에 www 밖으로 배치된다. 미착수 4건 (모델·하드웨어가 선행 조건) - 보호구·중장비 근접·화재 감지는 AGPL 아닌 가중치 확보 + HEF 컴파일이 관문이다. 감지기 배선·이벤트 계약·심각도·쿨다운·테스트까지 만들고 기본 비활성으로 둔다 (edge/detectors/pending.py). enabled=True인데 model=None이면 아무것도 하지 않도록 명시적으로 막았다 — "곧 됩니다" 상태로 켜 두면 현장은 감지되고 있다고 믿는다. - PLC 접점 협착 게이팅도 같은 이유로 인터페이스만. 검증: pytest 통과(skip 3 = 하드웨어·환경) / PHPUnit 221 (skip 0, +59). Chrome 실렌더로 신규 4화면 + 임계값 저장→config_version 증가→감사 기록→체인 검증→ 행 변조→탐지(exit 1) 전 경로 확인. cafe24 번들 + Pi 오프라인 번들(aarch64 휠 11개) 재생성, 소스 패리티 통과. 보안 자체점검: SQL 문자열 보간 0, innerHTML 0, 상태 변경 핸들러 전부 CSRF+RBAC.
373 lines
20 KiB
PHP
373 lines
20 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 are marked in the one field no ingest path writes: a device_id prefix. That makes
|
|
// --purge exact instead of "delete everything and hope".
|
|
const DEMO_PREFIX = 'demo-';
|
|
|
|
$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 = 'demo-seed'")->execute();
|
|
// 데모 채널/위험요인은 이름·검토자에 표식이 있다. 실제 운영 행을 지우지 않도록
|
|
// LIKE 로 좁힌다 — 시연용 DB 와 운영 DB 가 같은 호스트에 있는 경우가 실제로 있다.
|
|
$pdo->prepare("DELETE FROM move_alert_channels WHERE name LIKE '%(데모%'")->execute();
|
|
$pdo->prepare("DELETE FROM move_risk_controls WHERE reviewed_by = '안전관리자' AND site = 'factory-a'")->execute();
|
|
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-seed', $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', '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', '안전관리자 메일 (데모 · 사용 안 함)',
|
|
json_encode(['to' => ['safety@example.invalid']]), 'critical', 0, 0, 0, $now]);
|
|
$ch->execute(['factory-a', 'email', '공장장 에스컬레이션 (데모 · 사용 안 함)',
|
|
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, '안전관리자', $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');
|