-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModbusMaster.flowext.ts
More file actions
473 lines (451 loc) · 23.7 KB
/
ModbusMaster.flowext.ts
File metadata and controls
473 lines (451 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import type { BlockCategory } from '../types.js';
const COLOR = '#f59e0b';
// ─── Serial config string ────────────────────────────────────────────────────
function serialConfig(dataBits: string, parity: string, stopBits: string): string {
const p = parity === 'E' ? 'E' : parity === 'O' ? 'O' : 'N';
return `SERIAL_${dataBits}${p}${stopBits}`;
}
// ─── Register common globals/functions per modbus instance ──────────────────
function registerModbusInstance(
_dePin: string,
registerPreprocessor: (d: string) => void,
registerGlobal: (d: string) => void,
registerFunction: (h: string, b: string, decl?: string) => void,
) {
registerPreprocessor('#include <ModbusMasterPlus.h>');
registerGlobal(`ModbusMaster modbus;`);
registerGlobal(`HardwareSerial* modbus_serial = nullptr;`);
registerGlobal(`int modbus_de_pin = -1;`);
registerFunction(
`void modbus_preTx()`,
` if (modbus_de_pin >= 0) digitalWrite(modbus_de_pin, HIGH);`,
`void modbus_preTx();`
);
registerFunction(
`void modbus_postTx()`,
` if (modbus_de_pin >= 0) digitalWrite(modbus_de_pin, LOW);`,
`void modbus_postTx();`
);
}
// ─── Endian helpers ──────────────────────────────────────────────────────────
function modbusReadExpr(id: string, pad: string, rawType: string, endian: string): string {
const wordSwap = endian.startsWith('LE'); // swap word order (register 0 ↔ 1)
const byteSwap = endian.endsWith('-SWAP'); // swap bytes within each word
const raw = (i: number) => `modbus.getResponseBuffer(${i})`;
const buf = (i: number) => byteSwap
? `(uint16_t)((${raw(i)} >> 8) | (${raw(i)} << 8))`
: raw(i);
if (rawType === 'float') {
const conv_union = [
`union {`,
` uint16_t u16[2];`,
` float f32;`,
`} ${id}_conv;`
];
// u[0]=LSW, u[1]=MSW on little-endian MCU
// no word swap: buf[0]=MSW→u[1], buf[1]=LSW→u[0]
// word swap: buf[0]=LSW→u[0], buf[1]=MSW→u[1]
const [u0, u1] = wordSwap ? [buf(0), buf(1)] : [buf(1), buf(0)];
return [
...conv_union,
`${id}_conv.u16[0] = ${u0};`,
`${id}_conv.u16[1] = ${u1};`,
`float ${id} = ${id}_conv.f32;`,
].map(l => `${pad} ${l}`).join('\n');
}
if (rawType === 'double') {
const conv_union = [
`union {`,
` uint16_t u16[4];`,
` double f64;`,
`} ${id}_conv;`
];
// u[0]=LSW..u[3]=MSW; no word swap: buf[0]=u[3]..buf[3]=u[0]
const uIdx = wordSwap ? [0, 1, 2, 3] : [3, 2, 1, 0];
return [
...conv_union,
...uIdx.map((ui, bi) => `${id}_conv.u16[${ui}] = ${buf(bi)};`),
`double ${id} = ${id}_conv.f64;`,
].map(l => `${pad} ${l}`).join('\n');
}
if (rawType === 'uint32' || rawType === 'int32') {
const conv_union = [
`union {`,
` uint16_t u16[2];`,
` uint32_t u32;`,
` int32_t i32;`,
`} ${id}_conv;`
];
const [u0, u1] = wordSwap ? [buf(0), buf(1)] : [buf(1), buf(0)];
return [
...conv_union,
`${id}_conv.u16[0] = ${u0};`,
`${id}_conv.u16[1] = ${u1};`,
`${rawType}_t ${id} = ${id}_conv.${rawType === 'uint32' ? 'u32' : 'i32'};`,
].map(l => `${pad} ${l}`).join('\n');
}
if (rawType === 'bool') return `${pad} bool ${id} = (modbus.getResponseBuffer(0) & 0x01) != 0;`;
if (rawType === 'int16') return `${pad} int16_t ${id} = (int16_t)modbus.getResponseBuffer(0);`;
return `${pad} uint16_t ${id} = modbus.getResponseBuffer(0);`;
}
function modbusWriteLines(id: string, pad: string, writeType: string, dataType: string, address: string, coilCount: string, valueExpr: string, endian: string): string[] {
const wordSwap = endian.endsWith('-SWAP');
const byteSwap = endian.startsWith('LE');
const sw = (e: string) => byteSwap ? `(uint16_t)((${e} >> 8) | (${e} << 8))` : e;
if (writeType === 'single_coil') return [
`${pad}${id}_result = (uint8_t)modbus.writeSingleCoil(${address}, (${valueExpr}) !== 0 ? 1 : 0);`,
];
if (writeType === 'multi_coils') return [
`${pad}modbus.setTransmitBuffer(0, (uint16_t)(${valueExpr}));`,
`${pad}${id}_result = (uint8_t)modbus.writeMultipleCoils(${address}, ${coilCount});`,
];
const isMulti = writeType === 'multi_registers';
if (dataType === 'float32') {
// u[0]=LSW, u[1]=MSW; no word swap → send MSW first
const [b0, b1] = wordSwap
? [sw(`${id}_conv.u[0]`), sw(`${id}_conv.u[1]`)]
: [sw(`${id}_conv.u[1]`), sw(`${id}_conv.u[0]`)];
return [
`${pad}{ union { float f; uint16_t u[2]; } ${id}_conv; ${id}_conv.f = (float)(${valueExpr});`,
`${pad} modbus.setTransmitBuffer(0, ${b0});`,
`${pad} modbus.setTransmitBuffer(1, ${b1});`,
`${pad} ${id}_result = (uint8_t)modbus.writeMultipleRegisters(${address}, 2); }`,
];
}
if (dataType === 'int32') {
const hiW = `(uint16_t)(${id}_i32 >> 16)`;
const loW = `(uint16_t)(${id}_i32 & 0xFFFF)`;
const [b0, b1] = wordSwap ? [sw(loW), sw(hiW)] : [sw(hiW), sw(loW)];
return [
`${pad}{ uint32_t ${id}_i32 = (uint32_t)(int32_t)(${valueExpr});`,
`${pad} modbus.setTransmitBuffer(0, ${b0});`,
`${pad} modbus.setTransmitBuffer(1, ${b1});`,
`${pad} ${id}_result = (uint8_t)modbus.writeMultipleRegisters(${address}, 2); }`,
];
}
return isMulti ? [
`${pad}modbus.setTransmitBuffer(0, (uint16_t)(${valueExpr}));`,
`${pad}${id}_result = (uint8_t)modbus.writeMultipleRegisters(${address}, 1);`,
] : [
`${pad}${id}_result = (uint8_t)modbus.writeSingleRegister(${address}, (uint16_t)(${valueExpr}));`,
];
}
const modbusMasterExtension: BlockCategory = {
id: 'modbus-master',
name: 'Modbus Master',
blocks: [
// ─── Modbus Config ───────────────────────────────────────────────
{
id: 'modbus_config',
name: 'Modbus Config',
color: COLOR,
icon: '🔌',
category: 'Modbus Master',
description: 'กำหนดค่า Modbus RTU Master: Serial Port, Pin RX/TX/DE, Baud Rate, Frame Format\nใช้ไลบรารี่ ModbusMaster',
inputs: [{ id: 'in', type: 'input', label: '➜', dataType: 'any' }],
outputs: [{ id: 'out', type: 'output', label: '➜', dataType: 'void' }],
params: [
{
id: 'serial_port', label: 'Serial Port', type: 'option',
options: [
{ label: 'Serial1', value: 'Serial1' },
{ label: 'Serial2', value: 'Serial2' },
{ label: 'Serial3', value: 'Serial3' },
],
default: 'Serial2',
description: 'HardwareSerial ที่ใช้ต่อ RS-485',
},
{
id: 'rx_pin', label: 'RX Pin', type: 'number',
default: '16', description: 'GPIO ขา RX',
validation: (n: number) => Math.round(n),
},
{
id: 'tx_pin', label: 'TX Pin', type: 'number',
default: '17', description: 'GPIO ขา TX',
validation: (n: number) => Math.round(n),
},
{
id: 'de_pin', label: 'DE/RE Pin', type: 'number',
default: '4', description: 'GPIO ขา DE/RE สำหรับควบคุมทิศทาง RS-485 (-1 = ไม่ใช้)',
validation: (n: number) => Math.round(n),
},
{
id: 'baud', label: 'Baud Rate', type: 'option',
options: [
{ label: '1200', value: '1200' },
{ label: '2400', value: '2400' },
{ label: '4800', value: '4800' },
{ label: '9600', value: '9600' },
{ label: '19200', value: '19200' },
{ label: '38400', value: '38400' },
{ label: '57600', value: '57600' },
{ label: '115200', value: '115200' },
],
default: '9600',
description: 'ความเร็ว Baud Rate',
},
{
id: 'data_bits', label: 'Data Bits', type: 'option',
options: [
{ label: '8', value: '8' },
{ label: '7', value: '7' },
],
default: '8',
},
{
id: 'parity', label: 'Parity', type: 'option',
options: [
{ label: 'None', value: 'N' },
{ label: 'Even', value: 'E' },
{ label: 'Odd', value: 'O' },
],
default: 'N',
},
{
id: 'stop_bits', label: 'Stop Bits', type: 'option',
options: [
{ label: '1', value: '1' },
{ label: '2', value: '2' },
],
default: '1',
},
],
toCode({ pad, params, registerPreprocessor, registerGlobal, registerFunction }) {
const serialPt = params.serial_port ?? 'Serial2';
const rxPin = params.rx_pin ?? '16';
const txPin = params.tx_pin ?? '17';
const dePin = params.de_pin ?? '-1';
const baud = params.baud ?? '9600';
const cfg = serialConfig(params.data_bits ?? '8', params.parity ?? 'N', params.stop_bits ?? '1');
registerModbusInstance(dePin, registerPreprocessor, registerGlobal, registerFunction);
return {
parts: [
[`${pad}modbus_serial = &${serialPt};`],
[`${pad}modbus_de_pin = ${dePin};`],
[`${pad}if (modbus_de_pin >= 0) { pinMode(modbus_de_pin, OUTPUT); digitalWrite(modbus_de_pin, LOW); }`],
[`${pad}modbus_serial->begin(${baud}, ${cfg}, ${rxPin}, ${txPin});`],
[`${pad}modbus.preTransmission(modbus_preTx);`],
[`${pad}modbus.postTransmission(modbus_postTx);`],
{ portId: 'out', depthDelta: 0 },
]
};
}
},
// ─── Modbus Read ─────────────────────────────────────────────────
{
id: 'modbus_read',
name: 'Modbus Read',
color: COLOR,
icon: '📖',
category: 'Modbus Master',
requires: ['modbus_config'],
description: 'อ่านค่าจาก Modbus Slave\nรองรับ Coils, Discrete Inputs, Input Registers, Holding Registers',
inputs: [{ id: 'in', type: 'input', label: '➜', dataType: 'any' }],
outputs: [],
params: [
{
id: 'slave_id', label: 'Slave ID', type: 'number',
default: '1', description: 'หมายเลข Modbus Slave (1-247)',
validation: (n: number) => Math.max(1, Math.min(247, Math.round(n))),
},
{
id: 'register_type', label: 'Register Type', type: 'option',
options: [
{ label: 'Coil', value: 'coil', description: '01 (0x01) Read Coils' },
{ label: 'Discrete Input', value: 'discrete', description: '02 (0x02) Read Discrete Inputs' },
{ label: 'Holding Register', value: 'holding', description: '03 (0x03) Read Holding Registers' },
{ label: 'Input Register', value: 'input', description: '04 (0x03) Read Input Registers' },
],
default: 'holding',
},
{
id: 'address', label: 'Address', type: 'number',
default: '0', description: 'ที่อยู่ register (0-indexed)',
validation: (n: number) => Math.max(0, Math.round(n)),
},
{
id: 'data_type', label: 'Data Type', type: 'option',
options: [
{ label: 'Signed', value: 'int16' },
{ label: 'Unsigned', value: 'uint16' },
{ label: '32 Bit Signed', value: 'int32' },
{ label: '32 Bit Unsigned', value: 'uint32' },
/*{ label: '64 Bit Signed', value: 'int64' },
{ label: '64 Bit Unsigned', value: 'uint64' },*/
{ label: '32 Bit Float', value: 'float' },
{ label: '64 Bit Double', value: 'double' },
{ label: 'Binary', value: 'bool' },
],
default: 'int16',
hidden: ({ params }) => params.register_type === 'coil' || params.register_type === 'discrete',
},
{
id: 'endian', type: 'option', label: 'Endian',
options: [
{ label: 'Big-endian', value: 'BE' },
{ label: 'Big-endian byte swap', value: 'BE-SWAP' },
{ label: 'Little-endian', value: 'LE' },
{ label: 'Little-endian byte swap', value: 'LE-SWAP' },
],
description: 'ลำดับไบต์ Big-endian / Little-endian / Swap',
hidden: ({ params }) => params.register_type === 'coil' || params.register_type === 'discrete' || ['int32', 'uint32', 'float', 'double'].indexOf(params.data_type) < 0
},
],
dynamicPorts(params) {
const dataType = ({
'int16': 'int',
'uint16': 'int',
'int32': 'long',
'uint32': 'long',
'int64': 'int',
'uint64': 'int',
'float': 'float',
'double': 'double',
'bool': 'bool',
})[params.data_type] ?? 'int';
return {
outputs: [
{ id: 'value', type: 'output', label: 'Value', dataType, description: 'ค่าที่อ่านได้' },
{ id: 'error', type: 'output', label: 'Error', dataType: 'void', description: 'รันเมื่ออ่านไม่สำเร็จ' },
{ id: 'out', type: 'output', label: '➜', dataType: 'void', description: 'ต่อเสมอหลัง if/else' },
]
}
},
toCode({ pad, block, safeId, params, registerPreprocessor, registerGlobal, registerFunction }) {
const slaveId = params.slave_id ?? '1';
const regType = params.register_type ?? 'holding';
const address = params.address ?? '0';
const rawType = (regType === 'coil' || regType === 'discrete') ? 'bool' : (params.data_type ?? 'int16');
const endian = params.endian ?? 'BE';
const id = safeId(block.id);
registerModbusInstance('-1', registerPreprocessor, registerGlobal, registerFunction);
const isFloat = rawType === 'float';
const isDouble = rawType === 'double';
const isInt32 = rawType === 'int32';
const isUint32 = rawType === 'uint32';
const qty = isDouble ? 4 : (isFloat || isInt32 || isUint32) ? 2 : 1;
let readCall: string;
if (regType === 'holding') readCall = `modbus.readHoldingRegisters(${address}, ${qty})`;
else if (regType === 'input') readCall = `modbus.readInputRegisters(${address}, ${qty})`;
else if (regType === 'coil') readCall = `modbus.readCoils(${address}, 1)`;
else readCall = `modbus.readDiscreteInputs(${address}, 1)`;
const valueExpr = modbusReadExpr(id, pad, rawType, endian);
return {
parts: [
[`${pad}modbus.begin(${slaveId}, *modbus_serial);`],
[`${pad}uint8_t ${id}_result = ${readCall};`],
[`${pad}if (${id}_result == ModbusMaster::ku8MBSuccess) {`],
[valueExpr],
{ portId: 'value', depthDelta: 1 },
[`${pad}} else {`],
{ portId: 'error', depthDelta: 1 },
[`${pad}}`],
{ portId: 'out', depthDelta: 0 },
]
};
}
},
// ─── Modbus Write ────────────────────────────────────────────────
{
id: 'modbus_write',
name: 'Modbus Write',
color: COLOR,
icon: '✏️',
category: 'Modbus Master',
requires: ['modbus_config'],
description: 'เขียนค่าไปยัง Modbus Slave\nรองรับ Single Coil, Single/Multiple Holding Registers',
inputs: [
{ id: 'in', type: 'input', label: '➜', dataType: 'any', description: 'จุดต่อสายบล็อกก่อนหน้า' },
{ id: 'value', type: 'input', label: 'Value', dataType: 'any', description: 'ค่าที่ต้องการเขียน (ถ้าไม่ต่อสาย ใช้ค่าจาก param)' },
],
outputs: [
{ id: 'success', type: 'output', label: 'Success', dataType: 'void', description: 'รันเมื่อเขียนสำเร็จ' },
{ id: 'error', type: 'output', label: 'Error', dataType: 'void', description: 'รันเมื่อเขียนไม่สำเร็จ' },
{ id: 'out', type: 'output', label: '➜', dataType: 'void', description: 'ต่อเสมอหลัง if/else' },
],
params: [
{
id: 'slave_id', label: 'Slave ID', type: 'number',
default: '1', description: 'หมายเลข Modbus Slave (1-247)',
validation: (n: number) => Math.max(1, Math.min(247, Math.round(n))),
},
{
id: 'write_type', label: 'Write Type', type: 'option',
options: [
{ label: 'Single Coil', value: 'single_coil', description: 'writeSingleCoil (FC 05)' },
{ label: 'Single Register', value: 'single_register', description: 'writeSingleRegister (FC 06)' },
{ label: 'Multiple Coils', value: 'multi_coils', description: 'writeMultipleCoils (FC 15)' },
{ label: 'Multiple Registers', value: 'multi_registers', description: 'writeMultipleRegisters (FC 16)' },
],
default: 'single_register',
},
{
id: 'address', label: 'Address', type: 'number',
default: '0', description: 'ที่อยู่ register (0-indexed)',
validation: (n: number) => Math.max(0, Math.round(n)),
},
{
id: 'data_type', label: 'Data Type', type: 'option',
options: [
{ label: 'int16 (signed 16-bit)', value: 'int16' },
{ label: 'uint16 (word)', value: 'uint16' },
{ label: 'int32 (signed 32-bit)', value: 'int32' },
{ label: 'float32', value: 'float32' },
],
default: 'int16',
hidden: ({ params }) => params.write_type === 'single_coil' || params.write_type === 'multi_coils',
},
{
id: 'coil_count', label: 'Coil Count', type: 'number',
default: '8', description: 'จำนวน Coil ที่ต้องการเขียน (ใช้กับ Multiple Coils)',
validation: (n: number) => Math.max(1, Math.round(n)),
hidden: ({ params }) => params.write_type !== 'multi_coils',
},
{
id: 'value', label: 'Value', type: 'text',
default: '0', description: 'ค่าที่เขียน (ใช้เมื่อไม่มีสายต่อเข้า Value port)',
},
{
id: 'endian', type: 'option', label: 'Endian',
options: [
{ label: 'Big-endian', value: 'BE' },
{ label: 'Big-endian byte swap', value: 'BE-SWAP' },
{ label: 'Little-endian', value: 'LE' },
{ label: 'Little-endian byte swap', value: 'LE-SWAP' },
],
default: 'BE',
description: 'ลำดับไบต์ Big-endian / Little-endian / Swap',
hidden: ({ params }) => params.write_type === 'single_coil' || params.write_type === 'multi_coils' || (params.data_type !== 'int32' && params.data_type !== 'float32'),
},
],
toCode({ pad, block, safeId, params, resolveInput, registerPreprocessor, registerGlobal, registerFunction }) {
const slaveId = params.slave_id ?? '1';
const writeType = params.write_type ?? 'single_register';
const address = params.address ?? '0';
const dataType = params.data_type ?? 'int16';
const coilCount = params.coil_count ?? '8';
const fallback = params.value ?? '0';
const endian = params.endian ?? 'BE';
const id = safeId(block.id);
const valueExpr = resolveInput('value') ?? fallback;
registerModbusInstance('-1', registerPreprocessor, registerGlobal, registerFunction);
const writeLines = modbusWriteLines(id, pad, writeType, dataType, address, coilCount, valueExpr, endian);
return {
parts: [
[`${pad}modbus.begin(${slaveId}, *modbus_serial);`],
[`${pad}uint8_t ${id}_result = 0;`],
writeLines,
[`${pad}if (${id}_result == ModbusMaster::ku8MBSuccess) {`],
{ portId: 'success', depthDelta: 1 },
[`${pad}} else {`],
{ portId: 'error', depthDelta: 1 },
[`${pad}}`],
{ portId: 'out', depthDelta: 0 },
]
};
}
},
]
};
export default modbusMasterExtension;