ruby 中的数据包创建
我正在尝试创建一个数据包以使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您坚持使用字符串来表示二进制数据,那么您真的会遇到麻烦。您真正需要的是
pack
:这使得构造和解构任意二进制数据变得非常容易。该方法不仅支持无符号字符,还支持各种其他常用类型。
您甚至可能想构建自己的方法来读取和写入:
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
: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:
试试这个:
Try this: