Compare commits
6 Commits
5d18bb7965
...
dev-artem
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc8bfb6691 | ||
| fe9e7b5438 | |||
| 3c94cd92c1 | |||
| 5b97022116 | |||
| 7c67b9e34a | |||
| 3841faa810 |
@@ -10,9 +10,7 @@ COPY src ./src
|
||||
|
||||
RUN npm run build && npm prune --omit=dev
|
||||
|
||||
# app/public/index.html has content for video preview
|
||||
# TODO move all static files (html, mappers) to a separate folder "assets"
|
||||
COPY public ./public
|
||||
COPY assets ./assets
|
||||
|
||||
ENV NODE_ENV=production
|
||||
CMD ["node", "dist/index.js"]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export const cloudIngestUrl = process.env.CLOUD_INGEST_URL as string
|
||||
export const demoCloudIngestUrl = process.env.DEMO_CLOUD_INGEST_URL as string
|
||||
|
||||
export function postCloudIngest(body: unknown): Promise<Response> {
|
||||
return fetch(cloudIngestUrl, {
|
||||
@@ -10,3 +11,14 @@ export function postCloudIngest(body: unknown): Promise<Response> {
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export function postDemoCloudIngest(body: unknown): Promise<Response> {
|
||||
return fetch(demoCloudIngestUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'x-api-key': process.env.CLOUD_INGEST_API_KEY as string,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { postCloudIngest } from '../cloud-ingest.js'
|
||||
import { log } from '../helpers/log.js'
|
||||
import { createMetricMapper, type MappedMetric } from '../mapping.js'
|
||||
@@ -5,8 +8,13 @@ import type { TopicHandler } from '../types.js'
|
||||
|
||||
const REGISTER_COUNT = 125
|
||||
|
||||
const defaultMappingFile = join(
|
||||
dirname(fileURLToPath(import.meta.url)),
|
||||
'../../assets/edge5-modbus.json',
|
||||
)
|
||||
|
||||
const mapper = createMetricMapper({
|
||||
filePath: process.env.EDGE5_MODBUS_V2_MAPPING_FILE as string,
|
||||
filePath: process.env.EDGE5_MODBUS_V2_MAPPING_FILE ?? defaultMappingFile,
|
||||
})
|
||||
|
||||
function parseValues(payload: Buffer): number[] {
|
||||
|
||||
113
app/src/handlers/edge5-modbus-v3.ts
Normal file
113
app/src/handlers/edge5-modbus-v3.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import { postCloudIngest, postDemoCloudIngest } from '../cloud-ingest.js'
|
||||
import { log } from '../helpers/log.js'
|
||||
import type { TopicHandler } from '../types.js'
|
||||
|
||||
const EDGE = 'edge5-v3'
|
||||
const REGISTER_COUNT = 24
|
||||
|
||||
// Фиксируем интерпретацию
|
||||
const TAGS = [
|
||||
'edge5-v3-wk',
|
||||
'edge5-v3-pin',
|
||||
'edge5-v3-hk',
|
||||
'edge5-v3-mk',
|
||||
'edge5-v3-mrot',
|
||||
'edge5-v3-h',
|
||||
'edge5-v3-vw',
|
||||
'edge5-v3-pdk',
|
||||
'edge5-v3-h2s',
|
||||
'edge5-v3-t',
|
||||
'edge5-v3-nrot',
|
||||
'edge5-v3-vsp',
|
||||
] as const
|
||||
|
||||
// из них выводим на дашборд семь виджетов
|
||||
const CLOUD_INGEST_TAGS = new Set<string>([
|
||||
'edge5-v3-wk',
|
||||
'edge5-v3-hk',
|
||||
'edge5-v3-vw',
|
||||
'edge5-v3-pdk',
|
||||
'edge5-v3-h2s',
|
||||
'edge5-v3-nrot',
|
||||
'edge5-v3-vsp',
|
||||
])
|
||||
|
||||
type Edge5ModbusV3Metric = {
|
||||
edge: string
|
||||
timestamp: string
|
||||
tag: string
|
||||
value: number | null
|
||||
}
|
||||
|
||||
function toFloatCDAB(reg0: number, reg1: number): number | null {
|
||||
const buf = Buffer.allocUnsafe(4)
|
||||
buf.writeUInt16BE(reg1, 0)
|
||||
buf.writeUInt16BE(reg0, 2)
|
||||
return buf.readFloatBE(0)
|
||||
}
|
||||
|
||||
function parseValues(payload: Buffer): number[] {
|
||||
const values = JSON.parse(payload.toString('utf8')) as number[]
|
||||
assertRegisterCount(values)
|
||||
return values
|
||||
}
|
||||
|
||||
function assertRegisterCount(values: number[]): void {
|
||||
if (values.length !== REGISTER_COUNT) {
|
||||
throw new Error(`Expected ${REGISTER_COUNT} modbus values, got ${values.length}`)
|
||||
}
|
||||
}
|
||||
|
||||
function toMetrics(values: number[], timestamp: string): Edge5ModbusV3Metric[] {
|
||||
const metrics: Edge5ModbusV3Metric[] = []
|
||||
|
||||
for (let i = 0; i < values.length; i += 2) {
|
||||
const tag = TAGS[i / 2]
|
||||
const value = toFloatCDAB(values[i], values[i + 1]); // null is possible to send
|
||||
|
||||
metrics.push({
|
||||
edge: EDGE,
|
||||
timestamp,
|
||||
tag,
|
||||
value,
|
||||
})
|
||||
}
|
||||
|
||||
return metrics
|
||||
}
|
||||
|
||||
async function postMetrics(metrics: Edge5ModbusV3Metric[]): Promise<void> {
|
||||
const toPost = metrics.filter((metric) => CLOUD_INGEST_TAGS.has(metric.tag))
|
||||
const errors: Error[] = []
|
||||
|
||||
for (const metric of toPost) {
|
||||
try {
|
||||
const response = await postCloudIngest(metric)
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
throw new Error(text || `${response.status} ${response.statusText}`)
|
||||
}
|
||||
|
||||
void postDemoCloudIngest(metric); // для демо-системы
|
||||
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
errors.push(new Error(`${metric.tag}: ${message}`))
|
||||
console.error('edge5.modbus.v3.metric.failed', metric.tag, message)
|
||||
}
|
||||
}
|
||||
|
||||
log(`edge5.modbus.v3.data ↑ ${toPost.length} tags`);
|
||||
|
||||
if (errors.length) {
|
||||
throw new Error(`Failed to post ${errors.length}/${toPost.length} edge5 modbus v3 metrics`)
|
||||
}
|
||||
}
|
||||
|
||||
export const handleEdge5ModbusV3: TopicHandler = async (topic, payload) => {
|
||||
const timestamp = new Date().toISOString();
|
||||
const values = parseValues(payload);
|
||||
const metrics = toMetrics(values, timestamp);
|
||||
await postMetrics(metrics);
|
||||
}
|
||||
@@ -9,10 +9,10 @@ type Edge5iiModbusMetric = {
|
||||
edge: string
|
||||
timestamp: string
|
||||
tag: string
|
||||
value: number
|
||||
value: number | null
|
||||
};
|
||||
|
||||
function toFloatCDAB(reg0: number, reg1: number): number {
|
||||
function toFloatCDAB(reg0: number, reg1: number): number | null {
|
||||
const buf = Buffer.allocUnsafe(4)
|
||||
buf.writeUInt16BE(reg1, 0)
|
||||
buf.writeUInt16BE(reg0, 2)
|
||||
@@ -36,14 +36,7 @@ function toMetrics(values: number[], timestamp: string): Edge5iiModbusMetric[] {
|
||||
|
||||
for (let i = 0; i < values.length; i += 2) {
|
||||
const tag = `register-${String(i).padStart(3, '0')}`
|
||||
const value = toFloatCDAB(values[i], values[i + 1])
|
||||
if (isNaN(value)) {
|
||||
log(
|
||||
`${EDGE}.modbus: не удалось собрать число для ${tag}, ` +
|
||||
`исходные values[${i}]=${values[i]}, values[${i + 1}]=${values[i + 1]}, пропуск`,
|
||||
)
|
||||
continue
|
||||
};
|
||||
const value = toFloatCDAB(values[i], values[i + 1]); // null is possible to send
|
||||
|
||||
metrics.push({
|
||||
edge: EDGE,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { register } from '../registry.js';
|
||||
import { handleDemoPlc } from './demo-plc.js';
|
||||
import { handleDemoModbus } from './demo-modbus.js';
|
||||
import { handleEdge5ModbusV2 } from './edge5-modbus-v2.js';
|
||||
import { handleEdge5ModbusV3 } from './edge5-modbus-v3.js';
|
||||
import { handleEdge5Video } from './edge5-video.js';
|
||||
import { handleEdge5VideoV2 } from './edge5-video-v2.js';
|
||||
|
||||
@@ -22,3 +23,4 @@ register(EDGE5_VIDEO_TOPIC, handleEdge5Video);
|
||||
register('data/edge5i/modbus', interpretation);
|
||||
register('data/edge5cdab/modbus', cdab);
|
||||
register('data/edge5/video/v2/+', handleEdge5VideoV2);
|
||||
register('data/edge5/modbus/v3', handleEdge5ModbusV3);
|
||||
|
||||
@@ -6,8 +6,8 @@ import { fileURLToPath } from 'node:url'
|
||||
import { log } from '../helpers/log.js'
|
||||
|
||||
const httpPort = Number(process.env.HTTP_PORT)
|
||||
const publicDir = join(dirname(fileURLToPath(import.meta.url)), '../../public')
|
||||
const indexPath = join(publicDir, 'index.html')
|
||||
const assetsDir = join(dirname(fileURLToPath(import.meta.url)), '../../assets')
|
||||
const indexPath = join(assetsDir, 'index.html')
|
||||
|
||||
createServer(async (req, res) => {
|
||||
const path = req.url?.split('?')[0]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import './process-errors.js'
|
||||
import './handlers/index.js'
|
||||
import './http/server.js'
|
||||
import './mqtt.js'
|
||||
|
||||
@@ -19,7 +19,7 @@ export type MetricMapper = {
|
||||
|
||||
type MetricMapperOptions = {
|
||||
// filePath contract:
|
||||
// - built-in mappings are passed as URL via new URL('../mappings/*.json', import.meta.url);
|
||||
// - built-in mappings live in app/assets/*.json (resolved relative to dist/ at runtime);
|
||||
// - env overrides are expected as absolute paths inside the runtime container.
|
||||
filePath: string | URL
|
||||
}
|
||||
|
||||
57
app/src/process-errors.ts
Normal file
57
app/src/process-errors.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
type ErrorWithCause = Error & {
|
||||
cause?: unknown
|
||||
}
|
||||
|
||||
type NodeError = Error & {
|
||||
code?: string
|
||||
address?: string
|
||||
port?: number
|
||||
}
|
||||
|
||||
// Undici кладёт системную ошибку соединения внутрь error.cause.
|
||||
function getFetchCause(error: unknown): NodeError | null {
|
||||
if (!(error instanceof Error)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const cause = (error as ErrorWithCause).cause
|
||||
return cause instanceof Error ? (cause as NodeError) : null
|
||||
}
|
||||
|
||||
// Обрабатываем только подсвеченный кейс: backend отказал в TCP-соединении.
|
||||
function isFetchConnectionRefused(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const cause = getFetchCause(error)
|
||||
return error.message === 'fetch failed' && cause?.code === 'ECONNREFUSED'
|
||||
}
|
||||
|
||||
// Логируем короткую диагностическую форму без огромного stack trace.
|
||||
function formatFetchError(error: unknown): object {
|
||||
if (!(error instanceof Error)) {
|
||||
return { message: String(error) }
|
||||
}
|
||||
|
||||
const cause = getFetchCause(error)
|
||||
return {
|
||||
message: error.message,
|
||||
cause: cause?.message,
|
||||
code: cause?.code,
|
||||
address: cause?.address,
|
||||
port: cause?.port,
|
||||
}
|
||||
}
|
||||
|
||||
// Последний рубеж защиты для fire-and-forget fetch-запросов.
|
||||
// Если backend недоступен, Node.js 22 может превратить незахваченный
|
||||
// fetch failed / ECONNREFUSED в падение всего процесса mqtt-worker.
|
||||
process.on('unhandledRejection', (error) => {
|
||||
if (isFetchConnectionRefused(error)) {
|
||||
console.error('process.unhandled_fetch_refused', formatFetchError(error))
|
||||
return
|
||||
}
|
||||
|
||||
console.error('process.unhandled_rejection', error)
|
||||
})
|
||||
@@ -24,7 +24,7 @@ services:
|
||||
CLOUD_INGEST_URL: ${CLOUD_INGEST_URL}
|
||||
CLOUD_INGEST_API_KEY: ${CLOUD_INGEST_API_KEY}
|
||||
DEMO_CLOUD_INGEST_URL: ${DEMO_CLOUD_INGEST_URL}
|
||||
EDGE5_MODBUS_V2_MAPPING_FILE: ${EDGE5_MODBUS_V2_MAPPING_FILE:-/app/src/mappings/edge5-modbus.json}
|
||||
EDGE5_MODBUS_V2_MAPPING_FILE: ${EDGE5_MODBUS_V2_MAPPING_FILE:-/app/assets/edge5-modbus.json}
|
||||
networks:
|
||||
- default
|
||||
- proxy
|
||||
|
||||
Reference in New Issue
Block a user