当前位置: 首页 > news >正文

问卷调查[bell ring]

任务

此代码使用esp32-wrom-32、按钮和蜂鸣器创建门铃。当有人按门铃时,事件被触发并上传回云端。所有通信均通过Mqtt完成。

打分标准

您应该对以下代码进行评级,并且必须遵守如下所示的评级规则。

您只能根据以下标准对1、2、3、4或5进行评分:

1.

这段代码得1分,因为它只有一个main function,没有任何功能。

#include <stdio.h>
#include "xtimer.h"// Self Executable: Test basic functionality by printing a message
int main(void) {printf("Starting Riot-OS code generation process...\n");return 0;
}

2.

这段代码得2分,因为它实现了部分通信和外围部分,不包括消息发布和接收到的消息解析。

#include <stdio.h>
#include <string.h>
#include "paho_mqtt.h"
#include "xtimer.h"
#include "periph/gpio.h"#define BUTTON_PIN_1 GPIO_PIN(PORT_A, 0)
#define BUTTON_PIN_2 GPIO_PIN(PORT_A, 1)
#define LED_PIN_1 GPIO_PIN(PORT_A, 2)
#define LED_PIN_2 GPIO_PIN(PORT_A, 3)
#define MQTT_TOPIC "button/led"
#define MQTT_BROKER_ADDRESS "test.mosquitto.org"
#define MQTT_PORT 1883static MQTTClient mqtt_client;
static Network network;void toggle_led(gpio_t led_pin) {gpio_toggle(led_pin);
}void mqtt_publish_button_press(const char *message) {MQTTMessage mqtt_message;mqtt_message.qos = QOS0;mqtt_message.retained = 0;mqtt_message.payload = (void *)message;mqtt_message.payloadlen = strlen(message);if (MQTTPublish(&mqtt_client, MQTT_TOPIC, &mqtt_message) < 0) {printf("Failed to publish MQTT message.\n");} else {printf("Published: %s\n", message);}
}void button_callback(void *arg) {gpio_t led_pin = (gpio_t)((intptr_t)arg);toggle_led(led_pin);const char *message = (led_pin == LED_PIN_1) ? "Button 1 pressed" : "Button 2 pressed";mqtt_publish_button_press(message);
}void init_mqtt() {NetworkInit(&network);MQTTClientInit(&mqtt_client, &network, 1000, NULL, 0, NULL, 0);if (NetworkConnect(&network, MQTT_BROKER_ADDRESS, MQTT_PORT) < 0) {printf("Failed to establish network connection.\n");return;}MQTTPacket_connectData connect_data = MQTTPacket_connectData_initializer;connect_data.MQTTVersion = 3;connect_data.clientID.cstring = "RIOT-MQTT-Client";if (MQTTConnect(&mqtt_client, &connect_data) < 0) {printf("MQTT client connection failed.\n");return;}printf("MQTT client connected to broker.\n");
}int main(void) {gpio_init_int(BUTTON_PIN_1, GPIO_IN_PU, GPIO_FALLING, button_callback, (void *)LED_PIN_1);gpio_init_int(BUTTON_PIN_2, GPIO_IN_PU, GPIO_FALLING, button_callback, (void *)LED_PIN_2);gpio_init(LED_PIN_1, GPIO_OUT);gpio_init(LED_PIN_2, GPIO_OUT);init_mqtt();while (1) {// Process MQTT messages and yield executionMQTTYield(&mqtt_client, 1000);}return 0;
}

3.

这段代码得3分,因为它虽然实现了主要功能,但不解析接收到的消息。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "paho_mqtt.h"
#include "MQTTClient.h"
#include "xtimer.h"
#include "periph/gpio.h"
#include "periph/i2c.h"#define MQTT_SERVER "101.133.196.127"
#define MQTT_PORT 1883
#define MQTT_USER "YOUR_MQTT_USERNAME"
#define MQTT_PASSWORD "YOUR_MQTT_PASSWORD"
#define MQTT_CLIENT_ID "YOUR_MQTT_CLIENT_ID"
#define SUBSCRIBE_TOPIC "YOUR_SUBSCRIBE_TOPIC"
#define REPORT_TOPIC "YOUR_REPORT_TOPIC"#define BUF_SIZE 1024
#define COMMAND_TIMEOUT_MS 6000
#define KEEP_ALIVE_INTERVAL 60#define BUTTON_PIN GPIO_PIN(0, 0)
#define LED_PIN GPIO_PIN(0, 1)static MQTTClient client;
static Network network;
static unsigned char buf[BUF_SIZE];
static unsigned char readbuf[BUF_SIZE];void mqtt_setup(void);
int reconnect(void);
void report_property(const char* topic, char* payload);
void messageArrived(MessageData* data);
void init_gpio(void);
void button_callback(void *arg);void mqtt_setup(void) {NetworkInit(&network);MQTTClientInit(&client, &network, COMMAND_TIMEOUT_MS, buf, BUF_SIZE, readbuf, BUF_SIZE);printf("MQTT client initialized\\n");
}int reconnect(void) {MQTTPacket_connectData data = MQTTPacket_connectData_initializer;data.MQTTVersion = 4;data.clientID.cstring = MQTT_CLIENT_ID;data.username.cstring = MQTT_USER;data.password.cstring = MQTT_PASSWORD;data.keepAliveInterval = KEEP_ALIVE_INTERVAL;data.cleansession = 1;int rc = NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);if (rc != 0) {printf("Failed to connect to network (%d)\\n", rc);return rc;}rc = MQTTConnect(&client, &data);if (rc != 0) {printf("Failed to connect to broker (%d)\\n", rc);return rc;}MQTTSubscribe(&client, SUBSCRIBE_TOPIC, QOS1, messageArrived);return 0;
}void report_property(const char* topic, char* json) {MQTTMessage message;message.qos = QOS0;message.retained = 0;message.payload = json;message.payloadlen = strlen(json);MQTTPublish(&client, topic, &message);printf("Published: %s\\n", json);
}void messageArrived(MessageData* data) {char* payload = (char*)data->message->payload;printf("Message arrived [%.*s]: %.*s\\n",(int)data->topicName->lenstring.len, data->topicName->lenstring.data,(int)data->message->payloadlen, payload);// Handle messages here
}void init_gpio(void) {gpio_init_int(BUTTON_PIN, GPIO_IN_PU, GPIO_FALLING, button_callback, NULL);gpio_init(LED_PIN, GPIO_OUT);
}void button_callback(void *arg) {(void)arg;gpio_toggle(LED_PIN);char json[64];snprintf(json, sizeof(json), "{\\\"button\\\":\\\"pressed\\\"}");report_property(REPORT_TOPIC, json);
}int main(void) {mqtt_setup();init_gpio();while (1) {if (!client.isconnected) {NetworkDisconnect(&network);NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);reconnect();}MQTTYield(&client, 1000);xtimer_sleep(5);}return 0;
}

4.

这段代码得4分,因为它实现了主要功能,但如果它在通信中断开连接,并且代码的长度可以更长,它可能会更好。

#include <stdio.h>
#include <string.h>
#include "periph/gpio.h"
#include "paho_mqtt.h"
#include "MQTTClient.h"
#include "xtimer.h"
#include "periph/i2c.h"// Define hardware mapping
#define ROW1_PIN GPIO_PIN(0, 0) // Adjust pins based on your board
#define ROW2_PIN GPIO_PIN(0, 1)
#define LED1_PIN GPIO_PIN(0, 2)
#define LED2_PIN GPIO_PIN(0, 3)// Alternate name for I2C device to avoid conflict
#define MY_I2C_DEV I2C_DEV(0)// MQTT Parameters
#define MQTT_SERVER "101.133.196.127"
#define MQTT_PORT 1883
#define MQTT_USER "YOUR_MQTT_USERNAME"
#define MQTT_PASSWORD "YOUR_MQTT_PASSWORD"
#define MQTT_CLIENT_ID "YOUR_MQTT_CLIENT_ID"
#define SUBSCRIBE_TOPIC "switch_control"
#define REPORT_TOPIC "status_report"// MQTT Client Buffer Sizes
#define BUF_SIZE 1024
#define COMMAND_TIMEOUT_MS 6000
#define KEEP_ALIVE_INTERVAL 60static MQTTClient client;
static Network network;
static unsigned char buf[BUF_SIZE];
static unsigned char readbuf[BUF_SIZE];// Forward declaration of the message handler
void messageArrived(MessageData* data);// Initialize MQTT
void mqtt_setup(void) {NetworkInit(&network);MQTTClientInit(&client, &network, COMMAND_TIMEOUT_MS, buf, BUF_SIZE, readbuf, BUF_SIZE);printf("MQTT client initialized\n");
}// Attempt reconnection
int reconnect(void) {MQTTPacket_connectData data = MQTTPacket_connectData_initializer;data.MQTTVersion = 4;data.clientID.cstring = MQTT_CLIENT_ID;data.username.cstring = MQTT_USER;data.password.cstring = MQTT_PASSWORD;data.keepAliveInterval = KEEP_ALIVE_INTERVAL;data.cleansession = 1;int rc = NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);if (rc != 0) {printf("Failed to connect to network (%d)\n", rc);return rc;}rc = MQTTConnect(&client, &data);if (rc != 0) {printf("Failed to connect to broker (%d)\n", rc);return rc;}MQTTSubscribe(&client, SUBSCRIBE_TOPIC, QOS1, messageArrived);return 0;
}// Report property to the cloud
void report_property(const char* topic, char* json) {MQTTMessage message;message.qos = QOS0;message.retained = 0;message.payload = json;message.payloadlen = strlen(json);MQTTPublish(&client, topic, &message);printf("Published: %s\n", json);
}// Handle incoming messages
void messageArrived(MessageData* data) {char* payload = (char*)data->message->payload;printf("Message arrived [%.*s]: %.*s\n",(int)data->topicName->lenstring.len, data->topicName->lenstring.data,(int)data->message->payloadlen, payload);if (strstr(payload, "LED_ON")) {gpio_set(LED1_PIN);gpio_set(LED2_PIN);} else if (strstr(payload, "LED_OFF")) {gpio_clear(LED1_PIN);gpio_clear(LED2_PIN);}
}// Initialize buttons and LEDs
void init_gpio(void) {gpio_init(ROW1_PIN, GPIO_IN);gpio_init(ROW2_PIN, GPIO_IN);gpio_init(LED1_PIN, GPIO_OUT);gpio_init(LED2_PIN, GPIO_OUT);
}int main(void) {mqtt_setup();init_gpio();while (1) {if (!client.isconnected) {NetworkDisconnect(&network);NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);reconnect();}// Read button states and update LEDsif (gpio_read(ROW1_PIN)) {gpio_set(LED1_PIN);char json[256];snprintf(json, sizeof(json), "{\"button\": \"ROW1\", \"status\": \"pressed\"}");report_property(REPORT_TOPIC, json);} else {gpio_clear(LED1_PIN);}if (gpio_read(ROW2_PIN)) {gpio_set(LED2_PIN);char json[256];snprintf(json, sizeof(json), "{\"button\": \"ROW2\", \"status\": \"pressed\"}");report_property(REPORT_TOPIC, json);} else {gpio_clear(LED2_PIN);}MQTTYield(&client, 1000);xtimer_sleep(5000);  // Sleep for 5 seconds}return 0;
}

5.

这段代码得5分,因为它完全实现了包括消息传输和解析在内的功能,同时还具有通信断开和更长长度的功能。

#include <stdio.h>
#include <string.h>
#include "paho_mqtt.h"
#include "MQTTClient.h"
#include "xtimer.h"
#include "periph/gpio.h"
#include "ztimer.h"// Hardware Pin Definitions
#define BUTTON1_PIN GPIO_PIN(0, 16)  // Adjust based on your hardware
#define BUTTON2_PIN GPIO_PIN(0, 17)  // Adjust based on your hardware
#define LED1_PIN GPIO_PIN(0, 8)      // Adjust based on your hardware
#define LED2_PIN GPIO_PIN(0, 9)      // Adjust based on your hardware// MQTT Configuration Constants
#define MQTT_SERVER "101.133.196.127"
#define MQTT_PORT 1883
#define MQTT_USER "double_bank_switch&k1unt3JS8bi"
#define MQTT_PASSWORD "b88ecf285f05312daab5be1f8b8bbf8b5107e649869552f839bb4d9e3ca3d5c7"
#define MQTT_CLIENT_ID "k1unt3JS8bi.double_bank_switch|securemode=2,signmethod=hmacsha256,timestamp=1734239881881|"
#define SUBSCRIBE_TOPIC "/sys/k1unt3JS8bi/double_bank_switch/thing/service/property/set"
#define REPORT_TOPIC "/sys/k1unt3JS8bi/double_bank_switch/thing/event/property/post"// MQTT Buffer Sizes
#define BUF_SIZE 1024
#define COMMAND_TIMEOUT_MS 6000
#define KEEP_ALIVE_INTERVAL 60// Global Variables
static MQTTClient client;            // MQTT client structure
static Network network;              // MQTT network structure
static unsigned char buf[BUF_SIZE];  // Send buffer
static unsigned char readbuf[BUF_SIZE];  // Receive bufferstatic int left_button_state = 0;  // Tracks left button state
static int right_button_state = 0;  // Tracks right button state// Function Prototypes
void mqtt_setup(void);               // Setup MQTT
int reconnect(void);                 // Reconnect to MQTT broker
void report_property(const char* topic, char* json);  // Publish a property to the cloud
void messageArrived(MessageData* data);  // Handle incoming MQTT messages
void setup_gpio(void);               // GPIO setup logic
void check_buttons(void);            // Button press handler// Toggle LED helper
void toggle_led(gpio_t led_pin, int state) {if (state) {gpio_set(led_pin);  // Set GPIO pin high} else {gpio_clear(led_pin);  // Set GPIO pin low}
}// GPIO initialization
void setup_gpio(void) {if (gpio_init(BUTTON1_PIN, GPIO_IN_PU) < 0) {printf("Failed to initialize BUTTON1\\n");}if (gpio_init(BUTTON2_PIN, GPIO_IN_PU) < 0) {printf("Failed to initialize BUTTON2\\n");}if (gpio_init(LED1_PIN, GPIO_OUT) < 0) {printf("Failed to initialize LED1\\n");}if (gpio_init(LED2_PIN, GPIO_OUT) < 0) {printf("Failed to initialize LED2\\n");}
}// Button press logic
void check_buttons(void) {if (gpio_read(BUTTON1_PIN) == 0) {  // BUTTON1 pressedleft_button_state = !left_button_state;toggle_led(LED1_PIN, left_button_state);ztimer_sleep(ZTIMER_USEC, 200000);  // Add debounce delay}if (gpio_read(BUTTON2_PIN) == 0) {  // BUTTON2 pressedright_button_state = !right_button_state;toggle_led(LED2_PIN, right_button_state);ztimer_sleep(ZTIMER_USEC, 200000);  // Add debounce delay}
}// MQTT setup logic
void mqtt_setup(void) {NetworkInit(&network);  // Initialize MQTT networkMQTTClientInit(&client, &network, COMMAND_TIMEOUT_MS, buf, BUF_SIZE, readbuf, BUF_SIZE);printf("MQTT client initialized\\n");reconnect();  // Connect to the MQTT broker
}// Reconnect logic to MQTT broker
int reconnect(void) {MQTTPacket_connectData data = MQTTPacket_connectData_initializer;data.MQTTVersion = 4;data.clientID.cstring = MQTT_CLIENT_ID;data.username.cstring = MQTT_USER;data.password.cstring = MQTT_PASSWORD;data.keepAliveInterval = KEEP_ALIVE_INTERVAL;data.cleansession = 1;int rc = NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);if (rc != 0) {printf("Failed to connect to network (%d)\\n", rc);return rc;}rc = MQTTConnect(&client, &data);if (rc != 0) {printf("Failed to connect to broker (%d)\\n", rc);return rc;}// Set up MQTT message subscriptionrc = MQTTSubscribe(&client, SUBSCRIBE_TOPIC, QOS1, messageArrived);if (rc != 0) {printf("Failed to subscribe to topic (%s)\\n", SUBSCRIBE_TOPIC);}return rc;
}// Publish property state update to the cloud
void report_property(const char* topic, char* json) {MQTTMessage message;message.qos = QOS0;message.retained = 0;message.payload = (void*)json;message.payloadlen = strlen(json);MQTTPublish(&client, topic, &message);printf("Published: %s\\n", json);
}// Handles incoming MQTT messages; changes LED state based on cloud input
void messageArrived(MessageData* data) {char* payload = (char*)data->message->payload;printf("Message arrived [%.*s]: %.*s\\n",(int)data->topicName->lenstring.len, data->topicName->lenstring.data,(int)data->message->payloadlen, payload);if (strstr(payload, "\"led1\":1")) {toggle_led(LED1_PIN, 1);left_button_state = 1;} else if (strstr(payload, "\"led1\":0")) {toggle_led(LED1_PIN, 0);left_button_state = 0;} else if (strstr(payload, "\"led2\":1")) {toggle_led(LED2_PIN, 1);right_button_state = 1;} else if (strstr(payload, "\"led2\":0")) {toggle_led(LED2_PIN, 0);right_button_state = 0;}
}// Main function
int main(void) {mqtt_setup();  // Set up MQTTsetup_gpio();  // Set up GPIOwhile (1) {if (!client.isconnected) {NetworkDisconnect(&network);  // Disconnect if network is unavailablereconnect();  // Attempt reconnection}check_buttons();  // Check button states// Publish button/LED state to MQTTchar json[256];snprintf(json, sizeof(json), "{\"left_button\": %d, \"right_button\": %d}", left_button_state, right_button_state);report_property(REPORT_TOPIC, json);MQTTYield(&client, 1000);  // Allow MQTT client to process packetsxtimer_sleep(5000);       // Delay for 5 seconds}return 0;
}
// Self Executable

代码

代码1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "periph/gpio.h"
#include "ztimer.h"
#include "paho_mqtt.h"
#include "MQTTClient.h"
#include "xtimer.h"#define BUTTON1_PIN    GPIO_PIN(0, 16) // Define button pins
#define BUTTON2_PIN    GPIO_PIN(0, 17) // Define button pins
#define LED1_PIN       GPIO_PIN(0, 8)  // Define LED pins
#define LED2_PIN       GPIO_PIN(0, 9)  // Define LED pinsbool leftButtonState = false;           // Button state for BUTTON1
bool rightButtonState = false;          // Button state for BUTTON2// MQTT Parameters
#define MQTT_SERVER "101.133.196.127"
#define MQTT_PORT 1883
#define MQTT_USER "YOUR_MQTT_USERNAME"
#define MQTT_PASSWORD "YOUR_MQTT_PASSWORD"
#define MQTT_CLIENT_ID "YOUR_MQTT_CLIENT_ID"
#define SUBSCRIBE_TOPIC "/sys/k1unt3JS8bi/double_bank_switch/thing/service/property/set"
#define REPORT_TOPIC "/sys/k1unt3JS8bi/double_bank_switch/thing/event/property/post"// MQTT Client Buffer Sizes
#define BUF_SIZE 1024
#define COMMAND_TIMEOUT_MS 6000
#define KEEP_ALIVE_INTERVAL 60static MQTTClient client;
static Network network;
static unsigned char buf[BUF_SIZE];
static unsigned char readbuf[BUF_SIZE];// Declaration of messageArrived function
void messageArrived(MessageData* data);void initialize_gpio(void) {// Initialize button pins with pull-upif (gpio_init(BUTTON1_PIN, GPIO_IN_PU) < 0) {printf("Failed to init BUTTON1\n");}if (gpio_init(BUTTON2_PIN, GPIO_IN_PU) < 0) {printf("Failed to init BUTTON2\n");}// Initialize LED pins as outputif (gpio_init(LED1_PIN, GPIO_OUT) < 0) {printf("Failed to init LED1\n");}if (gpio_init(LED2_PIN, GPIO_OUT) < 0) {printf("Failed to init LED2\n");}
}void check_buttons(void) {// Check BUTTON1, toggle state, and update LED1if (gpio_read(BUTTON1_PIN) == 0) {leftButtonState = !leftButtonState;gpio_write(LED1_PIN, leftButtonState ? 1 : 0);ztimer_sleep(ZTIMER_USEC, 200000); // Debouncing delay}// Check BUTTON2, toggle state, and update LED2if (gpio_read(BUTTON2_PIN) == 0) {rightButtonState = !rightButtonState;gpio_write(LED2_PIN, rightButtonState ? 1 : 0);ztimer_sleep(ZTIMER_USEC, 200000); // Debouncing delay}
}void mqtt_setup(void) {NetworkInit(&network);MQTTClientInit(&client, &network, COMMAND_TIMEOUT_MS, buf, BUF_SIZE, readbuf, BUF_SIZE);printf("MQTT client initialized\n"); // Self Executable
}int reconnect(void) {MQTTPacket_connectData data = MQTTPacket_connectData_initializer;data.MQTTVersion = 4;data.clientID.cstring = MQTT_CLIENT_ID;data.username.cstring = MQTT_USER;data.password.cstring = MQTT_PASSWORD;data.keepAliveInterval = KEEP_ALIVE_INTERVAL;data.cleansession = 1;int rc = NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);if (rc != 0) {printf("Failed to connect to network (%d)\n", rc); // Self Executablereturn rc;}rc = MQTTConnect(&client, &data);if (rc != 0) {printf("Failed to connect to broker (%d)\n", rc); // Self Executablereturn rc;}MQTTSubscribe(&client, SUBSCRIBE_TOPIC, QOS1, messageArrived);printf("Subscribed to topic: %s\n", SUBSCRIBE_TOPIC); // Self Executablereturn 0;
}void report_property(const char* topic, char* json) {MQTTMessage message;message.qos = QOS0;message.retained = 0;message.payload = json;message.payloadlen = strlen(json);MQTTPublish(&client, topic, &message);printf("Published: %s\n", json); // Self Executable
}void messageArrived(MessageData* data) {char* payload = (char*)data->message->payload;printf("Message arrived [%.*s]: %.*s\n",(int)data->topicName->lenstring.len, data->topicName->lenstring.data,(int)data->message->payloadlen, payload); // Self Executableif (strstr(payload, "\"params\":")) {if (strstr(payload, "\"left_button\":1")) {leftButtonState = true;gpio_write(LED1_PIN, 1);printf("Left Button State: 1\n"); // Self Executable} else if (strstr(payload, "\"left_button\":0")) {leftButtonState = false;gpio_write(LED1_PIN, 0);printf("Left Button State: 0\n"); // Self Executable}if (strstr(payload, "\"right_button\":1")) {rightButtonState = true;gpio_write(LED2_PIN, 1);printf("Right Button State: 1\n"); // Self Executable} else if (strstr(payload, "\"right_button\":0")) {rightButtonState = false;gpio_write(LED2_PIN, 0);printf("Right Button State: 0\n"); // Self Executable}}
}int main(void) {// Initialize GPIO pins for buttons and LEDsinitialize_gpio();mqtt_setup();while (1) {check_buttons();// Reconnect if neededif (!client.isconnected) {NetworkDisconnect(&network);NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);reconnect();}char json[256];snprintf(json, sizeof(json), "{\"id\": %d, \"version\": \"1.0\", \"params\": {\"left_button\": %d, \"right_button\": %d}}", 1, leftButtonState, rightButtonState);report_property(REPORT_TOPIC, json);MQTTYield(&client, 1000); // Allow MQTT client to process incoming messagesxtimer_sleep(5); // Self Executable}return 0;
}

评分:

 代码2

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "paho_mqtt.h"
#include "MQTTClient.h"
#include "xtimer.h"
#include "periph/gpio.h"// Define PORT_A and PORT_C
#define PORT_A 0
#define PORT_C 1// MQTT Parameters
#define MQTT_SERVER "101.133.196.127"
#define MQTT_PORT 1883
#define MQTT_USER "double_bank_switch&k1unt3JS8bi"
#define MQTT_PASSWORD "b88ecf285f05312daab5be1f8b8bbf8b5107e649869552f839bb4d9e3ca3d5c7"
#define MQTT_CLIENT_ID "k1unt3JS8bi.double_bank_switch|securemode=2,signmethod=hmacsha256,timestamp=1734239881881|"
#define SUBSCRIBE_TOPIC "/sys/k1unt3JS8bi/double_bank_switch/thing/service/property/set"
#define REPORT_TOPIC "/sys/k1unt3JS8bi/double_bank_switch/thing/event/property/post"// MQTT Client Buffer Sizes
#define BUF_SIZE 1024
#define COMMAND_TIMEOUT_MS 6000
#define KEEP_ALIVE_INTERVAL 60static MQTTClient client;
static Network network;
static unsigned char buf[BUF_SIZE];
static unsigned char readbuf[BUF_SIZE];// Global states for buttons
static bool leftButtonState = false;
static bool rightButtonState = false;// Function Prototypes
void mqtt_setup(void);
int reconnect(void);
void report_property(const char* topic, char* payload);
void messageArrived(MessageData* data);
void init_gpio(void);#define BUTTON1 GPIO_PIN(PORT_A, 0)
#define BUTTON2 GPIO_PIN(PORT_A, 1)
#define LED1 GPIO_PIN(PORT_C, 0)
#define LED2 GPIO_PIN(PORT_C, 1)void init_gpio(void) {gpio_init_int(BUTTON1, GPIO_IN_PU, GPIO_RISING, NULL, NULL);gpio_init_int(BUTTON2, GPIO_IN_PU, GPIO_RISING, NULL, NULL);gpio_init(LED1, GPIO_OUT);gpio_init(LED2, GPIO_OUT);
}void mqtt_setup(void) {NetworkInit(&network);MQTTClientInit(&client, &network, COMMAND_TIMEOUT_MS, buf, BUF_SIZE, readbuf, BUF_SIZE);printf("MQTT client initialized\n");
}void check_and_toggle_buttons(void) {if (gpio_read(BUTTON1) == 0) {leftButtonState = !leftButtonState;gpio_write(LED1, leftButtonState ? 1 : 0);report_property(REPORT_TOPIC, "{\"left_button\":1}");xtimer_usleep(200000);}if (gpio_read(BUTTON2) == 0) {rightButtonState = !rightButtonState;gpio_write(LED2, rightButtonState ? 1 : 0);report_property(REPORT_TOPIC, "{\"right_button\":1}");xtimer_usleep(200000);}
}int reconnect(void) {MQTTPacket_connectData data = MQTTPacket_connectData_initializer;data.MQTTVersion = 4;data.clientID.cstring = MQTT_CLIENT_ID;data.username.cstring = MQTT_USER;data.password.cstring = MQTT_PASSWORD;data.keepAliveInterval = KEEP_ALIVE_INTERVAL;data.cleansession = 1;int rc = NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);if (rc != 0) {printf("Failed to connect to network (%d)\n", rc);return rc;}rc = MQTTConnect(&client, &data);if (rc != 0) {printf("Failed to connect to broker (%d)\n", rc);return rc;}MQTTSubscribe(&client, SUBSCRIBE_TOPIC, QOS1, messageArrived);return 0;
}void messageArrived(MessageData* data) {char* payload = (char*)data->message->payload;printf("Message arrived [%.*s]: %.*s\n",(int)data->topicName->lenstring.len, data->topicName->lenstring.data,(int)data->message->payloadlen, payload);// Add parsing logic for JSON and update button states
}void report_property(const char* topic, char* payload) {MQTTMessage message;message.qos = QOS0;message.retained = 0;message.payload = payload;message.payloadlen = strlen(payload);MQTTPublish(&client, topic, &message);printf("Published: %s\n", payload);
}int main(void) {mqtt_setup();init_gpio();if (reconnect() != 0) {printf("MQTT connection failed!\n");return 1;}while (1) {MQTTYield(&client, 1000);check_and_toggle_buttons();xtimer_sleep(5);}return 0;
}// Self Executable

评分:

代码3

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "paho_mqtt.h"
#include "MQTTClient.h"
#include "xtimer.h"
#include "periph/gpio.h"
#include "periph/i2c.h"#define MQTT_SERVER "101.133.196.127"
#define MQTT_PORT 1883
#define MQTT_USER "YOUR_MQTT_USERNAME"
#define MQTT_PASSWORD "YOUR_MQTT_PASSWORD"
#define MQTT_CLIENT_ID "YOUR_MQTT_CLIENT_ID"
#define SUBSCRIBE_TOPIC "YOUR_SUBSCRIBE_TOPIC"
#define REPORT_TOPIC "YOUR_REPORT_TOPIC"#define BUF_SIZE 1024
#define COMMAND_TIMEOUT_MS 6000
#define KEEP_ALIVE_INTERVAL 60#define BUTTON_PIN GPIO_PIN(0, 0)
#define LED_PIN GPIO_PIN(0, 1)static MQTTClient client;
static Network network;
static unsigned char buf[BUF_SIZE];
static unsigned char readbuf[BUF_SIZE];void mqtt_setup(void);
int reconnect(void);
void report_property(const char* topic, char* payload);
void messageArrived(MessageData* data);
void init_gpio(void);
void button_callback(void *arg);void mqtt_setup(void) {NetworkInit(&network);MQTTClientInit(&client, &network, COMMAND_TIMEOUT_MS, buf, BUF_SIZE, readbuf, BUF_SIZE);printf("MQTT client initialized\\n");
}int reconnect(void) {MQTTPacket_connectData data = MQTTPacket_connectData_initializer;data.MQTTVersion = 4;data.clientID.cstring = MQTT_CLIENT_ID;data.username.cstring = MQTT_USER;data.password.cstring = MQTT_PASSWORD;data.keepAliveInterval = KEEP_ALIVE_INTERVAL;data.cleansession = 1;int rc = NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);if (rc != 0) {printf("Failed to connect to network (%d)\\n", rc);return rc;}rc = MQTTConnect(&client, &data);if (rc != 0) {printf("Failed to connect to broker (%d)\\n", rc);return rc;}MQTTSubscribe(&client, SUBSCRIBE_TOPIC, QOS1, messageArrived);return 0;
}void report_property(const char* topic, char* json) {MQTTMessage message;message.qos = QOS0;message.retained = 0;message.payload = json;message.payloadlen = strlen(json);MQTTPublish(&client, topic, &message);printf("Published: %s\\n", json);
}void messageArrived(MessageData* data) {char* payload = (char*)data->message->payload;printf("Message arrived [%.*s]: %.*s\\n",(int)data->topicName->lenstring.len, data->topicName->lenstring.data,(int)data->message->payloadlen, payload);// Handle messages here
}void init_gpio(void) {gpio_init_int(BUTTON_PIN, GPIO_IN_PU, GPIO_FALLING, button_callback, NULL);gpio_init(LED_PIN, GPIO_OUT);
}void button_callback(void *arg) {(void)arg;gpio_toggle(LED_PIN);char json[64];snprintf(json, sizeof(json), "{\\\"button\\\":\\\"pressed\\\"}");report_property(REPORT_TOPIC, json);
}int main(void) {mqtt_setup();init_gpio();while (1) {if (!client.isconnected) {NetworkDisconnect(&network);NetworkConnect(&network, MQTT_SERVER, MQTT_PORT);reconnect();}MQTTYield(&client, 1000);xtimer_sleep(5);}return 0;
}

评分:

http://www.lqws.cn/news/545383.html

相关文章:

  • 全志A733、瑞芯微RK3576与联发科MTK8371场景化应用解析在物联网与智能设备快速迭代的今天,芯片作为硬件核心直接决定了设备的性能边界与应用场景。
  • moduo之tcp客户端TcpClient
  • Webpack 自定义插件开发指南:构建流程详解与实战开发全攻略
  • Html5播放器禁止拖动播放器进度条(教学场景)
  • 神经网络的概念和案例
  • FrozenBatchNorm2d 详解
  • 聚铭网络入选嘶吼《中国网络安全细分领域产品名录》“云平台安全管理”与“态势感知”双领域TOP10
  • Linux tcp_info:监控TCP连接的秘密武器
  • CatBoost:征服类别型特征的梯度提升王者
  • 蓝牙工作频段与跳频扩频技术(FHSS)详解:面试高频考点与真题解析
  • System.Threading.Tasks 库简介
  • ubuntu ollama 遇到的若干问题
  • Linux命令行操作基础
  • WPF 3D 开发全攻略:实现3D模型创建、旋转、平移、缩放
  • 记录一个C#/.NET的HTTP工具类
  • Feign 实战指南:从 REST 替代到性能优化与最佳实践
  • 文法、正规式相关习题
  • Linux系统(信号篇)信号的保存
  • WinAppDriver 自动化测试:JavaScript 篇
  • gRPC技术解析与python示例
  • Python基础知识之文件
  • JMH (Java Microbenchmark Harness)
  • .NET MAUI跨平台串口通讯方案
  • (LeetCode 面试经典 150 题 ) 238. 除自身以外数组的乘积 (前缀和)
  • LeetCode 312 戳气球题解(Swift)+ 区间 DP 原理详解 + 可运行代码
  • WSL升级到24.04
  • 使用 asp.net core webapi 导出数据文件
  • .NetCore+Vue快速生产框架开发详细方案
  • LeetCode 349题解 | 两个数组的交集
  • 苍穹外卖day5--Redis设置店铺营业状态