应用层协议

一、HTTP / HTTPS

1. 协议结构

GET / HTTP/1.1
Host: example.com
User-Agent: myapp/1.0
Accept: */*

响应:

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1234

<html>...</html>

2. 方法

3. 状态码

4. 嵌入式 HTTP 库

5. libcurl 示例

#include <curl/curl.h>

CURL *c = curl_easy_init();
curl_easy_setopt(c, CURLOPT_URL, "http://example.com/api/data");
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_perform(c);
curl_easy_cleanup(c);

二、RESTful API

GET    /api/sensors              列表
GET    /api/sensors/1            详情
POST   /api/sensors              创建
PUT    /api/sensors/1            更新
DELETE /api/sensors/1            删除

GET /api/sensors/1/data?start=...&end=...   查询
POST /api/auth/login             { user, pwd }  认证

三、JSON 库

cJSON 示例

#include "cJSON.h"

char *json = "{\"name\":\"alice\",\"age\":30}";
cJSON *root = cJSON_Parse(json);
cJSON *name = cJSON_GetObjectItem(root, "name");
printf("%s\n", name->valuestring);

cJSON_AddNumberToObject(root, "score", 95);
char *out = cJSON_Print(root);
printf("%s\n", out);
free(out);
cJSON_Delete(root);

四、MQTT(IoT 首选)

1. 概念

2. Broker

3. 客户端库

4. Paho MQTT 示例(发布)

#include "MQTTClient.h"

MQTTClient client;
MQTTClient_create(&client, "tcp://broker.hivemq.com:1883",
                  "my_client_id", MQTTCLIENT_PERSISTENCE_NONE, NULL);

MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
opts.keepAliveInterval = 20;
opts.cleansession = 1;

MQTTClient_connect(client, &opts);

MQTTClient_message pubmsg = MQTTClient_message_initializer;
pubmsg.payload = "{\"temp\":25}";
pubmsg.payloadlen = strlen(pubmsg.payload);
pubmsg.qos = 1;
pubmsg.retained = 0;

MQTTClient_publishMessage(client, "sensors/temperature", &pubmsg, NULL);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);

5. 订阅

MQTTClient_subscribe(client, "sensors/#", 1);

// 回调
int msg_arrived(void *ctx, char *topicName, int topicLen, MQTTClient_message *msg) {
    printf("topic: %s, payload: %s\n", topicName, (char*)msg->payload);
    MQTTClient_freeMessage(&msg);
    MQTTClient_free(topicName);
    return 1;
}
MQTTClient_setCallbacks(client, NULL, NULL, msg_arrived, NULL);

五、CoAP(受限设备 HTTP)

1. 特点

2. 库

3. 客户端

coap_context_t *ctx = coap_new_context(NULL);
coap_address_t addr;
coap_address_init(&addr);
addr.addr.sin.sin_family = AF_INET;
addr.addr.sin.sin_port = htons(5683);
inet_pton(AF_INET, "192.168.1.10", &addr.addr.sin.sin_addr);

coap_session_t *sess = coap_new_client_session(ctx, NULL, &addr, COAP_PROTO_UDP);

coap_pdu_t *pdu = coap_new_pdu(COAP_MESSAGE_CON, COAP_REQUEST_CODE_GET);
coap_add_option(pdu, COAP_OPTION_URI_PATH, 5, "temp");
coap_send(sess, pdu);

六、WebSocket

七、gRPC / Protocol Buffers

syntax = "proto3";
service Sensor {
    rpc Get(SensorRequest) returns (SensorResponse);
}
message SensorRequest { string id = 1; }
message SensorResponse { float value = 1; }

八、Modbus(工业)

九、OPC UA(工业 4.0)

十、选型指南

场景 协议
Web / REST HTTP/JSON
IoT 设备云端 MQTT / CoAP
视频流 RTSP / WebRTC
文件传输 FTP / SFTP / SCP
远程登录 SSH / Telnet
时间同步 NTP
DNS DNS
工业控制 Modbus / OPC UA
车内网络 CAN / SOME/IP
实时消息 MQTT / WebSocket