2 年前,由 afirefish 重新编辑
巴法云 C#/.NET SDK。支持TCP和MQTT协议接入,并提供超级简单的设备操作API。跨平台,支持Linux、Windows、OSX,支持树莓派。
项目地址:https://github.com/withsalt/BemfaCloud
简单使用:
控制一个开关关设备testSwitch001的TCP接入完整示例。
using System;
using System.Threading.Tasks;
using BemfaCloud;
using BemfaCloud.Connectors.Builder;
using BemfaCloud.Devices;
using BemfaCloud.Models;
namespace ConsoleApp7
{
internal class Program
{
static async Task Main(string[] args)
{
//构建一个Connector对象
using IBemfaConnector connector = new BemfaConnectorBuilder()
.WithTcp()
.WithSecret("在此处填写你的私钥")
.WithTopics("testSwitch001") //可订阅多个
.WithErrorHandler((e) =>
{
Console.WriteLine($"[LOG][{DateTime.Now}] {e.Message}");
})
.WithMessageHandler((MessageEventArgs e) =>
{
if (e.Type == CommandType.GetTimestamp)
{
Console.WriteLine($"收到消息:" + e);
}
})
.Build();
//连接到服务器
bool isConnect = await connector.ConnectAsync();
if (!isConnect)
{
throw new Exception("Connect with server faild.");
}
//使用开关设备
BemfaSwitch @switch = new BemfaSwitch("testSwitch001", connector);
@switch.On += (e) =>
{
//执行开关打开动作
Console.WriteLine("哦呦~需要打开开关");
return true;
};
@switch.Off += (e) =>
{
//执行开关关闭动作
Console.WriteLine("哦呦~需要关闭开关");
return true;
};
@switch.OnException += (e) =>
{
Console.WriteLine($"发生了异常:{e.Message}");
};
@switch.OnMessage += (e) =>
{
Console.WriteLine($"收到无法解析的消息:{e.ToString()}");
};
while (true)
{
string readStr = Console.ReadLine();
if (readStr.Equals("q", StringComparison.OrdinalIgnoreCase)
|| readStr.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
}
await connector.DisconnectAsync();
Console.WriteLine($"OK");
}
}
}