如何使用RxJS从arrayBuffer拆分数据帧? [英] How to split a data frame from an arrayBuffer with RxJS?

查看:245
本文介绍了如何使用RxJS从arrayBuffer拆分数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用websocket从硬件接收数据帧. 数据帧的定义如下:

I'm using websocket to receive data frame from hardware. The data frame is defined like this:

0xbb(head) ---data--- 0xee(tail)

接收到的数据存储在Uint8Array中,可能有多个帧:

the received data is store in Uint8Array, there maybe multiple frame:

var buffer = new Uint8Array([0xbb,0,0,0,0xee,0xbb,1,1,1,0xee,0xbb,3,3,3,0xee]);

我可以将数组转换为可观察的:

and I can convert the array to observable:

var obs= Rx.Observable.from(buffer);

RxMarbles:

RxMarbles:

--0xbb--0--0--0--0xee--0xbb--1--1--1--0xee--0xbb--2--2--2--0xee------
------------------000------------------111------------------222------

如何使用RxJS拆分可观察对象? 使用哪个运算符? RxJS是这种情况下的最佳实践吗?

How to use RxJS to split the observable? Which operators to use? Is RxJS the best practice for this situation?

推荐答案

const source = Rx.Observable
  .from(['0xbb','0','0','0','0xee','0xbb','1','1','1','0xee','0xbb','3','3','3','0xee'])
  .concatMap(i => Rx.Observable.of(i).delay(1));

source
  .filter(i => i != '0xee' && i != '0xbb')
  .buffer(source.filter(i => i === '0xee'))
  .subscribe(val => console.log(val));

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.js"></script>

我们需要使用concatMap(.. delay(1))将值转换为异步,因为否则,closingNotifier缓冲区的运行速度快于摄取值,最终您将得到三个空数组.但是,由于您从网络套接字收到了这些数据包,因此您已经不同步了.

We need to convert the values to async by using concatMap(.. delay(1)) because otherwise the closingNotifier of buffer is running faster then the ingestion of values and you end up with three empty array's. But since you receive these packets from a websocket you are already async.

此代码不是100%可靠的,例如,当外部设备不发出0xee时会发生什么?我们最终将下一条消息与上一条消息串联起来.

This code is not 100% foolproof, for instance what should happen when the external device does not emit 0xee? We end up with the next message being concatenated to the previous message.

这篇关于如何使用RxJS从arrayBuffer拆分数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆