[go] Go 언어와 IoT 시스템의 통신 프로토콜
서론
IoT(Internet of Things) 시스템에서는 장치 간 통신이 매우 중요합니다. 이를 위해 사용되는 프로토콜은 장치 간 데이터 통신을 안정적이고 효과적으로 하기 위한 핵심 요소입니다. 이번 포스트에서는 Go 언어를 사용하여 IoT 시스템과의 통신을 위한 다양한 프로토콜을 살펴보겠습니다.
MQTT 프로토콜
MQTT는 경량 메시지 브로커 프로토콜로, IoT 디바이스 간 실시간 데이터 스트리밍과 연결을 위해 디자인되었습니다. Go의 paho.mqtt
라이브러리를 사용하여 MQTT 프로토콜을 사용하는 서버 및 클라이언트를 구현할 수 있습니다.
import (
"fmt"
"os"
"time"
"github.com/eclipse/paho.mqtt.golang"
)
func main() {
opts := mqtt.NewClientOptions().AddBroker("tcp://iot.eclipse.org:1883")
opts.SetClientID("go-mqtt-example")
opts.SetDefaultPublishHandler(func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
})
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
token := client.Subscribe("topic/test", 1, nil)
token.Wait()
time.Sleep(3 * time.Second)
token = client.Unsubscribe("topic/test")
token.Wait()
client.Disconnect(250)
}
CoAP 프로토콜
CoAP는 제한된 장치와 대규모 장치 사이의 통신을 활성화하기 위한 Constrained Application Protocol입니다. Go의 github.com/dustin/go-coap
라이브러리를 사용하여 CoAP 프로토콜을 구현할 수 있습니다.
import (
"log"
"github.com/dustin/go-coap"
)
func main() {
co, err := coap.Dial("udp", "localhost:5683")
if err != nil {
log.Fatalf("Error dialing: %v", err)
}
path := "/other/sensor"
req := coap.Message{
Type: coap.Confirmable,
Code: coap.GET,
}
req.SetPathString(path)
rv, err := co.Exchange(req)
if err != nil {
log.Fatalf("Error sending request: %v", err)
}
log.Printf("Response payload: %s", rv.Payload)
}
결론
Go 언어는 다양한 IoT 시스템과 통신하기 위한 강력한 라이브러리를 제공하고 있습니다. MQTT 및 CoAP와 같은 통신 프로토콜을 사용하여 안정적이고 신뢰할 수 있는 IoT 시스템을 빌드하는 데 도움이 됩니다.