使用flutter设计modbus tcp网页版程序

问题描述 投票:0回答:1

全部

我想用flutter设计一个网页版形式的modbus tcp程序。 但我不知道如何开始。 我看到了这个包( https://pub.dev/packages/modbus)(https://pub.dev/packages/modbus_client),想尝试一下,但是在网页版上不起作用形式。 谁能给我举个简单的例子或者有经验可以分享一下吗,谢谢。

我尝试使用软件包 modbus 。 但不适用于网页版形式。 下面的代码可以在windows平台上使用,但是如果在chrome上运行debug,连接失败:

import 'package:flutter/material.dart';
import 'package:modbus_client/modbus_client.dart';
import 'package:modbus_client_tcp/modbus_client_tcp.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _ipController = TextEditingController();
  final TextEditingController _portController = TextEditingController();
  final TextEditingController _registerController = TextEditingController();
  String _result = '';

  Future<void> _readHoldingRegister() async {
    final ip = _ipController.text;
    final port = int.tryParse(_portController.text) ?? 502;
    final registerAddress = int.tryParse(_registerController.text) ?? 0;
    var battery = ModbusInt16Register(
      name: "Battery",
      type: ModbusElementType.inputRegister,
      address: 4098,
      uom: "V",
      multiplier: 0.1,
      onUpdate: (self) => print(self));
    try {
      // Initialize Modbus client
      var client =  ModbusClientTcp (
        ip,
        serverPort: port,
        unitId: 15,  //  unitId
        responseTimeout :const Duration(seconds: 3),
        connectionMode: ModbusConnectionMode.autoConnectAndDisconnect,
      );

      // Connect to the Modbus server
      final connected = await client.connect();
      if (!connected) {
        setState(() {
          _result = 'Failed to connect to the server';
        });
        return;
      }

      // Create a Modbus request to read holding registers
      final request = battery.getReadRequest();

      // Send the request
      final responseCode = await client.send(request);

      // Check the response code
      if (responseCode == ModbusResponseCode.requestSucceed) {
        // Read the register value
        final result = await client.send(request);
        setState(() {
          _result = 'Register value: ${battery.value}';
        });
      } else {
        setState(() {
          _result = 'Error: ${responseCode.code}';
        });
      }

      // Disconnect after request
      await client.disconnect();
    } catch (e) {
      setState(() {
        _result = 'Exception: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Modbus TCP Reader'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _ipController,
              decoration: InputDecoration(labelText: 'IP Address'),
            ),
            TextField(
              controller: _portController,
              decoration: InputDecoration(labelText: 'Port'),
              keyboardType: TextInputType.number,
            ),
            TextField(
              controller: _registerController,
              decoration: InputDecoration(labelText: 'Register Address'),
              keyboardType: TextInputType.number,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _readHoldingRegister,
              child: Text('Read Register'),
            ),
            SizedBox(height: 20),
            Text(_result),
          ],
        ),
      ),
    );
  }
}
flutter modbus-tcp
1个回答
0
投票

最后我用webscoket解决了。

  1. 通过C#(我用过)或node.js构建一个websocket服务器
  2. 让 websocketserver 处理 modbus tcp <=> Flutter web_socket_chanel 请求。

它对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.