OSD-Frontend/src/WebSocket.js

58 lines
1.3 KiB
JavaScript

import React, { createContext } from "react";
import PropTypes from "prop-types";
import io from "socket.io-client";
import { WS_BASE } from "./config";
import { useDispatch } from "react-redux";
import { setData, setPlugin } from "./coreSlice";
import { setRecording, setText } from "./voiceSlice";
const WebSocketContext = createContext(null);
export { WebSocketContext };
function WebSocketProvider({ children }) {
let socket;
const dispatch = useDispatch();
if (!socket) {
socket = io.connect(WS_BASE);
socket.on("switchPlugin", (payload) => {
dispatch(setData(payload.data || {}));
dispatch(setPlugin(payload.plugin));
if (payload.time) {
setTimeout(() => {
dispatch(setData({}));
dispatch(setPlugin(false));
}, payload.time);
}
});
socket.on("voice:wakeword", () => {
dispatch(setRecording(true));
dispatch(setText(null));
});
socket.on("voice:record_end", () => {
dispatch(setRecording(false));
dispatch(setText(null));
});
socket.on("voice:utterance", payload => {
dispatch(setRecording(false));
dispatch(setText(payload.text));
setTimeout(() => dispatch(setText(null)), 3000);
});
}
return (
<WebSocketContext.Provider value={socket}>
{children}
</WebSocketContext.Provider>
);
}
WebSocketProvider.propTypes = {
children: PropTypes.node
};
export default WebSocketProvider;