分类 Go 下的文章

“Go是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言。 罗伯特·格瑞史莫、罗勃·派克及肯·汤普逊于2007年9月开始设计Go,稍后伊恩·兰斯·泰勒、拉斯·考克斯加入项目。Go是基于Inferno操作系统所开发的。”

本示例用在linux上,用在windows上的话,要修改串口号为COM之类。
要使用goserial要先安装

go get github.com/tarm/goserial

直接上代码

package main

import (
    "encoding/hex"
    "fmt"
    "io"
    "net"
    "os"
    "strings"
    "time"

    serial "github.com/tarm/goserial"
)

var g_serial_rwc io.ReadWriteCloser
func main() {
    //com3 ttymxc2 ok.
    cfg := &serial.Config{Name: "/dev/ttymxc2", Baud: 115200, ReadTimeout: 10 * time.Millisecond /*毫秒*/}

    g_serial_rwc, err := serial.OpenPort(cfg)
    if err != nil {
        Info.Printf("open serial fail. %s", err)
        os.Exit(1)
        return
    }

    defer g_serial_rwc.Close()
    buffer := make([]byte, MAXRWLEN)

    //发命令之前清空缓冲区
    Info.Printf("发命令之前清空缓冲区")
    num, _ := g_serial_rwc.Read(buffer)

    Info.Printf("发命令数据类型为[]byte")
    //发命令数据类型为[]byte
    init_rsu(g_serial_rwc)

    Info.Printf("Read 10 times")
    var tmpstr string = ""
    for i := 0; i < 10; i++ {
        Info.Printf("read %d", i)
        num, err = g_serial_rwc.Read(buffer)
        if num > 0 {
            tmpstr += fmt.Sprintf("%s", strings.ToUpper(hex.EncodeToString(buffer[:num])))
            Info.Printf(tmpstr)
        } //查找读到信息的结尾标志
        if strings.LastIndex(tmpstr, "FF") > 0 {
            break
        }
    }

    Info.Printf("打印输出读到的信息")
    //打印输出读到的信息
    fmt.Println(tmpstr)

    return
}

package main

import (
    "fmt"
    "os"
    "time"

    mqtt "github.com/eclipse/paho.mqtt.golang"
)

var onConnect mqtt.OnConnectHandler = func(client mqtt.Client) {
    Info.Printf("Client connected: %t\n", client.IsConnected())
    // 订阅主题
    if token := client.Subscribe("const.net.cn/#", 0, nil); token.Wait() && token.Error() != nil {
        fmt.Println(token.Error())
        os.Exit(1)
    }
}

var onMessage mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
    Info.Printf("Topic: %s\n", msg.Topic())
    Info.Printf("Message: %s\n", msg.Payload())
}

var onDisconnect mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
    Info.Println("Client disconnected")
}
var onReconnect mqtt.ReconnectHandler = func(c mqtt.Client, co *mqtt.ClientOptions) {
    Info.Println("Client Reconnect.")
}
    
func MQTT_1883_unencrypted_unauthenticated() {
    opts := mqtt.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883").SetClientID("const.net.cn")

    opts.SetKeepAlive(60 * time.Second)
    // 设置消息回调处理函数
    opts.SetDefaultPublishHandler(onMessage)
    opts.SetCleanSession(true)
    opts.SetAutoReconnect(true)
    opts.SetProtocolVersion(4) //3.1.1
    opts.SetOnConnectHandler(onConnect)
    opts.SetConnectionLostHandler(onDisconnect)
    opts.SetReconnectingHandler(onReconnect)

    opts.SetPingTimeout(1 * time.Second)

    c := mqtt.NewClient(opts)
    if token := c.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }

    time.Sleep(5 * time.Second)
    // 发布消息
    Info.Printf("MQTT Publish")
    token := c.Publish("const.net.cn/1", 0, false, "Hello World")
    token.Wait()

    for {
        Info.Printf("wait.")
        time.Sleep(10 * time.Second)
    }
}

运行结果:
INFO: 2021/09/06 15:05:08.897152 Client connected: true
INFO: 2021/09/06 15:05:13.899218 MQTT Publish
INFO: 2021/09/06 15:05:13.899298 wait.
INFO: 2021/09/06 15:05:15.040248 Topic: const.net.cn/1
INFO: 2021/09/06 15:05:15.040341 Message: Hello World

用户名密码:rw/readwrite

package main

import (
    "fmt"
    "os"
    "time"

    mqtt "github.com/eclipse/paho.mqtt.golang"
)

var onConnect mqtt.OnConnectHandler = func(client mqtt.Client) {
    Info.Printf("Client connected: %t\n", client.IsConnected())
    // 订阅主题
    if token := client.Subscribe("const.net.cn/#", 0, nil); token.Wait() && token.Error() != nil {
        fmt.Println(token.Error())
        os.Exit(1)
    }
}

var onMessage mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
    Info.Printf("Topic: %s\n", msg.Topic())
    Info.Printf("Message: %s\n", msg.Payload())
}

var onDisconnect mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
    Info.Println("Client disconnected")
}
var onReconnect mqtt.ReconnectHandler = func(c mqtt.Client, co *mqtt.ClientOptions) {
    Info.Println("Client Reconnect.")
}

func MQTT_1884_unencrypted_authenticated() {
    opts := mqtt.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1884").SetClientID("const.net.cn")

    opts.SetKeepAlive(60 * time.Second)
    // 设置消息回调处理函数
    opts.SetDefaultPublishHandler(onMessage)
    opts.SetCleanSession(true)
    opts.SetAutoReconnect(true)
    opts.SetProtocolVersion(4) //3.1.1
    opts.SetOnConnectHandler(onConnect)
    opts.SetConnectionLostHandler(onDisconnect)
    opts.SetReconnectingHandler(onReconnect)
    opts.SetUsername("rw")
    opts.SetPassword("readwrite")

    opts.SetPingTimeout(1 * time.Second)

    c := mqtt.NewClient(opts)
    if token := c.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }

    time.Sleep(5 * time.Second)
    // 发布消息
    Info.Printf("MQTT Publish")
    token := c.Publish("const.net.cn/1", 0, false, "Hello World")
    token.Wait()

    for {
        Info.Printf("wait.")
        time.Sleep(10 * time.Second)
    }
}

运行结果:
INFO: 2021/09/06 15:10:39.721974 Client connected: true
INFO: 2021/09/06 15:10:44.723829 MQTT Publish
INFO: 2021/09/06 15:10:44.724246 wait.
INFO: 2021/09/06 15:10:45.317469 Topic: const.net.cn/1
INFO: 2021/09/06 15:10:45.317498 Message: Hello World
INFO: 2021/09/06 15:10:54.725207 wait.
INFO: 2021/09/06 15:11:04.725945 wait.
INFO: 2021/09/06 15:11:14.726876 wait.
INFO: 2021/09/06 15:11:24.727531 wait.

go 编译 静态可执行文件

go build -ldflags '-s -w -extldflags "-static"'

CGO_ENABLED=1 GOOS=linux GOARCH=amd64 CC=gcc go build -ldflags '-s -w -extldflags "-static"' .