Skip to content

关于 S7-200 smart 和 S7-300 PLC 读取标签的不支持中文,需要手动转换 #786

Description

@b1163646804

我是用的版本:3.1.0
下面是我的demo ,关于“string” 类型 标签读取包含中文会出现乱码,下面是我手动转换的,希望集成到 snap7 的 read_tag 和 read_tags中,帮助中文的支持。

Demo:

from snap7 import AsyncClient, Client
from snap7.type import Areas


def main():
    with Client() as client:
        # S7-200 smart 连接配置
        client.set_connection_type(connection_type=2)
        client.connect("192.168.0.101", 0, 1)
        # 使用 read_tag 读取 FSTRING,snap7 内部用 chr() 逐字节转换,中文会乱码
        # 解决方法:将乱码字符串重新编码为 latin-1,再用 GBK 解码
        data = client.read_tag("DB1:11:FSTRING[8]")  # data 现在是乱码字符串,例如 '²âÊÔ'
        text = data.encode('latin-1').decode('gbk').rstrip()  # 重新编码为 latin-1 恢复原始字节,再用 GBK 解码
        print("VB10 字符串:", text)  #

        # S7-300
        client.connect("192.168.0.102", 0, 2)
        data = client.read_tag("DB1600:22:STRING[10]")  # hello
        text = data.encode('latin-1').decode('gbk').rstrip()
        print("DB1600.DBD22 STRING[10] 字符串:", text)


if __name__ == '__main__':
    main()

output result:

VB10 字符串= ABCD测试
DB1600.DBD22 STRING[10] 字符串= 再见

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions