2020-12-21 10:46:05 +01:00
|
|
|
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";
|
2021-01-03 20:29:02 +01:00
|
|
|
import { setRecording, setText } from "./voiceSlice";
|
2020-12-21 10:46:05 +01:00
|
|
|
|
|
|
|
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) => {
|
2020-12-31 20:53:42 +01:00
|
|
|
dispatch(setData(payload.data || {}));
|
2020-12-21 10:46:05 +01:00
|
|
|
dispatch(setPlugin(payload.plugin));
|
|
|
|
if (payload.time) {
|
|
|
|
setTimeout(() => {
|
|
|
|
dispatch(setData({}));
|
|
|
|
dispatch(setPlugin(false));
|
|
|
|
}, payload.time);
|
|
|
|
}
|
|
|
|
});
|
2021-01-03 20:29:02 +01:00
|
|
|
|
|
|
|
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);
|
|
|
|
});
|
2020-12-21 10:46:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<WebSocketContext.Provider value={socket}>
|
|
|
|
{children}
|
|
|
|
</WebSocketContext.Provider>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
WebSocketProvider.propTypes = {
|
|
|
|
children: PropTypes.node
|
|
|
|
};
|
|
|
|
|
|
|
|
export default WebSocketProvider;
|