前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >C# Snet 采集库与转发库的最新应用示例代码,简单高效

C# Snet 采集库与转发库的最新应用示例代码,简单高效

作者头像
Shunnet
发布于 2025-03-18 01:34:05
发布于 2025-03-18 01:34:05
10500
代码可运行
举报
运行总次数:0
代码可运行

为了更快的上手,接下来的是采集库与转发库的最新代码示例,走的都是异步方式(按需使用同步异步),简单快捷

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Snet.Fatek" Version="最新版本" />
    <PackageReference Include="Snet.Mqtt" Version="最新版本" />
  </ItemGroup>

</Project>

采集库最新示例代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/// <summary>
    /// 以永宏示例,所有结果返回都是 OperateResult 请详细查看属性注释
    /// </summary>
    internal class Program1
    {
        static async Task Main(string[] args)
        {
            //生成点位
            Address address = new Address
            {
                //点位集合
                AddressArray = new List<AddressDetails>
                   {
					   //点位
                       {
						   //读地址 R24 的 Int数组数据  长度读 10 位
                            new AddressDetails(Guid.NewGuid().ToString(),"R24",Snet.Model.@enum.DataType.IntArray,10)
                       },
                       //点位
                       {
						   //读地址 R10 的 Bool数据
                            new AddressDetails(Guid.NewGuid().ToString(),"R10",Snet.Model.@enum.DataType.Bool)
                       },
                       //点位
                       {
						   //读地址 R99 的 string 数据 长度读 7 位
                            new AddressDetails(Guid.NewGuid().ToString(),"R99",Snet.Model.@enum.DataType.String,7,Snet.Model.@enum.EncodingType.ASCII)
                       }
                   }
            };

            //实例化一个单例,并且在使用完关闭,此方法是单例模式,也有其他的实例方案,请查看库的更新文档 https://Shunnet.top/rRbY7
            using (FatekOperate operate = FatekOperate.Instance(
                //基础数据
                new FatekData.Basics
                {
                    IpAddress = "127.0.0.1",
                    Port = 2000,
                    ProtocolType = FatekData.ProtocolType.FatekProgramOverTcp
                }
            ))
            {
                //打开
                OperateResult result = await operate.OnAsync();

                //打开成功
                if (result.Status)
                {
                    //获取连接状态
                    await operate.GetStatusAsync();


                    //获取实例化时传入的基础数据对象
                    await operate.GetBasicsDataAsync();


                    //根据 PType 确定哪些属性需要赋值
                    await operate.GetAutoAllocatingParamAsync();


                    //动态加载时获取参数,提供给外面动态加载界面使用,对象里面有数据该呈现的类型
                    await operate.GetParamAsync();


                    //日志操作参数获取
                    await operate.LogOGAsync();
                    //日志操作参数设置
                    await operate.LogOSAsync();


                    //启动webapi
                    await operate.WAOnAsync(new WAModel("127.0.0.1", 6688));
                    //停止webapi
                    await operate.WAOffAsync();
                    //获取webapi请求示例
                    await operate.WARequestExampleAsync();
                    //webapi的读取 Json
                    /*
//基础类型读取
{
    "SN": "8c71f4a7-04eb-4f9c-88d9-849c2f0c3a00",
    "AddressArray": [
        {
            "SN": "TestAddress",
            "AddressName": "M100",
            "AddressDataType": "Float"
        }
    ],
    "CreationTime": "2024-06-05T13:01:24.6245462+08:00"
}
//基础数组类型读取
{
    "SN": "8c71f4a7-04eb-4f9c-88d9-849c2f0c3a00",
    "AddressArray": [
        {
            "SN": "TestAddress",
            "AddressName": "M100",
            "AddressDataType": "FloatArray",
            "Length":5
        }
    ],
    "CreationTime": "2024-06-05T13:01:24.6245462+08:00"
}
//字节数组类型读取
{
    "SN": "8c71f4a7-04eb-4f9c-88d9-849c2f0c3a00",
    "AddressArray": [
        {
            "SN": "TestAddress",
            "AddressName": "M100",
            "AddressDataType": "ByteArray",
            "Length":6
        }
    ],
    "CreationTime": "2024-06-05T13:01:24.6245462+08:00"
}
//字符串读取
{
    "SN": "8c71f4a7-04eb-4f9c-88d9-849c2f0c3a00",
    "AddressArray": [
        {
            "SN": "TestAddress",
            "AddressName": "M100",
            "AddressDataType": "ByteArray",
            "Length":7,
            "EncodingType":"ASCII"
        }
    ],
    "CreationTime": "2024-06-05T13:01:24.6245462+08:00"
}
                     */
                    //webapi的写入 Json
                    /*
基础类型写入
{
  "M100": {
    "Value": 99.1,
    "AddressDataType": "Float"
  }
}
基础数组类型写入
{
  "M100": {
    "Value": [1.1,2.1,3.1,4.1,5.1],
    "AddressDataType": "FloatArray"
  }
}
字节数组类型写入
{
  "M100": {
    "Value": "0x00 0x01 0x02 0x03 0x04 0x05",
    "AddressDataType": "ByteArray"
  }
}
字符串写入
{
  "M100": {
    "Value": "abcdefg",
    "AddressDataType": "String",
    "EncodingType":"ASCII"
  }
}

                     */


                    //写入操作,实际生产环境别瞎写喔,搞不好就出大事
                    //第一种写入
                    result = await operate.WriteAsync(new ConcurrentDictionary<string, object>
                    {
                        ["R24"] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },  //写入int数组
                        ["R10"] = false,  //写入布尔
                        ["R99"] = "abcdefg"//写入字符串
                    });
                    //第二种写入,更明确的写入,也是webapi请求的格式
                    result = await operate.WriteAsync(new ConcurrentDictionary<string, WriteModel>
                    {
                        ["R24"] = new(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Snet.Model.@enum.DataType.IntArray),  //写入int数组
                        ["R10"] = new(false, Snet.Model.@enum.DataType.Bool),  //写入布尔
                        ["R99"] = new("abcdefg", Snet.Model.@enum.DataType.String, Snet.Model.@enum.EncodingType.ASCII)//写入字符串
                    });
                    //第三种写入
                    result = await operate.WriteAsync(new ConcurrentDictionary<string, (object value, Snet.Model.@enum.EncodingType? encodingType)>
                    {
                        ["R24"] = (new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, null),  //写入int数组
                        ["R10"] = (false, null),  //写入布尔
                        ["R99"] = ("abcdefg", Snet.Model.@enum.EncodingType.ASCII)//写入字符串
                    });
                    //直接输出结果
                    Console.WriteLine(result.ToJson(true));


                    //可以走读取模式
                    ConcurrentDictionary<string, AddressValue>? data = (await operate.ReadAsync(address)).ResultData?.GetSource<ConcurrentDictionary<string, AddressValue>>();
                    //直接输出结果
                    Console.WriteLine(data.ToJson(true));


                    //可以走订阅模式
                    //单得先注册事件
                    operate.OnDataEventAsync += FatekOperate_OnDataEventAsync;  //数据事件
                    operate.OnInfoEventAsync += FatekOperate_OnInfoEventAsync;  //信息事件
                    //执行订阅操作
                    if (!(await operate.SubscribeAsync(address)).GetDetails(out string? msg))
                    {
                        //订阅失败消息
                        Console.WriteLine(msg);
                    }
                }

                //完成操作,直接释放,如果启动了订阅会关闭订阅,然后关闭连接,下面代码是演示喔,正常使用 using 的话就不用写了
                Console.ReadLine();
                //手动关闭订阅
                await operate.UnSubscribeAsync(address);
                //手动关闭代码示例
                await operate.OffAsync();
                //手动释放
                operate.Dispose();
            }
        }

        /// <summary>
        /// 信息事件
        /// </summary>
        private static Task FatekOperate_OnInfoEventAsync(object? sender, EventInfoResult e)
        {
            Console.WriteLine(e.ToJson(true));
            return Task.CompletedTask;
        }

        /// <summary>
        /// 数据事件
        /// </summary>
        private static Task FatekOperate_OnDataEventAsync(object? sender, EventDataResult e)
        {
            ConcurrentDictionary<string, AddressValue>? data = e?.GetSource<ConcurrentDictionary<string, AddressValue>>();

            //获取精简地址Protobuf集合对象
            AddressValueSimplifyProtobuf? protobuf = data?.GetSimplifyProtobuf();

            //获取精简地址集合
            IEnumerable<AddressValueSimplify>? simplifies = data?.GetSimplifyArray();


            Console.WriteLine(data?.ToJson(true));
            return Task.CompletedTask;
        }
    }

转发库最新示例代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/// <summary>
/// 以Mqtt示例,所有结果返回都是 OperateResult 请详细查看属性注释
/// </summary>
internal class Program2
{
    static async Task Main(string[] args)
    {
        //实例化一个单例,并且在使用完关闭,此方法是单例模式,也有其他的实例方案,请查看库的更新文档 https://Shunnet.top/rRbY7
        using (MqttClientOperate operate = MqttClientOperate.Instance(
            //基础数据
            new MqttClientData.Basics
            {
                IpAddress = "127.0.0.1",
                Port = 2000
            }
        ))
        {
            //打开
            OperateResult result = await operate.OnAsync();

            //打开成功
            if (result.Status)
            {
                //获取连接状态
                await operate.GetStatusAsync();


                //获取实例化时传入的基础数据对象
                await operate.GetBasicsDataAsync();


                //根据 PType 确定哪些属性需要赋值
                await operate.GetAutoAllocatingParamAsync();


                //动态加载时获取参数,提供给外面动态加载界面使用,对象里面有数据该呈现的类型
                await operate.GetParamAsync();


                //日志操作参数获取
                await operate.LogOGAsync();
                //日志操作参数设置
                await operate.LogOSAsync();


                //注册事件
                operate.OnDataEventAsync += FatekOperate_OnDataEventAsync;  //数据事件
                operate.OnInfoEventAsync += FatekOperate_OnInfoEventAsync;  //信息事件


                //一个实例里面可以生产消费多个主题
                //执行生产操作
                await operate.ProduceAsync("主题", "内容");
                await operate.ProduceAsync("主题", new byte[] { 0x00 });


                //执行订阅操作
                await operate.SubscribeAsync("主题");
            }

            //完成操作,直接释放,如果启动了订阅会关闭订阅,然后关闭连接,下面代码是演示喔,正常使用 using 的话就不用写了
            Console.ReadLine();
            //手动关闭订阅
            await operate.UnSubscribeAsync("主题");
            //手动关闭代码示例
            await operate.OffAsync();
            //手动释放
            operate.Dispose();
        }
    }

    /// <summary>
    /// 信息事件
    /// </summary>
    private static Task FatekOperate_OnInfoEventAsync(object? sender, EventInfoResult e)
    {
        Console.WriteLine(e.ToJson(true));
        return Task.CompletedTask;
    }

    /// <summary>
    /// 数据事件
    /// </summary>
    private static Task FatekOperate_OnDataEventAsync(object? sender, EventDataResult e)
    {
        Console.WriteLine(e?.ToJson(true));
        return Task.CompletedTask;
    }
}

简简单单,完工

本文作者 :「 博主 」大顺

分享地址 : Shunnet.top/NV3R7 版权声明 : 转载注明出处

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-02-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文