分类 Demo 下的文章

“各种示例”

本示例用在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
}

打印文件的十六进制数据用hexdump就可以了。也可以使用xxd.

示例:

hexdump -C certs/accert/ac.oer 

00000000 80 03 00 83 08 c7 95 5d 5e b0 fb 26 29 50 80 00 |.......]^..&)P..|
00000010 00 51 55 74 42 7f 2b 52 98 fe 6c 71 44 ba 00 0a |.QUtB.+R..lqD...|
00000020 21 0b b1 40 84 00 a9 83 01 01 80 00 9c 01 02 00 |!..@............|
00000030 01 6f 00 01 70 80 84 21 83 52 53 01 bc c2 2f 17 |.o..p..!.RS.../.|
00000040 d9 10 60 5a 03 32 3a e9 d4 eb 72 d7 f5 c1 15 bd |..`Z.2:...r.....|
00000050 99 84 a2 c2 27 a9 21 8e c0 84 40 ba 8d b1 6c 92 |....'.!...@...l.|
00000060 c6 41 b4 24 44 0d be ae 2e d4 4f 22 47 af 1b c2 |.A.$D.....O"G...|
00000070 bb 58 8b a2 db e8 b5 c7 03 20 b5 aa 15 22 53 83 |.X....... ..."S.|
00000080 73 22 7c f2 13 68 c9 2b 1f b5 22 37 f5 2e 30 81 |s"|..h.+.."7..0.|
00000090 55 a0 74 b1 38 d8 8b e2 f7 f4 d7 |U.t.8......|

xxd -p -u certs/accert/ac.oer 

8003008308C7955D5EB0FB262950800000515574427F2B5298FE6C7144BA
000A210BB1408400A983010180009C010200016F00017080842183525301
BCC22F17D910605A03323AE9D4EB72D7F5C115BD9984A2C227A9218EC084
40BA8DB16C92C641B424440DBEAE2ED44F2247AF1BC2BB588BA2DBE8B5C7
0320B5AA1522538373227CF21368C92B1FB52237F52E308155A074B138D8
8BE2F7F4D7

xxd -p -u -i certs/accert/ac.oer 

unsigned char certs_accert_ac_oer[] = {
0X80, 0X03, 0X00, 0X83, 0X08, 0XC7, 0X95, 0X5D, 0X5E, 0XB0, 0XFB, 0X26,
0X29, 0X50, 0X80, 0X00, 0X00, 0X51, 0X55, 0X74, 0X42, 0X7F, 0X2B, 0X52,
0X98, 0XFE, 0X6C, 0X71, 0X44, 0XBA, 0X00, 0X0A, 0X21, 0X0B, 0XB1, 0X40,
0X84, 0X00, 0XA9, 0X83, 0X01, 0X01, 0X80, 0X00, 0X9C, 0X01, 0X02, 0X00,
0X01, 0X6F, 0X00, 0X01, 0X70, 0X80, 0X84, 0X21, 0X83, 0X52, 0X53, 0X01,
0XBC, 0XC2, 0X2F, 0X17, 0XD9, 0X10, 0X60, 0X5A, 0X03, 0X32, 0X3A, 0XE9,
0XD4, 0XEB, 0X72, 0XD7, 0XF5, 0XC1, 0X15, 0XBD, 0X99, 0X84, 0XA2, 0XC2,
0X27, 0XA9, 0X21, 0X8E, 0XC0, 0X84, 0X40, 0XBA, 0X8D, 0XB1, 0X6C, 0X92,
0XC6, 0X41, 0XB4, 0X24, 0X44, 0X0D, 0XBE, 0XAE, 0X2E, 0XD4, 0X4F, 0X22,
0X47, 0XAF, 0X1B, 0XC2, 0XBB, 0X58, 0X8B, 0XA2, 0XDB, 0XE8, 0XB5, 0XC7,
0X03, 0X20, 0XB5, 0XAA, 0X15, 0X22, 0X53, 0X83, 0X73, 0X22, 0X7C, 0XF2,
0X13, 0X68, 0XC9, 0X2B, 0X1F, 0XB5, 0X22, 0X37, 0XF5, 0X2E, 0X30, 0X81,
0X55, 0XA0, 0X74, 0XB1, 0X38, 0XD8, 0X8B, 0XE2, 0XF7, 0XF4, 0XD7
};
unsigned int certs_accert_ac_oer_len = 155;

readlink 用于读取本进程的程序名 
eadlink()会将参数path的符号链接内容存储到参数buf所指的内存空间
头文件: #include <unistd.h>
定义函数:ssize_t  readlink(const  char path,  char buf, size_t  bufsiz);

readlink("/proc/self/exe", exepath, sizeof(exepath));
此技巧可以读取本进程的程序名。
示例:

#define MAX_PATH_LEN 256
string get_process_path()
{
    char process_path[MAX_PATH_LEN]={0};
    int n = 0;
    string strret = "";

    memset(process_path, 0x00, MAX_PATH_LEN);
    n = readlink("/proc/self/exe", process_path, MAX_PATH_LEN);
    if (n != -1)
    {        
        strret.append(process_path, n);
    }
    else
    {
        return strret;
    }
    return strret;
}

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.