Ruby-Serialport:监听输入
我计划很快开始围绕串行设备的输入进行编码,并且很高兴找到 Ruby-serialport。该 API 看起来很容易使用,但我对如何采用基于事件的方法接收数据有点困惑。
我想在出现 \n
时对数据执行某些操作,但库中当前的 read() 似乎只是转储屏幕上的任何内容。我真正寻找的是一种在新数据进入时触发函数的方法。
I'm planning on moving into coding around the input from serial devices soon and was quite happy to find Ruby-serialport. The API looks easy to use, but I'm a bit confused on how to take an event-based approach towards receiving data.
I want to do something on data whenever a \n
appears, but the current read() in the library appears to just dump whatever is on the screen. What I'm really looking for is a way to tigger a function it when new data comes in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 和操作系统已经为您处理串行 I/O 的事件驱动部分。
gem 实现的
SerialPort
类是IO
的子类,因此它已经可以处理读取换行符...如下所示:Ruby and the OS already handle the event-driven part of serial I/O for you.
The
SerialPort
class implemented by your gem is a child ofIO
, so it will already handle reading up to newlines...something like this:我认为您需要在应用程序中创建另一个线程来侦听数据。
然后你应该处理传入的数据 - 放入某种数组中。
使用观察者设计模式来跟踪数据数组的状态 - 然后您将拥有您的功能 - 请记住 ruby 不是事件驱动语言。
I think that you need to create another thread in your application listening to data.
Then you should handle incoming data - put into some kind of array.
Use Observer design pattern to track state of the array with data - then you will have your functionality - remember that ruby isn't event driven language.