75 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
			
		
		
	
	
			75 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
| import * as msgpack from 'msgpack-lite';
 | |
| 
 | |
| class DeviceHttpDataSource {
 | |
| 
 | |
|     constructor(dataUrl, onNewData, pollInterval=1000, startIndex = 0) {
 | |
|         this.dataUrl = dataUrl;
 | |
|         this.onNewData = onNewData;
 | |
|         this.pollInterval = pollInterval;
 | |
|         this.startIndex = startIndex;
 | |
| 
 | |
|         // msgpack setup
 | |
|         this.msgpackCodec = msgpack.createCodec();
 | |
|         this.msgpackCodec.addExtUnpacker(205, function (byteArr) {
 | |
|             const buffer = byteArr.buffer.slice(byteArr.byteOffset, byteArr.byteLength + byteArr.byteOffset);
 | |
|             const result = new Int16Array(buffer);
 | |
|             return result;
 | |
|         });
 | |
| 
 | |
|         this.fetchDataHttp = this.fetchDataHttp.bind(this);
 | |
|     }
 | |
| 
 | |
|     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.addEventListener("error", evt => reject(evt));
 | |
|             req.addEventListener("abort", evt => reject(evt));
 | |
| 
 | |
|             req.send(null);
 | |
|         });
 | |
|     }
 | |
| 
 | |
|     async fetchDataHttp() {
 | |
|         try {
 | |
|             const url = this.dataUrl + "?startIdx=" + this.startIndex;
 | |
|             const arrayBuffer = await this.getUrl(url);
 | |
|             const decoded = msgpack.decode(new Uint8Array(arrayBuffer), { codec: this.msgpackCodec });
 | |
|             this.startIndex += decoded["values"].length;
 | |
|             //"values", "sessionStartTime", "startIndex"
 | |
|             this.onNewData(decoded);
 | |
|         } catch (err) {
 | |
|             //console.log(err);
 | |
|         }
 | |
|     }
 | |
| 
 | |
|     start() {
 | |
|         if (this.timer === null) {
 | |
|             this.timer = setInterval(this.fetchDataHttp, this.pollInterval);
 | |
|             return true;
 | |
|         } else {
 | |
|             return false;
 | |
|         }
 | |
|     }
 | |
| 
 | |
|     stop() {
 | |
|         if (this.timer !== null) {
 | |
|             clearInterval(this.timer);
 | |
|             this.timer = null;
 | |
|             return true;
 | |
|         } else {
 | |
|             return false;
 | |
|         }
 | |
|     }
 | |
| };
 | |
| 
 | |
| export default DeviceHttpDataSource;
 |