swimtracker-app/components/DeviceHttpDataSource.js

83 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-05-17 15:57:26 +02:00
import React from 'react';
import PropTypes from 'prop-types';
2020-06-02 17:19:09 +02:00
import * as msgpack from 'msgpack-lite';
2020-05-17 15:57:26 +02:00
class DeviceHttpDataSource extends React.Component {
constructor(props) {
super(props);
this.data = [];
2020-06-02 17:19:09 +02:00
this.dataUrl = this.props.deviceUrl + "/api/session/data";
2020-05-17 15:57:26 +02:00
// msgpack setup
2020-06-02 17:19:09 +02:00
this.msgpackCodec = msgpack.createCodec();
this.msgpackCodec.addExtUnpacker(205, function (byteArr) {
2020-05-17 15:57:26 +02:00
const buffer = byteArr.buffer.slice(byteArr.byteOffset, byteArr.byteLength + byteArr.byteOffset);
2020-06-02 17:19:09 +02:00
const result = new Int16Array(buffer);
return result;
2020-05-17 15:57:26 +02:00
});
this.fetchDataHttp = this.fetchDataHttp.bind(this);
}
2020-06-02 17:19:09 +02:00
getUrl(url) {
return new Promise((accept, reject) => {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.onload = function (event) {
var resp = req.response;
if (resp) {
accept(resp);
}
};
req.send(null);
});
//todo reject on error
}
2020-05-17 15:57:26 +02:00
async fetchDataHttp() {
2020-06-02 17:19:09 +02:00
try {
const url = this.dataUrl + "?startIdx=" + this.data.length;
const arrayBuffer = await this.getUrl(url);
const decoded = msgpack.decode(new Uint8Array(arrayBuffer), { codec: this.msgpackCodec });
const typedValueArr = decoded['values'];
const newDataStart = this.data.length;
for (let i = 0; i < typedValueArr.length; ++i) {
this.data.push(typedValueArr[i]);
}
this.props.onNewData(this.data, newDataStart);
} catch (err) {
//console.log(err);
2020-05-17 15:57:26 +02:00
}
}
componentDidMount() {
this.timer = setInterval(this.fetchDataHttp, this.props.pollInterval);
}
componentWillUnmount() {
clearInterval(this.timer);
this.timer = null;
}
render() {
2020-06-02 17:19:09 +02:00
return null;
2020-05-17 15:57:26 +02:00
}
}
DeviceHttpDataSource.propTypes = {
deviceUrl: PropTypes.string.isRequired,
onNewData: PropTypes.func.isRequired,
pollInterval: PropTypes.number // poll interval in ms
};
DeviceHttpDataSource.defaultProps = {
pollInterval: 20000
};
export default DeviceHttpDataSource;