diff --git a/db.sqlite b/db.sqlite new file mode 100644 index 0000000..1892691 Binary files /dev/null and b/db.sqlite differ diff --git a/equipment.json b/equipment.json deleted file mode 100644 index d476d52..0000000 --- a/equipment.json +++ /dev/null @@ -1,730 +0,0 @@ -{ - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Аспирационная установка 1", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inAsp1Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Аспирационная установка 2", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inAsp2Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Аспирационная установка 3", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inAsp3Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Аспирационная установка 4", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inAsp4Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Аспирационная установка 5", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inAsp5Run", - "value": 1, - "zone": null - }, - { - "connect_time": "01.02.2025 07:20", - "isServicing": false, - "name": "Аспирационная установка 5а на конвейре поз. 74", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inAU5aRun", - "value": 1, - "zone": null - }, - { - "connect_time": "01.02.2025 07:20", - "isServicing": false, - "name": "Аспирационная установка 5а на конвейре поз. 74 - работа вентилятора", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inAU5aFanRun", - "value": 1, - "zone": null - }, - { - "connect_time": "01.02.2025 07:20", - "isServicing": false, - "name": "Аспирационная установка 6 на конвейере поз. 73", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inAU6Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 1", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV1Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 10", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV10Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 11", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV11Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 2", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV2Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 3", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV3Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 4", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV4Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 5", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV5Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 6", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV6Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 7", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV7Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 8", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV8Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор 9", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inV9Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Вибратор горизонтальной центрифуги поз. 21", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos21VibroRun", - "value": 1, - "zone": null - }, - { - "connect_time": "01.02.2025 07:17", - "isServicing": false, - "name": "Грохот поз. 101", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos101Run", - "value": 1, - "zone": null - }, - { - "connect_time": "01.02.2025 07:17", - "isServicing": false, - "name": "Грохот поз. 115", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos115Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Грохот поз. 12", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos12Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Грохот поз. 130", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos130Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Грохот поз. 15", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos15Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Грохот поз. 17", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos17Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Грохот поз. 20", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos20Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Делитель потока в зумпфы НКС и КС", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos20.5Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Дробилка поз. 9", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos9Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Дробилка поз. 9 - маслонасос", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos9OilPumpRun", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Железоотделитель поз. 6", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos6Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер ленточный поз. 22.2", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos22.2DKS", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер поз. 13", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos13DKS", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер поз. 14", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos14DKS", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер поз. 18", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos18DKS", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер поз. 22", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos22DKS", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер поз. 22.3", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos22.3DKS", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер поз. 4", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos4DKS", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Конвейер поз. 49", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos49DKS", - "value": 1, - "zone": null - }, - { - "connect_time": "01.02.2025 00:08", - "isServicing": false, - "name": "Ленточный фильтр-пресс поз. 122", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos122Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Ленточный фильтр-пресс поз. 44", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos44Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Маслонасос центрифуги поз. 21", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos21OilPumpRun", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Маслонасос центрифуги поз. 72", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos72OilPumpRun", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Мешалка зумпфа питания ленточного фильтр-пресса поз. 42", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos42Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 10", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos10Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 11", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos11Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 32", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos32Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 33", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos33Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 40", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos40Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 41", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos41Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 43", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos43Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 46", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos46Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Насос поз. 61", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos61Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Питатель ленточный поз. 22.1", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos22.1DKS", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Питатель поз. 1", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos1Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:08", - "isServicing": false, - "name": "Питатель поз. 18.1", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos18.1Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Питатель поз. 19", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos19Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Плужковый сбрасыватель поз. 57", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos57Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Плужковый сбрасыватель поз. 62", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos62BrushRun", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Плужковый сбрасыватель поз.62", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos62Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Плужковый сбрасыватель поз. 63", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos63Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Пробоотборник поз. 51", - "position": "Не задано", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos51Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Пробоотборник поз. 53", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos53Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Пробоотборник поз. 53.1", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos53.1Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Пробоотборник поз. 7", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos7Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Проборазделочная машина поз. 53.2", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos53.2Run", - "value": 0, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Сгуститель радиальный поз. 37", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos37Run", - "value": 2, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Центрифуга горизонтальная поз. 21", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos21Run", - "value": 1, - "zone": null - }, - { - "connect_time": "31.01.2025 20:39", - "isServicing": false, - "name": "Центрифуга поз. 102", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos102Run", - "value": 1, - "zone": null - }, - { - "connect_time": "02.02.2025 18:58", - "isServicing": false, - "name": "Центрифуга поз. 103", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos103Run", - "value": 0, - "zone": null - }, - { - "connect_time": "31.01.2025 20:39", - "isServicing": false, - "name": "Центрифуга шнеково-фильтрующая поз. 113", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos113Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 05:07", - "isServicing": false, - "name": "Центрифуга шнеково-фильтрующая поз. 114", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.ZG02.Area I.inPos114Run", - "value": 1, - "zone": null - }, - { - "connect_time": "03.02.2025 08:09", - "isServicing": false, - "name": "Центрифуга шнеково-фильтрующая поз. 72", - "position": " ", - "quality": "0x000000C0", - "tag": "SIEMENSPLC.AZG01.Area I.inPos72Run", - "value": 0, - "zone": null - } \ No newline at end of file diff --git a/error.json b/error.json deleted file mode 100644 index d9451d5..0000000 --- a/error.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "Аспирационная установка 1": [ - { - "alarmCode": 2, - "description": "Перегрев двигателя. Необходимо проверить систему охлаждения.", - "timestamp": "03.02.2025 08:09" - }, - { - "alarmCode": 1, - "description": "Низкий уровень масла.", - "timestamp": "03.02.2025 08:15" - } - ], - "Аспирационная установка 2": [ - { - "alarmCode": 1, - "description": "Низкий уровень масла. Проверьте систему смазки.", - "timestamp": "03.02.2025 08:10" - } - ], - "Аспирационная установка 3": [ - { - "alarmCode": 2, - "description": "Ошибка системы охлаждения.", - "timestamp": "03.02.2025 08:11" - }, - { - "alarmCode": 3, - "description": "Перегрузка электросети.", - "timestamp": "03.02.2025 08:20" - } - ], - "Аспирационная установка 4": [ - { - "alarmCode": 2, - "description": "Перегрев системы.", - "timestamp": "03.02.2025 08:12" - } - ], - "Аспирационная установка 5": [ - { - "alarmCode": 1, - "description": "Низкое давление масла.", - "timestamp": "03.02.2025 08:13" - }, - { - "alarmCode": 3, - "description": "Сбой питания.", - "timestamp": "03.02.2025 08:25" - } - ], - "Аспирационная установка 6": [ - { - "alarmCode": 2, - "description": "Ошибка датчика температуры.", - "timestamp": "03.02.2025 08:14" - } - ], - "Аспирационная установка 7": [ - { - "alarmCode": 1, - "description": "Низкий уровень жидкости.", - "timestamp": "03.02.2025 08:16" - } - ], - "Аспирационная установка 8": [ - { - "alarmCode": 3, - "description": "Аварийное отключение.", - "timestamp": "03.02.2025 08:17" - } - ] - } - \ No newline at end of file diff --git a/index.ts b/index.ts index f6745f4..9916549 100644 --- a/index.ts +++ b/index.ts @@ -1,250 +1,26 @@ -import { Elysia } from 'elysia' -import { cors } from '@elysiajs/cors' -import { Database } from "bun:sqlite"; +import { Elysia } from 'elysia'; +import { cors } from '@elysiajs/cors'; +import { runMigrations, runSeeders } from './src/db/migrations'; +import { errorResolveRoutes } from './src/endpoints/errorResolve'; +import { errorsRoutes } from './src/endpoints/errors'; +import { sensorDetailsRoutes } from './src/endpoints/sensorDetails'; +import { sensorsRoutes } from './src/endpoints/sensors'; -const db = new Database("db.sqlite"); +runMigrations(); +runSeeders(); -interface SensorRow { - id: number; - connect_time: string; - isServicing: boolean; - name: string; - position: string; - quality: string; - tag: string; - value: number; - zone: string | null; -} - -interface SensorCount { - count: number; -} - -interface ErrorRow { - id: number; - sensor_id: number; - alarmCode: number; - description: string; - timestamp: string; -} - -interface SensorDetail { - id: number; - sensor_id: number; - description: string; -} - -// Создаём нормализованные таблицы, если их ещё нет -db.exec(` - CREATE TABLE IF NOT EXISTS sensors ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - connect_time TEXT, - isServicing BOOLEAN, - name TEXT UNIQUE, - position TEXT, - quality TEXT, - tag TEXT, - value INTEGER, - zone TEXT - ); - - CREATE TABLE IF NOT EXISTS errors ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sensor_id INTEGER, - alarmCode INTEGER, - description TEXT, - timestamp TEXT, - FOREIGN KEY(sensor_id) REFERENCES sensors(id) - ); - - CREATE TABLE IF NOT EXISTS sensor_details ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sensor_id INTEGER UNIQUE, - description TEXT, - FOREIGN KEY(sensor_id) REFERENCES sensors(id) - ); -`); - -// Если таблица sensors пуста – вставляем тестовые данные -const sensorsCount = (db.prepare('SELECT COUNT(*) as count FROM sensors').get() as SensorCount).count; -if (sensorsCount === 0) { - const insertSensor = db.prepare(` - INSERT INTO sensors (connect_time, isServicing, name, position, quality, tag, value, zone) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - `); - insertSensor.run("03.02.2025 08:09", false, "Аспирационная установка 1", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inAsp1Run", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Аспирационная установка 2", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inAsp2Run", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Аспирационная установка 3", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inAsp3Run", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Аспирационная установка 4", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inAsp4Run", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Аспирационная установка 5", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inAsp5Run", 1, null); - insertSensor.run("01.02.2025 07:20", false, "Аспирационная установка 6 на конвейере поз. 73", " ", "0x000000C0", "SIEMENSPLC.ZG02.Area I.inAU5aRun", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Питатель поз. 1", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos1Run", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Дробилка поз. 9", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos9Run", 0, null); - insertSensor.run("03.02.2025 08:09", false, "Грохот поз. 12", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos12Run", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Конвейер поз. 14", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos14DKS", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Конвейер поз. 13", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos13DKS", 1, null); - insertSensor.run("03.02.2025 08:09", false, "Конвейер поз. 4", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos4DKS", 1, null); -} - -// Если таблица errors пуста – вставляем тестовые данные -const errorsCount = (db.prepare('SELECT COUNT(*) as count FROM errors').get() as SensorCount).count; -if (errorsCount === 0) { - const insertError = db.prepare(` - INSERT INTO errors (sensor_id, alarmCode, description, timestamp) - VALUES (?, ?, ?, ?) - `); - // Функция для получения sensor_id по имени - const getSensorId = (name: string): number | undefined => { - const row = db.prepare("SELECT id FROM sensors WHERE name = ?").get(name) as { id: number } | undefined; - return row?.id; - }; - - let sensorId = getSensorId("Аспирационная установка 1"); - if (sensorId !== undefined) { - insertError.run(sensorId, 2, "Перегрев двигателя. Необходимо проверить систему охлаждения.", "03.02.2025 08:09"); - insertError.run(sensorId, 1, "Низкий уровень масла.", "03.02.2025 08:15"); - } - sensorId = getSensorId("Аспирационная установка 2"); - if (sensorId !== undefined) { - insertError.run(sensorId, 1, "Низкий уровень масла. Проверьте систему смазки.", "03.02.2025 08:10"); - } - sensorId = getSensorId("Аспирационная установка 3"); - if (sensorId !== undefined) { - insertError.run(sensorId, 2, "Ошибка системы охлаждения.", "03.02.2025 08:11"); - insertError.run(sensorId, 3, "Перегрузка электросети.", "03.02.2025 08:20"); - } - sensorId = getSensorId("Аспирационная установка 4"); - if (sensorId !== undefined) { - insertError.run(sensorId, 2, "Перегрев системы.", "03.02.2025 08:12"); - } - sensorId = getSensorId("Аспирационная установка 5"); - if (sensorId !== undefined) { - insertError.run(sensorId, 1, "Низкое давление масла.", "03.02.2025 08:13"); - insertError.run(sensorId, 3, "Сбой питания.", "03.02.2025 08:25"); - } - sensorId = getSensorId("Аспирационная установка 6 на конвейере поз. 73"); - if (sensorId !== undefined) { - insertError.run(sensorId, 2, "Ошибка датчика температуры.", "03.02.2025 08:14"); - } - sensorId = getSensorId("Питатель поз. 1"); - // Если ошибок для данного оборудования нет, то пропускаем -} - -// Если таблица sensor_details пуста – вставляем тестовые данные -const detailsCount = (db.prepare('SELECT COUNT(*) as count FROM sensor_details').get() as SensorCount).count; -if (detailsCount === 0) { - const insertDetail = db.prepare(` - INSERT INTO sensor_details (sensor_id, description) - VALUES (?, ?) - `); - const getSensorId = (name: string): number | undefined => { - const row = db.prepare("SELECT id FROM sensors WHERE name = ?").get(name) as { id: number } | undefined; - return row?.id; - }; - - let sensorId = getSensorId("Аспирационная установка 1"); - if (sensorId !== undefined) { - insertDetail.run(sensorId, "Описание: Аспирационная установка 1. Основные характеристики..."); - } - sensorId = getSensorId("Аспирационная установка 2"); - if (sensorId !== undefined) { - insertDetail.run(sensorId, "Описание: Аспирационная установка 2. Основные характеристики..."); - } - sensorId = getSensorId("Аспирационная установка 3"); - if (sensorId !== undefined) { - insertDetail.run(sensorId, "Описание: Аспирационная установка 3. Основные характеристики..."); - } - sensorId = getSensorId("Аспирационная установка 4"); - if (sensorId !== undefined) { - insertDetail.run(sensorId, "Описание: Аспирационная установка 4. Основные характеристики..."); - } - sensorId = getSensorId("Аспирационная установка 5"); - if (sensorId !== undefined) { - insertDetail.run(sensorId, "Описание: Аспирационная установка 5. Основные характеристики..."); - } - sensorId = getSensorId("Аспирационная установка 6 на конвейере поз. 73"); - if (sensorId !== undefined) { - insertDetail.run(sensorId, "Описание: Аспирационная установка 6 на конвейере поз. 73. Основные характеристики..."); - } -} - -// Создаём сервер Elysia с необходимыми эндпоинтами const app = new Elysia() .use(cors()) - // Эндпоинт для получения данных оборудования - .get('/api/v2/sensors', () => { - const sensors = db.prepare("SELECT * FROM sensors").all() as SensorRow[]; - return { - error: "", - items: sensors, - status: 0, - total: sensors.length - }; - }) - // Эндпоинт для получения ошибок, сгруппированных по оборудованию (с JOIN для имени) - .get('/api/v2/errors', () => { - const errorsRows = db.prepare(` - SELECT e.id, e.sensor_id, e.alarmCode, e.description, e.timestamp, s.name as sensor_name - FROM errors e - JOIN sensors s ON s.id = e.sensor_id - `).all() as (ErrorRow & { sensor_name: string })[]; - - const groupedErrors = errorsRows.reduce>( - (acc, curr) => { - if (!acc[curr.sensor_name]) { - acc[curr.sensor_name] = []; - } - acc[curr.sensor_name].push({ - alarmCode: curr.alarmCode, - description: curr.description, - timestamp: curr.timestamp - }); - return acc; - }, - {} - ); - return groupedErrors; - }) - // Эндпоинт для "снятия" ошибки - // Ожидается JSON: { sensorName: string, alarmCode?: number } - .post('/api/v2/errors/resolve', async ({ request }) => { - const { sensorName, alarmCode } = await request.json() as { sensorName: string; alarmCode?: number }; - - // Получаем sensor_id по sensorName - const sensor = db.prepare("SELECT * FROM sensors WHERE name = ?").get(sensorName) as SensorRow | undefined; - if (!sensor) { - return { error: `Оборудование с именем ${sensorName} не найдено` }; - } - - if (alarmCode !== undefined) { - db.prepare(` - DELETE FROM errors WHERE sensor_id = ? AND alarmCode = ? - `).run(sensor.id, alarmCode); - } else { - db.prepare(` - DELETE FROM errors WHERE sensor_id = ? - `).run(sensor.id); - } - // Если оборудование находится в аварийном состоянии (value === 2), сбрасываем его состояние в 0 - if (sensor.value === 2) { - db.prepare("UPDATE sensors SET value = 0 WHERE id = ?").run(sensor.id); - } - return { message: "Ошибка успешно снята" } - }) - // Новый эндпоинт для получения описания оборудования по sensor_name - .get('/api/v2/sensor-details/:sensorName', ({ params }) => { - const sensorName = params.sensorName; - const detail = db.prepare(` - SELECT sd.id, s.name, sd.description - FROM sensor_details sd - JOIN sensors s ON s.id = sd.sensor_id - WHERE s.name = ? - `).get(sensorName) as (SensorDetail & { name: string }) | undefined; - if (!detail) { - return { error: `Описание для оборудования '${sensorName}' не найдено.` }; - } - return detail; + .group("/api/v2", (group) => { + sensorsRoutes(group as any); + errorsRoutes(group as any); + errorResolveRoutes(group as any); + sensorDetailsRoutes(group as any); + return group; }) .listen(3030); console.log(`Server running on http://localhost:3030`); + +// Импортируем periodicUpdates как побочный эффект: +import "./src/periodicUpdates"; diff --git a/src/db/database.ts b/src/db/database.ts new file mode 100644 index 0000000..c72f00c --- /dev/null +++ b/src/db/database.ts @@ -0,0 +1,4 @@ +import { Database } from "bun:sqlite"; + +const db = new Database("db.sqlite"); +export default db; diff --git a/src/db/migrations.ts b/src/db/migrations.ts new file mode 100644 index 0000000..06d8694 --- /dev/null +++ b/src/db/migrations.ts @@ -0,0 +1,94 @@ +import type { SensorCount } from '../interfaces/SensorRow'; +import db from './database'; + + +export function runMigrations(): void { + db.exec(` + CREATE TABLE IF NOT EXISTS sensors ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + connect_time TEXT, + isServicing BOOLEAN, + name TEXT UNIQUE, + position TEXT, + quality TEXT, + tag TEXT, + value INTEGER, + zone TEXT + ); + + CREATE TABLE IF NOT EXISTS errors ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sensor_id INTEGER, + alarmCode INTEGER, + description TEXT, + timestamp TEXT, + FOREIGN KEY(sensor_id) REFERENCES sensors(id) + ); + + CREATE TABLE IF NOT EXISTS sensor_details ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sensor_id INTEGER UNIQUE, + description TEXT, + FOREIGN KEY(sensor_id) REFERENCES sensors(id) + ); + `); +} + +export function runSeeders(): void { + const sensorsCount = (db.prepare('SELECT COUNT(*) as count FROM sensors').get() as SensorCount).count; + if (sensorsCount === 0) { + const insertSensor = db.prepare(` + INSERT INTO sensors (connect_time, isServicing, name, position, quality, tag, value, zone) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `); + // Вставляем только нужные датчики + insertSensor.run("01.02.2025 07:20", false, "Аспирационная установка 6 на конвейере поз. 73", " ", "0x000000C0", "SIEMENSPLC.ZG02.Area I.inAU5aRun", 1, null); + insertSensor.run("03.02.2025 08:09", false, "Питатель поз. 1", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos1Run", 1, null); + insertSensor.run("03.02.2025 08:09", false, "Дробилка поз. 9", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos9Run", 0, null); + insertSensor.run("03.02.2025 08:09", false, "Грохот поз. 12", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos12Run", 1, null); + insertSensor.run("03.02.2025 08:09", false, "Конвейер поз. 14", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos14DKS", 1, null); + insertSensor.run("03.02.2025 08:09", false, "Конвейер поз. 13", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos13DKS", 1, null); + insertSensor.run("03.02.2025 08:09", false, "Конвейер поз. 4", " ", "0x000000C0", "SIEMENSPLC.AZG01.Area I.inPos4DKS", 1, null); + } + + const detailsCount = (db.prepare('SELECT COUNT(*) as count FROM sensor_details').get() as SensorCount).count; + if (detailsCount === 0) { + const insertDetail = db.prepare(` + INSERT INTO sensor_details (sensor_id, description) + VALUES (?, ?) + `); + const getSensorId = (name: string): number | undefined => { + const row = db.prepare("SELECT id FROM sensors WHERE name = ?").get(name) as { id: number } | undefined; + return row?.id; + }; + + let sensorId = getSensorId("Аспирационная установка 6 на конвейере поз. 73"); + if (sensorId !== undefined) { + insertDetail.run(sensorId, "Описание: Аспирационная установка 6 на конвейере поз. 73. Основные характеристики..."); + } + sensorId = getSensorId("Питатель поз. 1"); + if (sensorId !== undefined) { + insertDetail.run(sensorId, "Описание: Питатель поз. 1. Основные характеристики..."); + } + sensorId = getSensorId("Дробилка поз. 9"); + if (sensorId !== undefined) { + insertDetail.run(sensorId, "Описание: Дробилка поз. 9. Основные характеристики..."); + } + sensorId = getSensorId("Грохот поз. 12"); + if (sensorId !== undefined) { + insertDetail.run(sensorId, "Описание: Грохот поз. 12. Основные характеристики..."); + } + sensorId = getSensorId("Конвейер поз. 14"); + if (sensorId !== undefined) { + insertDetail.run(sensorId, "Описание: Конвейер поз. 14. Основные характеристики..."); + } + sensorId = getSensorId("Конвейер поз. 13"); + if (sensorId !== undefined) { + insertDetail.run(sensorId, "Описание: Конвейер поз. 13. Основные характеристики..."); + } + sensorId = getSensorId("Конвейер поз. 4"); + if (sensorId !== undefined) { + insertDetail.run(sensorId, "Описание: Конвейер поз. 4. Основные характеристики..."); + } + } +} diff --git a/src/endpoints/errorResolve.ts b/src/endpoints/errorResolve.ts new file mode 100644 index 0000000..5c74b34 --- /dev/null +++ b/src/endpoints/errorResolve.ts @@ -0,0 +1,29 @@ +import db from '../db/database'; + +import { Elysia } from 'elysia'; +import type { SensorRow } from '../interfaces/SensorRow'; + +export function errorResolveRoutes(group: Elysia): Elysia { + return group.post("/errors/resolve", async ({ request }) => { + const { sensorName, alarmCode } = await request.json() as { sensorName: string; alarmCode?: number }; + + const sensor = db.prepare("SELECT * FROM sensors WHERE name = ?").get(sensorName) as SensorRow | undefined; + if (!sensor) { + return { error: `Оборудование с именем ${sensorName} не найдено` }; + } + + if (alarmCode !== undefined) { + db.prepare(` + DELETE FROM errors WHERE sensor_id = ? AND alarmCode = ? + `).run(sensor.id, alarmCode); + } else { + db.prepare(` + DELETE FROM errors WHERE sensor_id = ? + `).run(sensor.id); + } + if (sensor.value === 2) { + db.prepare("UPDATE sensors SET value = 0 WHERE id = ?").run(sensor.id); + } + return { message: "Ошибка успешно снята" }; + }); +} diff --git a/src/endpoints/errors.ts b/src/endpoints/errors.ts new file mode 100644 index 0000000..1674b63 --- /dev/null +++ b/src/endpoints/errors.ts @@ -0,0 +1,30 @@ +import db from '../db/database'; + +import { Elysia } from 'elysia'; +import type { ErrorRow } from '../interfaces/ErrorRow'; + +export function errorsRoutes(group: Elysia): Elysia { + return group.get("/errors", () => { + const errorsRows = db.prepare(` + SELECT e.id, e.sensor_id, e.alarmCode, e.description, e.timestamp, s.name as sensor_name + FROM errors e + JOIN sensors s ON s.id = e.sensor_id + `).all() as (ErrorRow & { sensor_name: string })[]; + + const groupedErrors = errorsRows.reduce>( + (acc, curr) => { + if (!acc[curr.sensor_name]) { + acc[curr.sensor_name] = []; + } + acc[curr.sensor_name].push({ + alarmCode: curr.alarmCode, + description: curr.description, + timestamp: curr.timestamp + }); + return acc; + }, + {} + ); + return groupedErrors; + }); +} diff --git a/src/endpoints/sensorDetails.ts b/src/endpoints/sensorDetails.ts new file mode 100644 index 0000000..ab6eeef --- /dev/null +++ b/src/endpoints/sensorDetails.ts @@ -0,0 +1,20 @@ +import db from '../db/database'; + +import { Elysia } from 'elysia'; +import type { SensorDetail } from '../interfaces/SensorDetail'; + +export function sensorDetailsRoutes(group: Elysia): Elysia { + return group.get("/sensor-details/:sensorName", ({ params }) => { + const sensorName = params.sensorName; + const detail = db.prepare(` + SELECT sd.id, s.name, sd.description + FROM sensor_details sd + JOIN sensors s ON s.id = sd.sensor_id + WHERE s.name = ? + `).get(sensorName) as (SensorDetail & { name: string }) | undefined; + if (!detail) { + return { error: `Описание для оборудования '${sensorName}' не найдено.` }; + } + return detail; + }); +} diff --git a/src/endpoints/sensors.ts b/src/endpoints/sensors.ts new file mode 100644 index 0000000..caf1475 --- /dev/null +++ b/src/endpoints/sensors.ts @@ -0,0 +1,17 @@ +import db from '../db/database'; + +import { Elysia } from 'elysia'; +import type { SensorRow } from '../interfaces/SensorRow'; + + +export function sensorsRoutes(group: Elysia): Elysia { + return group.get("/sensors", () => { + const sensors = db.prepare("SELECT * FROM sensors").all() as SensorRow[]; + return { + error: "", + items: sensors, + status: 0, + total: sensors.length + }; + }); + } \ No newline at end of file diff --git a/src/interfaces/ErrorRow.ts b/src/interfaces/ErrorRow.ts new file mode 100644 index 0000000..6bb1419 --- /dev/null +++ b/src/interfaces/ErrorRow.ts @@ -0,0 +1,8 @@ +export interface ErrorRow { + id: number; + sensor_id: number; + alarmCode: number; + description: string; + timestamp: string; + } + \ No newline at end of file diff --git a/src/interfaces/SensorDetail.ts b/src/interfaces/SensorDetail.ts new file mode 100644 index 0000000..1682763 --- /dev/null +++ b/src/interfaces/SensorDetail.ts @@ -0,0 +1,6 @@ +export interface SensorDetail { + id: number; + sensor_id: number; + description: string; + } + \ No newline at end of file diff --git a/src/interfaces/SensorRow.ts b/src/interfaces/SensorRow.ts new file mode 100644 index 0000000..b7ea58b --- /dev/null +++ b/src/interfaces/SensorRow.ts @@ -0,0 +1,16 @@ +export interface SensorRow { + id: number; + connect_time: string; + isServicing: boolean; + name: string; + position: string; + quality: string; + tag: string; + value: number; + zone: string | null; + } + + export interface SensorCount { + count: number; + } + \ No newline at end of file diff --git a/src/periodicUpdates.ts b/src/periodicUpdates.ts new file mode 100644 index 0000000..654bb38 --- /dev/null +++ b/src/periodicUpdates.ts @@ -0,0 +1,84 @@ +import db from './db/database'; +import type { SensorCount, SensorRow } from './interfaces/SensorRow'; + + +const updateInterval = 30000; // 30 секунд + +// Периодическое обновление аварийного состояния: +setInterval(() => { + const currentCount = (db.prepare("SELECT COUNT(*) as count FROM sensors WHERE value = 2").get() as SensorCount).count; + if (currentCount >= 3) { + console.log("Максимальное количество датчиков с аварийным состоянием уже достигнуто."); + return; + } + + const availableSensors = db.prepare("SELECT * FROM sensors WHERE value != 2").all() as SensorRow[]; + if (availableSensors.length === 0) return; + + const maxToUpdate = Math.min(3 - currentCount, availableSensors.length); + const countToUpdate = Math.floor(Math.random() * maxToUpdate) + 1; + + const selectedSensors: SensorRow[] = []; + while (selectedSensors.length < countToUpdate) { + const randomIndex = Math.floor(Math.random() * availableSensors.length); + const sensor = availableSensors[randomIndex]; + if (!selectedSensors.find(s => s.id === sensor.id)) { + selectedSensors.push(sensor); + } + } + + const errorDescriptions = [ + "Перегрев системы.", + "Ошибка датчика.", + "Низкий уровень масла.", + "Сбой питания.", + "Перегрузка электросети." + ]; + const possibleAlarmCodes = [1, 2, 3]; + + selectedSensors.forEach(sensor => { + db.prepare("UPDATE sensors SET value = 2 WHERE id = ?").run(sensor.id); + const numErrors = Math.floor(Math.random() * 2) + 1; + for (let i = 0; i < numErrors; i++) { + const alarmCode = possibleAlarmCodes[Math.floor(Math.random() * possibleAlarmCodes.length)]; + const description = errorDescriptions[Math.floor(Math.random() * errorDescriptions.length)]; + const timestamp = new Date().toLocaleString("ru-RU"); + db.prepare("INSERT INTO errors (sensor_id, alarmCode, description, timestamp) VALUES (?, ?, ?, ?)") + .run(sensor.id, alarmCode, description, timestamp); + } + }); + + console.log(`Периодическое обновление: для ${countToUpdate} датчика(ов) установлено аварийное состояние и добавлены ошибки.`); +}, updateInterval); + +// Периодическое включение выключенных датчиков: +setInterval(() => { + const offSensors = db.prepare("SELECT * FROM sensors WHERE value = 0").all() as SensorRow[]; + const offCount = offSensors.length; + if (offCount === 0) { + console.log("Нет выключенных датчиков для обновления."); + return; + } + + const maxToUpdate = Math.floor(offCount / 2); + if (maxToUpdate < 1) { + console.log("Слишком мало выключенных датчиков для обновления."); + return; + } + + const countToUpdate = Math.floor(Math.random() * maxToUpdate) + 1; + const selectedSensors: SensorRow[] = []; + while (selectedSensors.length < countToUpdate) { + const randomIndex = Math.floor(Math.random() * offSensors.length); + const sensor = offSensors[randomIndex]; + if (!selectedSensors.find(s => s.id === sensor.id)) { + selectedSensors.push(sensor); + } + } + + selectedSensors.forEach(sensor => { + db.prepare("UPDATE sensors SET value = 1 WHERE id = ?").run(sensor.id); + }); + + console.log(`Периодическое обновление: для ${countToUpdate} выключенных датчика(ов) установлено состояние 'on' (value = 1).`); +}, updateInterval);