go语言连接plc

Go使用gos7实现西门子PLC通讯-CSDN博客

先创建一个文件夹,用以收纳我们的项目文件。然后输入以下命令,创建go.mod文件。

go mod init 项目名称

然后输入以下指令,自动安装gos7。

go get github.com/robinson/gos7

报错 :go: module github.com/robinson/gos7: Get "https://proxy.golang.org/github.com/robinson/
gos7/@v/list": dial tcp 142.251.42.241:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

 原因:

项目里面初始化了 go mod 你再在工程目录下面使用 go get 拉包会自动使用 go mod 拉包,并整理到 go.mod 文件里面。

但是默认他使用的源是国外的,所以安装依赖包一般都很慢,或者不能成功。

所以我们需要设置下他们的代理,让他们从国内的服务器出去,这样速度和稳定性都能更好些。

解决方法:七牛云 - Goproxy.cn

打开你的终端并执行

$ go env -w GO111MODULE=on
$ go env -w GOPROXY=https://goproxy.cn,direct

完成。

完整代码:

package main
 
import (
	"fmt"
	"time"
 
	"github.com/robinson/gos7"
)
 
type PlcData struct {
	boolValue    bool
	intValue     uint16
	realValue    float32
	stringValue  string
	wstringValue string
}
 
func main() {
		const (
		ipAddr = "192.168.10.230" //PLC IP
		rack   = 0                // PLC机架号
		slot   = 1                // PLC插槽号
	)
 
	//PLC tcp连接客户端
	handler := gos7.NewTCPClientHandler(ipAddr, rack, slot)
	//连接及读取超时
	handler.Timeout = 200 * time.Second
	//关闭连接超时
	handler.IdleTimeout = 200 * time.Second
	//打开连接
	handler.Connect()
	//函数退出时关闭连接
	defer handler.Close()
 
	//获取PLC对象
	client := gos7.NewClient(handler)
 
	//DB号
	address := 10
	//起始地址
	start := 0
	//读取字节数
	size := 776
	//读写字节缓存区
	buffer := make([]byte, size)
 
	//读取字节
	client.AGReadDB(address, start, size, buffer)
 
	//gos7解析数据类
	var helper gos7.Helper
 
	//gos7内置方法解析数据
	var data PlcData
	data.boolValue = helper.GetBoolAt(buffer[0], 0)
	helper.GetValueAt(buffer[2:4], 0, &data.intValue)
	data.realValue = helper.GetRealAt(buffer[4:8], 0)
	data.stringValue = helper.GetStringAt(buffer[8:264], 0)
	data.wstringValue = helper.GetWStringAt(buffer[264:], 0)
 
	//输出数据
	fmt.Println(data)
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值