ruby 中的数据包创建

发布于 2024-11-29 02:48:28 字数 825 浏览 1 评论 0原文

我正在尝试创建一个数据包以使用 ruby​​-serialport 通过串行发送。这看起来应该很简单,当我只写一个字符串时它就可以工作:

packet = "\xFF\x03\x10\x01\x01\xFE"
sp.write(packet)
=>hardware does what it's supposed to, opens the door represented by the 4th hex value

但我显然需要以编程方式完成它,而且我无法找出正确的方法。以下是我尝试过的一些事情:

door = 1    
packet = "\xFF\x03\x10" + door.to_s(16) + "\x01\xFE"
sp.write(packet)
=> can't convert fixnum into string

door = 1
packet = "\xFF\x03\x10" + door.to_a.pack('H*') + "\x01\xFE"
sp.write(packet)
=> to_a will be obsolete
can't convert fixnum into string

任何人都

door = 1
sp.write("\xFF\x03\x10")
sp.write(door)
sp.write("\x01\xFE")
=>no response from hardware

可以帮助我了解如何将数字正确转换为串行端口的正确十六进制表示法并连接到其他十六进制字符串吗?提前致谢!

I'm trying to create a packet to send over serial using ruby-serialport. This seems like it should be simple, and it works when I just write a string:

packet = "\xFF\x03\x10\x01\x01\xFE"
sp.write(packet)
=>hardware does what it's supposed to, opens the door represented by the 4th hex value

but I obviously need to do it programmatically, and I can't figure out the right way. Here are just a few of the things I've tried:

door = 1    
packet = "\xFF\x03\x10" + door.to_s(16) + "\x01\xFE"
sp.write(packet)
=> can't convert fixnum into string

and

door = 1
packet = "\xFF\x03\x10" + door.to_a.pack('H*') + "\x01\xFE"
sp.write(packet)
=> to_a will be obsolete
can't convert fixnum into string

and

door = 1
sp.write("\xFF\x03\x10")
sp.write(door)
sp.write("\x01\xFE")
=>no response from hardware

Can anyone help me out on how to properly convert a number into the right hex notation for serialport and joining to the other hex strings? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

口干舌燥 2024-12-06 02:48:28

如果您坚持使用字符串来表示二进制数据,那么您真的会遇到麻烦。您真正需要的是 pack

packet = [ 0xFF, 0x30, 0x10, door, 0x01, 0xFE ].pack('C*')

这使得构造和解构任意二进制数据变得非常容易。该方法不仅支持无符号字符,还支持各种其他常用类型。

您甚至可能想构建自己的方法来读取和写入:

def write_packet(*bytes)
  sp.write(bytes.flatten.pack('C*'))
end

You're really going to get into trouble if you insist on using strings to represent otherwise binary data. What you really need is pack:

packet = [ 0xFF, 0x30, 0x10, door, 0x01, 0xFE ].pack('C*')

This makes it very easy to construct and deconstruct arbitrary binary data. The method supports not just unsigned characters but a variety of other types that are commonly used.

You may even want to construct your own method to read and write this:

def write_packet(*bytes)
  sp.write(bytes.flatten.pack('C*'))
end
一抹微笑 2024-12-06 02:48:28

试试这个:

door = 1    
packet = "\xFF\x03\x10" + door.chr + "\x01\xFE"

Try this:

door = 1    
packet = "\xFF\x03\x10" + door.chr + "\x01\xFE"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文