Types are now bidirectional

It is still possible to define types as functions (Buffer => string for 
state topics, string => Buffer for command topics). Otherwise types have 
from and to properties.
(Fixes #101)
This commit is contained in:
uwap 2020-10-19 05:45:09 +02:00
parent 2997ff8862
commit ccd9bcd3b5
7 changed files with 64 additions and 38 deletions

View file

@ -124,8 +124,8 @@ class App extends React.PureComponent<AppProps & Classes, AppState> {
for (let i in topics) {
const topic = topics[i];
const stateTopic = this.topics[topic].state;
const parseVal = stateTopic ? stateTopic.type : null;
const val = parseVal == null ? message.toString() : parseVal(message);
const typeConversion = stateTopic?.type?.from ?? stateTopic?.type;
const val = (typeConversion ?? ((x) => x.toString()))(message);
this.setMqttStateDebounced(
{mqttState: Object.assign({},
merge(this.state.mqttState, { [topic]: val}))});
@ -145,16 +145,16 @@ class App extends React.PureComponent<AppProps & Classes, AppState> {
this.setState({drawerOpened: false});
}
changeState = (topic: string, value: string) => {
changeState = (topic: string, val: string) => {
try {
if (this.topics[topic].command == null) {
const commandTopic = this.topics[topic].command;
if (commandTopic == null) {
return;
}
const rawTopic = this.topics[topic].command.name;
const transformValue = this.topics[topic].command.type;
const val =
transformValue == null ? value : transformValue(Buffer.from(value));
this.state.mqttSend(rawTopic, Buffer.from(val));
const rawTopic = commandTopic.name;
const typeConversion = commandTopic.type?.to ?? commandTopic.type;
const value = (typeConversion ?? Buffer.from)(val);
this.state.mqttSend(rawTopic, value);
} catch (err) {
this.setState({ error: err.toString() });
}