### Install BemfaCloud SDK via .NET CLI Source: https://github.com/withsalt/bemfacloud/blob/main/README.md Instructions for installing the BemfaCloud and BemfaCloud.Devices NuGet packages using the .NET CLI. These packages are essential for interacting with the BemfaCloud platform. ```shell dotnet add package BemfaCloud dotnet add package BemfaCloud.Devices ``` -------------------------------- ### Connect to BemfaCloud using MQTT Source: https://github.com/withsalt/bemfacloud/blob/main/README.md Example code for establishing a connection to the BemfaCloud server using the MQTT protocol. It shows how to configure the connector with a secret key and topics, and handle connection events. ```csharp using IBemfaConnector connector = new BemfaConnectorBuilder() .WithMqtt() .WithSecret("在此处填写你的私钥") .WithTopics("testSwitchMqtt001") //可订阅多个 .WithErrorHandler((e) => { Console.WriteLine($"[LOG][{DateTime.Now}] {e.Message}"); }) .WithMessageHandler((MessageEventArgs e) => { Console.WriteLine($"收到消息:" + e); }) .Build(); //连接到服务器 bool isConnect = await connector.ConnectAsync(); if (!isConnect) { throw new Exception("Connect with server faild."); } ``` -------------------------------- ### Raspberry Pi Integration Source: https://github.com/withsalt/bemfacloud/blob/main/README.md Information and examples for integrating BemfaCloud with Raspberry Pi using C#. ```APIDOC ## Raspberry Pi Integration Leveraging the cross-platform capabilities of .NET and the `System.Device.Gpio` library, you can build a powerful smart home control center on a Raspberry Pi using C#. ### Resources - **Raspberry Pi Example:** [https://github.com/withsalt/BemfaCloud/blob/main/src/Examples/BemfaCloud.Example.RaspberryPi/Program.cs](https://github.com/withsalt/BemfaCloud/blob/main/src/Examples/BemfaCloud.Example.RaspberryPi/Program.cs) ### More Examples For more complete examples, please visit the BemfaCloud GitHub repository: - [https://github.com/withsalt/BemfaCloud/tree/main/src/Examples](https://github.com/withsalt/BemfaCloud/tree/main/src/Examples) ``` -------------------------------- ### Socket Control Example Source: https://github.com/withsalt/bemfacloud/blob/main/README.md A C# code example demonstrating how to control a BemfaSocket, including handling on/off actions and exceptions. ```APIDOC ## Socket Control Example This C# example shows how to use the `BemfaSocket` class to control a socket device. It includes event handlers for turning the socket on/off, handling exceptions, and processing incoming messages. ### Method C# ### Code Example ```csharp static void Socket(IBemfaConnector connector) { BemfaSocket socket = new BemfaSocket("填写设备主题", connector); socket.On += (e) => { //执行打开插座动作 Console.WriteLine("哦呦~需要打开插座"); return true; }; socket.Off += (e) => { //执行关闭插座动作 Console.WriteLine("哦呦~需要关闭插座"); return true; }; socket.OnException += (e) => { Console.WriteLine($"发生了异常:{e.Message}"); }; socket.OnMessage += (e) => { Console.WriteLine($"收到无法解析的消息:{e.ToString()}"); }; } ``` **Note:** After performing operations like `On` or `Off`, it is necessary to return whether the operation was successful. Returning `true` indicates that the operation was completed successfully and the device status has been updated on the server. ``` -------------------------------- ### Control BemfaLight Device (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt Provides an example of controlling a BemfaLight device, supporting on/off, brightness adjustment (1-100), and color setting (RGB). It shows how to handle the 'On' event with brightness and color parameters and the 'Off' event. ```csharp using System.Drawing; using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; using IBemfaConnector connector = new BemfaConnectorBuilder() .WithTcp() .WithSecret("your-secret-key") .WithTopics("smartLight002") // 后缀002表示灯泡设备 .Build(); await connector.ConnectAsync(); BemfaLight light = new BemfaLight("smartLight002", connector); // 处理灯打开事件(包含亮度和颜色参数) // 命令格式: on#亮度#颜色值 例如: on#80#16777215 (白色,80%亮度) light.On += (MessageEventArgs e, int brightness, Color color) => { Console.WriteLine($"打开灯 - 亮度: {brightness}%, 颜色: R={color.R} G={color.G} B={color.B}"); // 控制LED灯带或智能灯泡 SetLedBrightness(brightness); SetLedColor(color); return true; }; // 处理灯关闭事件 light.Off += (MessageEventArgs e) => { Console.WriteLine("关闭灯"); TurnOffLed(); return true; }; light.OnException += (e) => { Console.WriteLine($"灯控制异常: {e.Message}"); }; ``` -------------------------------- ### Control a Switch Device using TCP Source: https://github.com/withsalt/bemfacloud/blob/main/README.md An example demonstrating how to control a switch device ('testSwitch001') using the TCP protocol with the BemfaCloud SDK. It covers building a connector, handling device events (on/off), and managing exceptions. ```csharp 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"); } } } ``` -------------------------------- ### Connect to BemfaCloud using TCP Source: https://github.com/withsalt/bemfacloud/blob/main/README.md Example code for establishing a connection to the BemfaCloud server using the TCP protocol. It demonstrates how to configure the connector with a secret key and topics, and handle connection events. ```csharp using IBemfaConnector connector = new BemfaConnectorBuilder() .WithTcp() .WithSecret("在此处填写你的私钥") .WithTopics("testSwitchMqtt001") //可订阅多个 .WithErrorHandler((e) => { Console.WriteLine($"[LOG][{DateTime.Now}] {e.Message}"); }) .WithMessageHandler((MessageEventArgs e) => { Console.WriteLine($"收到消息:" + e); }) .Build(); //连接到服务器 bool isConnect = await connector.ConnectAsync(); if (!isConnect) { throw new Exception("Connect with server faild."); } ``` -------------------------------- ### Report BemfaSensor - Sensor Device Data (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt This example shows how to report various sensor data using a Bemfa sensor device. It supports reporting temperature, humidity, air quality (AQI), light (lux), PM2.5, heart rate, and CO2 levels. Data can be reported individually or chained together before calling 'Update()'. It uses TCP for communication. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; using BemfaCloud.Devices.Models; using IBemfaConnector connector = new BemfaConnectorBuilder() .WithTcp() .WithSecret("your-secret-key") .WithTopics("envSensor004") // 后缀004表示传感器设备 .Build(); await connector.ConnectAsync(); BemfaSensor sensor = new BemfaSensor("envSensor004", connector); // 处理传感器开关事件 sensor.On += (MessageEventArgs e) => { Console.WriteLine("传感器启用"); StartSensorReading(); return true; }; sensor.Off += (MessageEventArgs e) => { Console.WriteLine("传感器禁用"); StopSensorReading(); return true; }; // 链式调用上报传感器数据 // 数据格式: #温度#湿度#开关#光照/AQI#PM2.5/心率#CO2 sensor .WithTemperature(25.5) // 温度 25.5°C .WithHumidity(60.0) // 湿度 60% .WithDeviceStatus(DeviceStatus.On) // 设备状态 .WithLux(500) // 光照强度 500 lux .WithPM25(35.0) // PM2.5 35 μg/m³ .WithPPM(400.0) // CO2 400 ppm .Update(); // 发送数据到云端 // 或者分开上报不同类型的数据 sensor.WithTemperature(26.0).WithHumidity(55.0).Update(); // 上报空气质量数据 sensor.WithAQI(50).WithPM25(25.0).Update(); // 上报心率数据(与PM2.5共用同一槽位) sensor.WithHeartRate(75).Update(); sensor.OnException += (e) => { Console.WriteLine($"传感器异常: {e.Message}"); }; ``` -------------------------------- ### Control Raspberry Pi GPIO with BemfaCloud Source: https://context7.com/withsalt/bemfacloud/llms.txt This C# implementation initializes a GPIO pin on a Raspberry Pi and maps it to a BemfaCloud smart switch. It uses the BemfaConnectorBuilder to establish an MQTT connection and handles On/Off events to toggle the physical pin state. ```csharp using System; using System.Device.Gpio; using System.Threading.Tasks; using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; class RaspberryPiSwitch { private const int GPIO_PIN = 7; static async Task Main(string[] args) { using IBemfaConnector connector = new BemfaConnectorBuilder() .WithMqtt() .WithSecret("your-secret-key") .WithTopics("piSwitch006") .WithAutoReconnectDelay(3) .Build(); bool isConnected = await connector.ConnectAsync(); if (!isConnected) return; using GpioController gpio = new GpioController(PinNumberingScheme.Board); gpio.OpenPin(GPIO_PIN, PinMode.Output); BemfaSwitch @switch = new BemfaSwitch("piSwitch006", connector); @switch.On += (e) => { gpio.Write(GPIO_PIN, PinValue.High); return true; }; @switch.Off += (e) => { gpio.Write(GPIO_PIN, PinValue.Low); return true; }; while (true) { string input = Console.ReadLine(); if (input == "q") break; } gpio.Write(GPIO_PIN, PinValue.Low); await connector.DisconnectAsync(); } } ``` -------------------------------- ### Build BemfaCloud Connectors with BemfaConnectorBuilder (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt Demonstrates how to use the BemfaConnectorBuilder to create TCP and MQTT connectors. It shows configuration options for protocols, secrets, topics, auto-reconnect, error handling, and message handling. Supports TLS encryption for MQTT. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Models; // 创建TCP连接器 using IBemfaConnector tcpConnector = new BemfaConnectorBuilder() .WithTcp() // 使用TCP协议 (端口8344) .WithSecret("your-secret-key") // 设置私钥 .WithTopics("switch001", "light002") // 订阅主题(最多8个) .WithAutoReconnectDelay(5) // 自动重连间隔5秒 .WithErrorHandler((e) => { Console.WriteLine($"错误: {e.Message}"); }) .WithMessageHandler((MessageEventArgs e) => { Console.WriteLine($"收到消息 - 主题: {e.DeviceInfo.Topic}, 内容: {e}"); }) .Build(); // 创建MQTT连接器(带TLS加密) using IBemfaConnector mqttConnector = new BemfaConnectorBuilder() .WithMqtt() // 使用MQTT协议 (端口9501) .WithTls() // 启用TLS (端口变为9503) .WithSecret("your-secret-key") .WithTopics("aircon005") .Build(); ``` -------------------------------- ### Control BemfaSwitch Device (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt Shows how to use the BemfaSwitch class to control a switch device. It covers subscribing to 'On' and 'Off' events, handling exceptions, and managing unrecognized messages. The return value of event handlers indicates success and syncs state to the cloud. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; using IBemfaConnector connector = new BemfaConnectorBuilder() .WithTcp() .WithSecret("your-secret-key") .WithTopics("mySwitch006") // 后缀006表示开关设备 .Build(); await connector.ConnectAsync(); BemfaSwitch @switch = new BemfaSwitch("mySwitch006", connector); // 处理开关打开事件 @switch.On += (MessageEventArgs e) => { Console.WriteLine("收到开关打开命令"); // 执行硬件操作,例如GPIO高电平 bool success = TurnOnHardware(); return success; // 返回true表示操作成功,状态会同步到云端 }; // 处理开关关闭事件 @switch.Off += (MessageEventArgs e) => { Console.WriteLine("收到开关关闭命令"); bool success = TurnOffHardware(); return success; }; // 处理异常 @switch.OnException += (Exception ex) => { Console.WriteLine($"开关操作异常: {ex.Message}"); }; // 处理未识别的消息 @switch.OnMessage += (MessageEventArgs e) => { Console.WriteLine($"收到未知消息: {e}"); }; ``` -------------------------------- ### Core IBemfaConnector Operations (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt Illustrates the fundamental operations of the IBemfaConnector interface, including connecting to the server, checking connection status, publishing messages, updating cloud data, registering message handlers, and disconnecting. This is essential for any device interaction. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; // 创建并连接 using IBemfaConnector connector = new BemfaConnectorBuilder() .WithMqtt() .WithSecret("your-secret-key") .WithTopics("testDevice001") .Build(); // 连接到服务器 bool isConnected = await connector.ConnectAsync(); if (!isConnected) { throw new Exception("连接服务器失败"); } Console.WriteLine($"连接状态: {connector.IsConnected}"); Console.WriteLine($"协议类型: {connector.ProtocolType}"); // 发布消息到指定主题(推送给所有订阅者,但不包括自己) await connector.PublishAsync("testDevice001", "on"); // 更新云端数据(仅更新数据,不推送) await connector.UpdateAsync("testDevice001", "off"); // 注册消息处理器 connector.MessageEventRegister((e) => { Console.WriteLine($"设备: {e.DeviceInfo.Topic}, 命令类型: {e.Type}, 数据: {e}"); }); // 断开连接 await connector.DisconnectAsync(); ``` -------------------------------- ### Control BemfaCurtain - Curtain Device (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt This snippet demonstrates controlling a Bemfa curtain device. It supports opening, closing, pausing, and setting the opening percentage. The 'On' command takes a percentage (e.g., 'on#50'), and 'Off' closes the curtain. It uses MQTT for communication. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; using IBemfaConnector connector = new BemfaConnectorBuilder() .WithMqtt() .WithSecret("your-secret-key") .WithTopics("smartCurtain009") // 后缀009表示窗帘设备 .Build(); await connector.ConnectAsync(); BemfaCurtain curtain = new BemfaCurtain("smartCurtain009", connector); // 处理窗帘打开事件(包含开合百分比) // 命令格式: on#百分比 例如: on#50 (打开到50%) // 单独的"on"命令默认打开到100% curtain.On += (MessageEventArgs e, int percentage) => { Console.WriteLine($"打开窗帘到 {percentage}%"); SetCurtainPosition(percentage); return true; }; // 处理窗帘关闭事件 curtain.Off += (MessageEventArgs e) => { Console.WriteLine("关闭窗帘"); SetCurtainPosition(0); return true; }; // 处理窗帘暂停事件 curtain.Pause += (MessageEventArgs e) => { Console.WriteLine("窗帘暂停"); StopCurtainMotor(); return true; }; curtain.OnException += (e) => { Console.WriteLine($"窗帘控制异常: {e.Message}"); }; ``` -------------------------------- ### Control BemfaSocket Device (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt Demonstrates the usage of the BemfaSocket class, which inherits from BemfaSwitch, for controlling smart socket devices. It includes event handlers for 'On' and 'Off' states and exception handling, similar to the switch functionality. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; using IBemfaConnector connector = new BemfaConnectorBuilder() .WithMqtt() .WithSecret("your-secret-key") .WithTopics("smartSocket001") // 后缀001表示插座设备 .Build(); await connector.ConnectAsync(); BemfaSocket socket = new BemfaSocket("smartSocket001", connector); socket.On += (e) => { Console.WriteLine("打开插座电源"); // 控制继电器通电 return true; }; socket.Off += (e) => { Console.WriteLine("关闭插座电源"); // 控制继电器断电 return true; }; socket.OnException += (e) => { Console.WriteLine($"插座异常: {e.Message}"); }; ``` -------------------------------- ### Supported Device Types Source: https://github.com/withsalt/bemfacloud/blob/main/README.md Lists the device types supported by BemfaCloud, their corresponding enum values, and class names. ```APIDOC ## Supported Device Types BemfaCloud supports common devices. The following table lists the supported device types, their enum values, and corresponding classes: | Device | Enum | Class | |---|---|---| | Socket | 001 | BemfaSocket | | Light | 002 | BemfaLight | | Fan | 003 | BemfaFan | | Sensor | 004 | BemfaSensor | | Air Conditioner | 005 | BemfaAircon | | Switch | 006 | BemfaSwitch | | Curtain | 009 | BemfaCurtain | ``` -------------------------------- ### BemfaCloud Device Control API Source: https://github.com/withsalt/bemfacloud/blob/main/README.md High-level API for interacting with specific device types based on topic suffixes. ```APIDOC ## POST /bemfa/device/switch ### Description Initializes a switch device control object to handle On/Off events. ### Method INITIALIZATION ### Parameters #### Path Parameters - **topic** (string) - Required - The device topic name (e.g., testSwitch006). ### Request Example BemfaSwitch @switch = new BemfaSwitch("testSwitch001", connector); ### Response #### Success Response (200) - **On** (event) - Triggered when an 'on' command is received. - **Off** (event) - Triggered when an 'off' command is received. ``` -------------------------------- ### Control BemfaSocket in C# Source: https://github.com/withsalt/bemfacloud/blob/main/README.md This C# code demonstrates how to control a BemfaSocket device. It sets up event handlers for 'On' and 'Off' actions, allowing you to execute specific logic when these events are triggered. It also includes handlers for exceptions and unparsed messages. The 'On' and 'Off' operations require a boolean return value to indicate success. ```csharp static void Socket(IBemfaConnector connector) { BemfaSocket socket = new BemfaSocket("填写设备主题", connector); socket.On += (e) => { //执行打开插座动作 Console.WriteLine("哦呦~需要打开插座"); return true; }; socket.Off += (e) => { //执行关闭插座动作 Console.WriteLine("哦呦~需要关闭插座"); return true; }; socket.OnException += (e) => { Console.WriteLine($"发生了异常:{e.Message}"); }; socket.OnMessage += (e) => { Console.WriteLine($"收到无法解析的消息:{e.ToString()}"); }; } ``` -------------------------------- ### Control BemfaFan - Fan Device (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt This snippet shows how to control a Bemfa fan device. It supports turning the fan on/off, setting fan speed (0-30), and controlling the oscillation feature. The 'On' command format is 'on#speed#oscillation', and 'Off' simply turns the fan off. It uses MQTT for communication. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; using IBemfaConnector connector = new BemfaConnectorBuilder() .WithMqtt() .WithSecret("your-secret-key") .WithTopics("smartFan003") // 后缀003表示风扇设备 .Build(); await connector.ConnectAsync(); BemfaFan fan = new BemfaFan("smartFan003", connector); // 处理风扇打开事件(包含风速和摇头状态) // 命令格式: on#风速#摇头 例如: on#3#1 (3档风速,开启摇头) fan.On += (MessageEventArgs e, int level, bool isHeadSwing) => { Console.WriteLine($"打开风扇 - 风速: {level}档, 摇头: {(isHeadSwing ? "开" : "关")}"); SetFanSpeed(level); SetFanSwing(isHeadSwing); return true; }; fan.Off += (MessageEventArgs e) => { Console.WriteLine("关闭风扇"); StopFan(); return true; }; fan.OnException += (e) => { Console.WriteLine($"风扇控制异常: {e.Message}"); }; ``` -------------------------------- ### BemfaCloud Connection API Source: https://github.com/withsalt/bemfacloud/blob/main/README.md Endpoints and builder patterns for establishing TCP or MQTT connections to the BemfaCloud platform. ```APIDOC ## CONNECT /bemfa/connector ### Description Establishes a connection to the BemfaCloud server using either TCP or MQTT protocols. ### Method BUILDER_PATTERN ### Parameters #### Request Body - **Secret** (string) - Required - The private key provided by the BemfaCloud dashboard. - **Topics** (string[]) - Required - List of device topics to subscribe to. - **Protocol** (enum) - Required - Connection type: TCP or MQTT. ### Request Example new BemfaConnectorBuilder().WithTcp().WithSecret("your_secret").WithTopics("topic001").Build(); ### Response #### Success Response (200) - **isConnect** (boolean) - Returns true if the connection to the server was successful. ``` -------------------------------- ### Control BemfaAircon - Air Conditioner Device (C#) Source: https://context7.com/withsalt/bemfacloud/llms.txt This code controls a Bemfa air conditioner. It supports setting the mode (Auto, Cooling, Heating, etc.), temperature, fan speed, and oscillation for left/right and up/down. The 'On' command format is 'on#mode#temperature#level#leftRightSweep#upDownSweep'. It uses TCP for communication. ```csharp using BemfaCloud; using BemfaCloud.Connectors.Builder; using BemfaCloud.Devices; using BemfaCloud.Devices.Models; using IBemfaConnector connector = new BemfaConnectorBuilder() .WithTcp() .WithSecret("your-secret-key") .WithTopics("smartAircon005") // 后缀005表示空调设备 .Build(); await connector.ConnectAsync(); BemfaAircon aircon = new BemfaAircon("smartAircon005", connector); // 处理空调打开事件 // 命令格式: on#模式#温度#风速#左右扫风#上下扫风 // 例如: on#2#26#3#1#0 (制冷模式,26度,3档风,左右扫风开,上下扫风关) // AirconMode: Auto=1, Cooling=2, Heating=3, Blowning=4, Dewatering=5, Sleep=6, EnergySaving=7 aircon.On += (MessageEventArgs e, AirconMode mode, double temperature, int level, bool? isLeftRightSweep, bool? isUpDownSweep) => { Console.WriteLine($"打开空调:"); Console.WriteLine($" 模式: {mode}"); Console.WriteLine($" 温度: {temperature}°C"); Console.WriteLine($" 风速: {level}档"); Console.WriteLine($" 左右扫风: {isLeftRightSweep}"); Console.WriteLine($" 上下扫风: {isUpDownSweep}"); // 发送红外命令控制空调 SendIRCommand(mode, temperature, level); return true; }; aircon.Off += (MessageEventArgs e) => { Console.WriteLine("关闭空调"); SendIRPowerOff(); return true; }; aircon.OnException += (e) => { Console.WriteLine($"空调控制异常: {e.Message}"); }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.