mirror of
https://github.com/thomasnordquist/MQTT-Explorer.git
synced 2026-09-11 17:13:53 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28b99f5774 | ||
|
|
42565c8bdc | ||
|
|
8b43e20f2e | ||
|
|
a2a75588c9 | ||
|
|
c13b60cd18 | ||
|
|
18f8da9054 | ||
|
|
f6856d66cc | ||
|
|
79fbd34cfa | ||
|
|
3bc23e6d74 | ||
|
|
e9a56ac48d | ||
|
|
b4bdd01808 | ||
|
|
4406bf5de4 | ||
|
|
ae0ce79e26 | ||
|
|
bbe2ae3f29 | ||
|
|
a2c4388c78 | ||
|
|
c88978f0dd | ||
|
|
b3a37e4794 | ||
|
|
1ecb53b397 | ||
|
|
97fedcba08 | ||
|
|
1f23c65484 | ||
|
|
980072f680 | ||
|
|
10aae59c92 | ||
|
|
f4bda3e242 | ||
|
|
626b9cab7d | ||
|
|
567f6d2d50 |
+5
-5
@@ -80,14 +80,14 @@
|
||||
"node-loader": "^0.6.0",
|
||||
"source-map-loader": "^0.2.4",
|
||||
"style-loader": "^1",
|
||||
"ts-loader": "^9.2.6",
|
||||
"ts-loader": "^9.5.1",
|
||||
"typescript": "^4.5.5",
|
||||
"webpack": "^5.69.1",
|
||||
"webpack": "^5.91.0",
|
||||
"webpack-bundle-analyzer": "^4.5.0",
|
||||
"webpack-cli": "^4.9.2",
|
||||
"webpack-dev-server": "^4.7.4"
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^5.0.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"electron": "^29"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Action, ActionTypes } from '../reducers/Publish'
|
||||
import { AppState } from '../reducers'
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
import { Dispatch } from 'redux'
|
||||
import { makePublishEvent, rendererEvents } from '../../../events'
|
||||
import { MqttMessage, makePublishEvent, rendererEvents } from '../../../events'
|
||||
|
||||
export const setTopic = (topic?: string): Action => {
|
||||
return {
|
||||
@@ -41,7 +41,7 @@ export const publish = (connectionId: string) => (dispatch: Dispatch<Action>, ge
|
||||
}
|
||||
|
||||
const publishEvent = makePublishEvent(connectionId)
|
||||
const mqttMessage = {
|
||||
const mqttMessage: Partial<MqttMessage> = {
|
||||
topic,
|
||||
payload: state.publish.payload ? Base64Message.fromString(state.publish.payload) : null,
|
||||
retain: state.publish.retain,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as q from '../../../backend/src/Model'
|
||||
import { ActionTypes, SettingsStateModel, TopicOrder } from '../reducers/Settings'
|
||||
import { ActionTypes, SettingsStateModel, TopicOrder, ValueRendererDisplayMode } from '../reducers/Settings'
|
||||
import { AppState } from '../reducers'
|
||||
import { autoExpandLimitSet } from '../components/SettingsDrawer/Settings'
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
@@ -68,13 +68,14 @@ export const selectTopicWithMouseOver = (doSelect: boolean) => (dispatch: Dispat
|
||||
dispatch(storeSettings())
|
||||
}
|
||||
|
||||
export const setValueDisplayMode = (valueRendererDisplayMode: 'diff' | 'raw') => (dispatch: Dispatch<any>) => {
|
||||
dispatch({
|
||||
valueRendererDisplayMode,
|
||||
type: ActionTypes.SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE,
|
||||
})
|
||||
dispatch(storeSettings())
|
||||
}
|
||||
export const setValueDisplayMode =
|
||||
(valueRendererDisplayMode: ValueRendererDisplayMode) => (dispatch: Dispatch<any>) => {
|
||||
dispatch({
|
||||
valueRendererDisplayMode,
|
||||
type: ActionTypes.SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE,
|
||||
})
|
||||
dispatch(storeSettings())
|
||||
}
|
||||
|
||||
export const toggleHighlightTopicUpdates = () => (dispatch: Dispatch<any>) => {
|
||||
dispatch({
|
||||
@@ -117,7 +118,7 @@ export const filterTopics = (filterStr: string) => (dispatch: Dispatch<any>, get
|
||||
const messageMatches =
|
||||
node.message &&
|
||||
node.message.payload &&
|
||||
Base64Message.toUnicodeString(node.message.payload).toLowerCase().indexOf(filterStr) !== -1
|
||||
node.message.payload.toUnicodeString().toLowerCase().indexOf(filterStr) !== -1
|
||||
|
||||
return Boolean(messageMatches)
|
||||
}
|
||||
|
||||
@@ -33,13 +33,8 @@ const debouncedSelectTopic = debounce(
|
||||
setTopicDispatch = setTopic(topic.path())
|
||||
}
|
||||
|
||||
if (previouslySelectedTopic && previouslySelectedTopic.viewModel) {
|
||||
previouslySelectedTopic.viewModel.setSelected(false)
|
||||
}
|
||||
|
||||
if (topic.viewModel) {
|
||||
topic.viewModel.setSelected(true)
|
||||
}
|
||||
previouslySelectedTopic?.viewModel?.setSelected(false)
|
||||
topic.viewModel?.setSelected(true)
|
||||
|
||||
const selectTreeTopicDispatch = {
|
||||
selectedTopic: topic,
|
||||
|
||||
@@ -114,6 +114,7 @@ function TopicChart(props: Props) {
|
||||
</div>
|
||||
</div>
|
||||
<TopicPlot
|
||||
node={props.treeNode ? props.treeNode : undefined}
|
||||
color={props.parameters.color}
|
||||
interpolation={props.parameters.interpolation}
|
||||
timeInterval={props.parameters.timeRange ? props.parameters.timeRange.until : undefined}
|
||||
|
||||
@@ -1,26 +1,40 @@
|
||||
import React from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { connect } from 'react-redux'
|
||||
import { ListItem, Typography } from '@material-ui/core'
|
||||
import { toMqttConnection, ConnectionOptions } from '../../../model/ConnectionOptions'
|
||||
import { withStyles, Theme } from '@material-ui/core/styles'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connectionManagerActions } from '../../../actions'
|
||||
import { connectionActions, connectionManagerActions } from '../../../actions'
|
||||
|
||||
export interface Props {
|
||||
connection: ConnectionOptions
|
||||
actions: any
|
||||
actions: {
|
||||
connection: any
|
||||
connectionManager: any
|
||||
}
|
||||
selected: boolean
|
||||
classes: any
|
||||
}
|
||||
|
||||
const ConnectionItem = (props: Props) => {
|
||||
const connect = useCallback(() => {
|
||||
const mqttOptions = toMqttConnection(props.connection)
|
||||
if (mqttOptions) {
|
||||
props.actions.connection.connect(mqttOptions, props.connection.id)
|
||||
}
|
||||
}, [props.connection, props])
|
||||
|
||||
const connection = props.connection.host && toMqttConnection(props.connection)
|
||||
return (
|
||||
<ListItem
|
||||
button={true}
|
||||
selected={props.selected}
|
||||
style={{ display: 'block' }}
|
||||
onClick={() => props.actions.selectConnection(props.connection.id)}
|
||||
onClick={() => props.actions.connectionManager.selectConnection(props.connection.id)}
|
||||
onDoubleClick={() => {
|
||||
props.actions.connectionManager.selectConnection(props.connection.id)
|
||||
connect()
|
||||
}}
|
||||
>
|
||||
<Typography className={props.classes.name}>{props.connection.name || 'mqtt broker'}</Typography>
|
||||
<Typography className={props.classes.details}>{connection && connection.url}</Typography>
|
||||
@@ -30,10 +44,12 @@ const ConnectionItem = (props: Props) => {
|
||||
|
||||
export const mapDispatchToProps = (dispatch: any) => {
|
||||
return {
|
||||
actions: bindActionCreators(connectionManagerActions, dispatch),
|
||||
actions: {
|
||||
connection: bindActionCreators(connectionActions, dispatch),
|
||||
connectionManager: bindActionCreators(connectionManagerActions, dispatch),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const connectionItemStyle = (theme: Theme) => ({
|
||||
name: {
|
||||
width: '100%',
|
||||
|
||||
@@ -7,7 +7,7 @@ import { connect } from 'react-redux'
|
||||
import { connectionManagerActions } from '../../../actions'
|
||||
import { ConnectionOptions } from '../../../model/ConnectionOptions'
|
||||
import { KeyCodes } from '../../../utils/KeyCodes'
|
||||
import { List, ListSubheader } from '@material-ui/core'
|
||||
import { List } from '@material-ui/core'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { useGlobalKeyEventHandler } from '../../../effects/useGlobalKeyEventHandler'
|
||||
|
||||
|
||||
@@ -123,7 +123,7 @@ function renderStat(tree: q.Tree<TopicViewModel>, stat: Stats) {
|
||||
return null
|
||||
}
|
||||
|
||||
const str = node.message.payload ? Base64Message.toUnicodeString(node.message.payload) : ''
|
||||
const str = node.message.payload ? node.message.payload.toUnicodeString() : ''
|
||||
let value = node.message && node.message.payload ? parseFloat(str) : NaN
|
||||
value = !isNaN(value) ? abbreviate(value) : str
|
||||
|
||||
|
||||
@@ -52,16 +52,16 @@ function ChartPreview(props: Props) {
|
||||
/>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip title="Add to chart panel, not enough data for preview">
|
||||
<ShowChart
|
||||
onClick={onClick}
|
||||
className={props.classes.icon}
|
||||
style={{ color: '#aaa' }}
|
||||
data-test-type="ShowChart"
|
||||
data-test={props.literal.path}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
<Tooltip title="Add to chart panel, not enough data for preview">
|
||||
<ShowChart
|
||||
onClick={onClick}
|
||||
className={props.classes.icon}
|
||||
style={{ color: '#aaa' }}
|
||||
data-test-type="ShowChart"
|
||||
data-test={props.literal.path}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
|
||||
return (
|
||||
<span>
|
||||
@@ -69,7 +69,7 @@ function ChartPreview(props: Props) {
|
||||
<Popper open={open} anchorEl={chartIconRef.current} placement="left-end">
|
||||
<Fade in={open} timeout={300}>
|
||||
<Paper style={{ width: '300px' }}>
|
||||
{open ? <TopicPlot history={props.treeNode.messageHistory} dotPath={props.literal.path} /> : <span />}
|
||||
{open ? <TopicPlot node={props.treeNode} history={props.treeNode.messageHistory} dotPath={props.literal.path} /> : <span />}
|
||||
</Paper>
|
||||
</Fade>
|
||||
</Popper>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import * as q from '../../../../backend/src/Model'
|
||||
import React, { useState, useEffect, useCallback } from 'react'
|
||||
import ExpandMore from '@material-ui/icons/ExpandMore'
|
||||
import NodeStats from './NodeStats'
|
||||
import ValuePanel from './ValueRenderer/ValuePanel'
|
||||
import { AppState } from '../../reducers'
|
||||
import { Badge, ExpansionPanel, ExpansionPanelDetails, ExpansionPanelSummary, Typography } from '@material-ui/core'
|
||||
import { ExpansionPanelDetails } from '@material-ui/core'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { settingsActions, sidebarActions } from '../../actions'
|
||||
@@ -28,7 +27,7 @@ interface Props {
|
||||
}
|
||||
|
||||
function useUpdateNodeWhenNodeReceivesUpdates(node?: q.TreeNode<any>) {
|
||||
const [lastUpdate, setLastUpdate] = useState(0)
|
||||
const [, setLastUpdate] = useState(0)
|
||||
const updateNode = useCallback(
|
||||
throttle(() => {
|
||||
setLastUpdate(node ? node.lastUpdate : 0)
|
||||
@@ -52,7 +51,6 @@ function Sidebar(props: Props) {
|
||||
const { classes, tree, nodePath } = props
|
||||
const node = usePollingToFetchTreeNode(tree, nodePath || '')
|
||||
useUpdateNodeWhenNodeReceivesUpdates(node)
|
||||
// console.log(node && node.path(), tree, nodePath)
|
||||
|
||||
return (
|
||||
<div id="Sidebar" className={classes.drawer}>
|
||||
|
||||
@@ -6,19 +6,19 @@ import Topic from './Topic'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { RecursiveTopicDeleteButton } from './RecursiveTopicDeleteButton'
|
||||
import { sidebarActions } from '../../../actions'
|
||||
import { TopicDeleteButton } from './TopicDeleteButton'
|
||||
import { TopicTypeButton } from './TopicTypeButton'
|
||||
import { sidebarActions } from '../../../actions'
|
||||
|
||||
const TopicPanel = (props: { node?: q.TreeNode<any>; actions: typeof sidebarActions }) => {
|
||||
const { node } = props
|
||||
console.log(node && node.path())
|
||||
|
||||
const copyTopic = node ? <Copy value={node.path()} /> : null
|
||||
|
||||
const deleteTopic = useCallback((topic?: q.TreeNode<any>, recursive: boolean = false) => {
|
||||
if (!topic) {
|
||||
return
|
||||
}
|
||||
|
||||
props.actions.clearTopic(topic, recursive)
|
||||
}, [])
|
||||
|
||||
@@ -29,11 +29,12 @@ const TopicPanel = (props: { node?: q.TreeNode<any>; actions: typeof sidebarActi
|
||||
Topic {copyTopic}
|
||||
<TopicDeleteButton node={node} deleteTopicAction={deleteTopic} />
|
||||
<RecursiveTopicDeleteButton node={node} deleteTopicAction={deleteTopic} />
|
||||
<TopicTypeButton node={node} />
|
||||
</span>
|
||||
<Topic node={node} />
|
||||
</Panel>
|
||||
),
|
||||
[node, node && node.childTopicCount()]
|
||||
[node, node?.childTopicCount()]
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import React, { useCallback, useMemo } from 'react'
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import ClickAwayListener from '@material-ui/core/ClickAwayListener'
|
||||
import Grow from '@material-ui/core/Grow'
|
||||
import Button from '@material-ui/core/Button'
|
||||
import Paper from '@material-ui/core/Paper'
|
||||
import Popper from '@material-ui/core/Popper'
|
||||
import MenuItem from '@material-ui/core/MenuItem'
|
||||
import MenuList from '@material-ui/core/MenuList'
|
||||
import WarningRounded from '@material-ui/icons/WarningRounded'
|
||||
import { MessageDecoder, decoders } from '../../../decoders'
|
||||
import { Tooltip } from '@material-ui/core'
|
||||
|
||||
export const TopicTypeButton = (props: { node?: q.TreeNode<any> }) => {
|
||||
const { node } = props
|
||||
if (!node || !node.message || !node.message.payload) {
|
||||
return null
|
||||
}
|
||||
|
||||
const options = decoders.flatMap(decoder => decoder.formats.map(format => [decoder, format] as const))
|
||||
|
||||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
|
||||
const selectOption = useCallback(
|
||||
(decoder: MessageDecoder, format: string) => {
|
||||
if (!node) {
|
||||
return
|
||||
}
|
||||
|
||||
node.viewModel.decoder = { decoder, format }
|
||||
setOpen(false)
|
||||
},
|
||||
[node]
|
||||
)
|
||||
|
||||
const handleToggle = useCallback(
|
||||
(event: React.MouseEvent<HTMLElement>) => {
|
||||
event.stopPropagation()
|
||||
if (open === true) {
|
||||
return
|
||||
}
|
||||
setAnchorEl(event.currentTarget)
|
||||
setOpen(prevOpen => !prevOpen)
|
||||
},
|
||||
[open]
|
||||
)
|
||||
|
||||
const handleClose = useCallback((event: React.MouseEvent<Document, MouseEvent>) => {
|
||||
if (anchorEl && anchorEl.contains(event.target as HTMLElement)) {
|
||||
return
|
||||
}
|
||||
setOpen(false)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Button onClick={handleToggle}>
|
||||
{props.node?.viewModel.decoder?.format ?? props.node?.type}
|
||||
<Popper open={open} anchorEl={anchorEl} role={undefined} transition>
|
||||
{({ TransitionProps, placement }) => (
|
||||
<Grow
|
||||
{...TransitionProps}
|
||||
style={{
|
||||
transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom',
|
||||
}}
|
||||
>
|
||||
<Paper>
|
||||
<ClickAwayListener onClickAway={handleClose}>
|
||||
<MenuList id="topicTypeMode">
|
||||
{options.map(([decoder, format], index) => (
|
||||
<MenuItem
|
||||
key={format}
|
||||
selected={node && format === node.type}
|
||||
onClick={() => selectOption(decoder, format)}
|
||||
>
|
||||
<DecoderStatus decoder={decoder} format={format} node={node} />
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuList>
|
||||
</ClickAwayListener>
|
||||
</Paper>
|
||||
</Grow>
|
||||
)}
|
||||
</Popper>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function DecoderStatus({ node, decoder, format }: { node: q.TreeNode<any>; decoder: MessageDecoder; format: string }) {
|
||||
const decoded = useMemo(() => {
|
||||
return node.message?.payload && decoder.decode(node.message?.payload, format)
|
||||
}, [node.message, decoder, format])
|
||||
|
||||
return decoded?.error ? (
|
||||
<Tooltip title={decoded.error}>
|
||||
<div>
|
||||
{format} <WarningRounded />
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<>{format}</>
|
||||
)
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import Copy from '../../helper/Copy'
|
||||
import DateFormatter from '../../helper/DateFormatter'
|
||||
import History from '../HistoryDrawer'
|
||||
import TopicPlot from '../../TopicPlot'
|
||||
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
|
||||
import { isPlottable } from '../CodeDiff/util'
|
||||
import { TopicViewModel } from '../../../model/TopicViewModel'
|
||||
import { bindActionCreators } from 'redux'
|
||||
@@ -13,6 +12,8 @@ import { chartActions } from '../../../actions'
|
||||
import { connect } from 'react-redux'
|
||||
import CustomIconButton from '../../helper/CustomIconButton'
|
||||
import { MessageId } from '../MessageId'
|
||||
import { useSubscription } from '../../hooks/useSubscription'
|
||||
import { useDecoder } from '../../hooks/useDecoder'
|
||||
|
||||
const throttle = require('lodash.throttle')
|
||||
|
||||
@@ -25,117 +26,100 @@ interface Props {
|
||||
}
|
||||
}
|
||||
|
||||
interface State {
|
||||
displayMessage?: q.Message
|
||||
anchorEl?: HTMLElement
|
||||
lastUpdate: number
|
||||
}
|
||||
export const MessageHistory: React.FC<Props> = props => {
|
||||
const [, setLastUpdate] = React.useState(Date.now())
|
||||
const updateNodeThrottled = React.useCallback(
|
||||
throttle(() => {
|
||||
setLastUpdate
|
||||
}, 300),
|
||||
[]
|
||||
)
|
||||
|
||||
class MessageHistory extends React.PureComponent<Props, State> {
|
||||
private updateNode = throttle(() => {
|
||||
this.setState({ lastUpdate: Date.now() })
|
||||
}, 300)
|
||||
useSubscription(props.node?.onMessage, updateNodeThrottled)
|
||||
const decodeMessage = useDecoder(props.node)
|
||||
|
||||
constructor(props: any) {
|
||||
super(props)
|
||||
this.state = { lastUpdate: 0 }
|
||||
}
|
||||
|
||||
private addNodeToCharts = (event: React.MouseEvent) => {
|
||||
function addNodeToCharts(event: React.MouseEvent) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
const { node } = this.props
|
||||
const { node } = props
|
||||
if (!node) {
|
||||
return null
|
||||
}
|
||||
|
||||
this.props.actions.charts.addChart({ topic: node.path() })
|
||||
props.actions.charts.addChart({ topic: node.path() })
|
||||
}
|
||||
|
||||
private displayMessage = (index: number, eventTarget: EventTarget) => {
|
||||
const message = this.props.node && this.props.node.messageHistory.toArray().reverse()[index]
|
||||
function displayMessage(index: number, eventTarget: EventTarget) {
|
||||
const message = props.node && props.node.messageHistory.toArray().reverse()[index]
|
||||
if (message) {
|
||||
this.props.onSelect(message)
|
||||
props.onSelect(message)
|
||||
}
|
||||
}
|
||||
|
||||
public componentWillReceiveProps(nextProps: Props) {
|
||||
this.props.node && this.props.node.onMessage.unsubscribe(this.updateNode)
|
||||
nextProps.node && nextProps.node.onMessage.subscribe(this.updateNode)
|
||||
const { node } = props
|
||||
if (!node) {
|
||||
return null
|
||||
}
|
||||
|
||||
public componentDidMount() {
|
||||
this.props.node && this.props.node.onMessage.subscribe(this.updateNode)
|
||||
}
|
||||
const history = node.messageHistory.toArray()
|
||||
let previousMessage: q.Message | undefined = node.message
|
||||
const historyElements = [...history].reverse().map((message, idx) => {
|
||||
const value = node.message ? decodeMessage(message)?.message?.format()[0] ?? null : null
|
||||
|
||||
public componentWillUnMount() {
|
||||
this.props.node && this.props.node.onMessage.unsubscribe(this.updateNode)
|
||||
}
|
||||
|
||||
public render() {
|
||||
const { node } = this.props
|
||||
if (!node) {
|
||||
return null
|
||||
}
|
||||
|
||||
const history = node.messageHistory.toArray()
|
||||
let previousMessage: q.Message | undefined = node.message
|
||||
const historyElements = [...history].reverse().map((message, idx) => {
|
||||
const value = message.payload ? Base64Message.toUnicodeString(message.payload) : ''
|
||||
const element = {
|
||||
value,
|
||||
key: `${message.messageNumber}-${message.received}`,
|
||||
title: (
|
||||
const element = {
|
||||
value: value ?? '',
|
||||
key: `${message.messageNumber}-${message.received}`,
|
||||
title: (
|
||||
<span>
|
||||
<div style={{ float: 'left' }}>
|
||||
<DateFormatter date={message.received} />
|
||||
{previousMessage && previousMessage !== message ? (
|
||||
<i>
|
||||
(-
|
||||
<DateFormatter date={message.received} intervalSince={previousMessage.received} />)
|
||||
</i>
|
||||
) : null}
|
||||
</div>
|
||||
<span>
|
||||
<div style={{ float: 'left' }}>
|
||||
<DateFormatter date={message.received} />
|
||||
{previousMessage && previousMessage !== message ? (
|
||||
<i>
|
||||
(-
|
||||
<DateFormatter date={message.received} intervalSince={previousMessage.received} />)
|
||||
</i>
|
||||
) : null}
|
||||
</div>
|
||||
<span>
|
||||
|
||||
<MessageId message={message} />
|
||||
</span>
|
||||
<div style={{ float: 'right' }}>
|
||||
<Copy value={value} />
|
||||
</div>
|
||||
|
||||
<MessageId message={message} />
|
||||
</span>
|
||||
),
|
||||
selected: message && message === this.props.selected,
|
||||
}
|
||||
previousMessage = message
|
||||
return element
|
||||
})
|
||||
<div style={{ float: 'right' }}>
|
||||
<Copy value={value ?? ''} />
|
||||
</div>
|
||||
</span>
|
||||
),
|
||||
selected: message && message === props.selected,
|
||||
}
|
||||
previousMessage = message
|
||||
return element
|
||||
})
|
||||
|
||||
const isMessagePlottable =
|
||||
node.message && node.message.payload && isPlottable(Base64Message.toUnicodeString(node.message.payload))
|
||||
return (
|
||||
<div>
|
||||
<History
|
||||
items={historyElements}
|
||||
contentTypeIndicator={
|
||||
isMessagePlottable ? (
|
||||
<CustomIconButton
|
||||
style={{ height: '22px', width: '22px' }}
|
||||
onClick={this.addNodeToCharts}
|
||||
tooltip="Add to chart panel"
|
||||
>
|
||||
<ShowChart style={{ marginTop: '-5px' }} />
|
||||
</CustomIconButton>
|
||||
) : undefined
|
||||
}
|
||||
onClick={this.displayMessage}
|
||||
>
|
||||
{isMessagePlottable ? <TopicPlot history={node.messageHistory} /> : null}
|
||||
</History>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const value = node.message ? decodeMessage(node.message)?.message?.format()[0] ?? null : null
|
||||
|
||||
const isMessagePlottable = isPlottable(value)
|
||||
return (
|
||||
<div>
|
||||
<History
|
||||
items={historyElements}
|
||||
contentTypeIndicator={
|
||||
isMessagePlottable ? (
|
||||
<CustomIconButton
|
||||
style={{ height: '22px', width: '22px' }}
|
||||
onClick={addNodeToCharts}
|
||||
tooltip="Add to chart panel"
|
||||
>
|
||||
<ShowChart style={{ marginTop: '-5px' }} />
|
||||
</CustomIconButton>
|
||||
) : undefined
|
||||
}
|
||||
onClick={displayMessage}
|
||||
>
|
||||
{isMessagePlottable ? <TopicPlot node={node} history={node.messageHistory} /> : null}
|
||||
</History>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const mapDispatchToProps = (dispatch: any) => {
|
||||
@@ -144,4 +128,4 @@ const mapDispatchToProps = (dispatch: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(null, mapDispatchToProps)(MessageHistory)
|
||||
export default connect(null, mapDispatchToProps)(React.memo(MessageHistory))
|
||||
|
||||
@@ -7,13 +7,13 @@ import Panel from '../Panel'
|
||||
import React, { useCallback } from 'react'
|
||||
import ValueRenderer from './ValueRenderer'
|
||||
import { AppState } from '../../../reducers'
|
||||
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Theme, Typography, withStyles } from '@material-ui/core'
|
||||
import { connect } from 'react-redux'
|
||||
import { sidebarActions } from '../../../actions'
|
||||
import DeleteSelectedTopicButton from './DeleteSelectedTopicButton'
|
||||
import { MessageId } from '../MessageId'
|
||||
import { useDecoder } from '../../hooks/useDecoder'
|
||||
|
||||
interface Props {
|
||||
node?: q.TreeNode<any>
|
||||
@@ -35,6 +35,7 @@ function RenderedValue(props: { node?: q.TreeNode<any>; compareMessage?: q.Messa
|
||||
|
||||
function ValuePanel(props: Props) {
|
||||
const { node, compareMessage } = props
|
||||
const decodeMessage = useDecoder(node)
|
||||
|
||||
function renderViewOptions() {
|
||||
if (!props.node || !props.node.message) {
|
||||
@@ -54,6 +55,10 @@ function ValuePanel(props: Props) {
|
||||
)
|
||||
}
|
||||
|
||||
const getDecodedValue = useCallback(() => {
|
||||
return node?.message && decodeMessage(node.message)?.message?.toUnicodeString()
|
||||
}, [node, decodeMessage])
|
||||
|
||||
function messageMetaInfo() {
|
||||
if (!props.node || !props.node.message) {
|
||||
return null
|
||||
@@ -85,10 +90,9 @@ function ValuePanel(props: Props) {
|
||||
[compareMessage]
|
||||
)
|
||||
|
||||
const copyValue =
|
||||
node && node.message && node.message.payload ? (
|
||||
<Copy value={Base64Message.toUnicodeString(node.message.payload)} />
|
||||
) : null
|
||||
const [value] =
|
||||
node && node.message && node.message.payload ? node.message.payload?.format(node.type) : [null, undefined]
|
||||
const copyValue = value ? <Copy getValue={getDecodedValue} /> : null
|
||||
|
||||
return (
|
||||
<Panel>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import * as React from 'react'
|
||||
import React, { useMemo } from 'react'
|
||||
import CodeDiff from '../CodeDiff'
|
||||
import { AppState } from '../../../reducers'
|
||||
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
|
||||
import { connect } from 'react-redux'
|
||||
import { ValueRendererDisplayMode } from '../../../reducers/Settings'
|
||||
import { Fade } from '@material-ui/core'
|
||||
import { Decoder } from '../../../../../backend/src/Model/Decoder'
|
||||
import { useDecoder } from '../../hooks/useDecoder'
|
||||
import { TopicViewModel } from '../../../model/TopicViewModel'
|
||||
|
||||
interface Props {
|
||||
message: q.Message
|
||||
@@ -15,103 +16,114 @@ interface Props {
|
||||
renderMode: ValueRendererDisplayMode
|
||||
}
|
||||
|
||||
interface State {
|
||||
width: number
|
||||
type Language = 'json'
|
||||
|
||||
function renderDiff(
|
||||
treeNode: q.TreeNode<TopicViewModel>,
|
||||
compareWithPreviousMessage: boolean,
|
||||
current: string = '',
|
||||
previous: string = '',
|
||||
title?: string,
|
||||
language?: Language
|
||||
) {
|
||||
return (
|
||||
<CodeDiff
|
||||
treeNode={treeNode}
|
||||
previous={previous}
|
||||
current={current}
|
||||
title={title}
|
||||
language={language}
|
||||
nameOfCompareMessage={compareWithPreviousMessage ? 'selected' : 'previous'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
class ValueRenderer extends React.Component<Props, State> {
|
||||
constructor(props: Props) {
|
||||
super(props)
|
||||
this.state = { width: 0 }
|
||||
}
|
||||
function renderDiffMode(
|
||||
treeNode: q.TreeNode<TopicViewModel>,
|
||||
currentStr: string | undefined,
|
||||
compareStr: string | undefined,
|
||||
currentType: Language | undefined,
|
||||
compareType: Language | undefined,
|
||||
compareWithPreviousMessage: boolean
|
||||
) {
|
||||
const language = currentType === compareType && compareType === 'json' ? 'json' : undefined
|
||||
|
||||
private renderDiff(current: string = '', previous: string = '', title?: string, language?: 'json') {
|
||||
return (
|
||||
<CodeDiff
|
||||
treeNode={this.props.treeNode}
|
||||
previous={previous}
|
||||
current={current}
|
||||
title={title}
|
||||
language={language}
|
||||
nameOfCompareMessage={this.props.compareWith ? 'selected' : 'previous'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return <div>{renderDiff(treeNode, compareWithPreviousMessage, currentStr, compareStr, undefined, language)}</div>
|
||||
}
|
||||
|
||||
private convertMessage(msg?: Base64Message): [string | undefined, 'json' | undefined] {
|
||||
if (!msg) {
|
||||
return [undefined, undefined]
|
||||
}
|
||||
function renderRawMode(
|
||||
treeNode: q.TreeNode<TopicViewModel>,
|
||||
currentStr: string | undefined,
|
||||
compareStr: string | undefined,
|
||||
currentType: Language | undefined,
|
||||
compareType: Language | undefined,
|
||||
compareWithPreviousMessage: boolean
|
||||
) {
|
||||
return (
|
||||
<div>
|
||||
{renderDiff(treeNode, compareWithPreviousMessage, currentStr, currentStr, undefined, currentType)}
|
||||
<Fade in={Boolean(compareStr)} timeout={400}>
|
||||
<div>
|
||||
{Boolean(compareStr)
|
||||
? renderDiff(treeNode, compareWithPreviousMessage, compareStr, compareStr, 'selected', compareType)
|
||||
: null}
|
||||
</div>
|
||||
</Fade>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const str = Base64Message.toUnicodeString(msg)
|
||||
try {
|
||||
JSON.parse(str)
|
||||
} catch (error) {
|
||||
return [str, undefined]
|
||||
}
|
||||
export const ValueRenderer: React.FC<Props> = ({ treeNode, compareWith: compare, message, renderMode }) => {
|
||||
const decodeMessage = useDecoder(treeNode)
|
||||
const decodedMessage = useMemo(() => decodeMessage(message), [decodeMessage, message])
|
||||
|
||||
return [this.messageToPrettyJson(str), 'json']
|
||||
}
|
||||
const previousMessages = treeNode.messageHistory.toArray()
|
||||
const previousMessage = previousMessages[previousMessages.length - 2]
|
||||
const compareMessage = compare || previousMessage || message
|
||||
const compareWithPreviousMessage = !!compare
|
||||
|
||||
private messageToPrettyJson(str: string): string | undefined {
|
||||
try {
|
||||
const json = JSON.parse(str)
|
||||
return JSON.stringify(json, undefined, ' ')
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
const [currentStr, currentType] = useMemo(
|
||||
() => decodedMessage?.message?.format(treeNode.type) ?? [],
|
||||
[decodedMessage, treeNode.type]
|
||||
)
|
||||
const [compareStr, compareType] = useMemo(
|
||||
() => decodeMessage(compareMessage)?.message?.format(treeNode.type) ?? [],
|
||||
[compareMessage, decodeMessage, treeNode.type]
|
||||
)
|
||||
|
||||
private renderRawMode(message: q.Message, compare?: q.Message) {
|
||||
if (!message.payload) {
|
||||
return
|
||||
}
|
||||
const [value, valueLanguage] = this.convertMessage(message.payload)
|
||||
const [compareStr, compareStrLanguage] =
|
||||
compare && compare.payload ? this.convertMessage(compare.payload) : [undefined, undefined]
|
||||
|
||||
return (
|
||||
<div>
|
||||
{this.renderDiff(value, value, undefined, valueLanguage)}
|
||||
<Fade in={Boolean(compareStr)} timeout={400}>
|
||||
<div>
|
||||
{Boolean(compareStr) ? this.renderDiff(compareStr, compareStr, 'selected', compareStrLanguage) : null}
|
||||
</div>
|
||||
</Fade>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
public render() {
|
||||
return (
|
||||
<div style={{ padding: '0px 0px 8px 0px', width: '100%' }}>
|
||||
{this.props.message?.payload?.decoder === Decoder.SPARKPLUG && 'Decoded SparkplugB'}
|
||||
{this.renderValue()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
public renderValue() {
|
||||
const { message, treeNode, compareWith, renderMode } = this.props
|
||||
const previousMessages = treeNode.messageHistory.toArray()
|
||||
const previousMessage = previousMessages[previousMessages.length - 2]
|
||||
const compareMessage = compareWith || previousMessage || message
|
||||
|
||||
if (renderMode === 'raw') {
|
||||
return this.renderRawMode(message, compareWith)
|
||||
}
|
||||
if (!message.payload) {
|
||||
function renderValue(
|
||||
treeNode: q.TreeNode<TopicViewModel>,
|
||||
currentStr: string | undefined,
|
||||
compareStr: string | undefined,
|
||||
currentType: Language | undefined,
|
||||
compareType: Language | undefined,
|
||||
renderMode: string,
|
||||
compareWithPreviousMessage: boolean
|
||||
) {
|
||||
if (!decodedMessage) {
|
||||
return null
|
||||
}
|
||||
|
||||
const compareValue = compareMessage.payload || message.payload
|
||||
const [current, currentLanguage] = this.convertMessage(message.payload)
|
||||
const [compare, compareLanguage] = this.convertMessage(compareValue)
|
||||
|
||||
const language = currentLanguage === compareLanguage && compareLanguage === 'json' ? 'json' : undefined
|
||||
|
||||
return this.renderDiff(current, compare, undefined, language)
|
||||
switch (renderMode) {
|
||||
case 'diff':
|
||||
return renderDiffMode(treeNode, currentStr, compareStr, currentType, compareType, compareWithPreviousMessage)
|
||||
default:
|
||||
return renderRawMode(treeNode, currentStr, compareStr, currentType, compareType, compareWithPreviousMessage)
|
||||
}
|
||||
}
|
||||
|
||||
const renderedValue = useMemo(
|
||||
() =>
|
||||
renderValue(treeNode, currentStr, compareStr, currentType, compareType, renderMode, compareWithPreviousMessage),
|
||||
[treeNode, currentStr, compareStr, currentType, compareType, renderMode, compareWithPreviousMessage]
|
||||
)
|
||||
|
||||
return (
|
||||
<div style={{ padding: '0px 0px 8px 0px', width: '100%' }}>
|
||||
{decodedMessage?.decoder === Decoder.SPARKPLUG && 'Decoded SparkplugB'}
|
||||
{renderedValue}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const mapStateToProps = (state: AppState) => {
|
||||
|
||||
@@ -2,12 +2,14 @@ import * as dotProp from 'dot-prop'
|
||||
import * as q from '../../../backend/src/Model'
|
||||
import * as React from 'react'
|
||||
import PlotHistory from './Chart/Chart'
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
import { toPlottableValue } from './Sidebar/CodeDiff/util'
|
||||
import { PlotCurveTypes } from '../reducers/Charts'
|
||||
import { DecoderFunction, useDecoder } from './hooks/useDecoder'
|
||||
|
||||
const parseDuration = require('parse-duration')
|
||||
|
||||
interface Props {
|
||||
node?: q.TreeNode<any>
|
||||
history: q.MessageHistory
|
||||
dotPath?: string
|
||||
timeInterval?: string
|
||||
@@ -25,21 +27,27 @@ function filterUsingTimeRange(startTime: number | undefined, data: Array<q.Messa
|
||||
return data
|
||||
}
|
||||
|
||||
function nodeToHistory(startTime: number | undefined, history: q.MessageHistory) {
|
||||
function nodeToHistory(decodeMessage: DecoderFunction, startTime: number | undefined, history: q.MessageHistory) {
|
||||
return filterUsingTimeRange(startTime, history.toArray())
|
||||
.map((message: q.Message) => {
|
||||
const value = message.payload ? toPlottableValue(Base64Message.toUnicodeString(message.payload)) : NaN
|
||||
return { x: message.received.getTime(), y: toPlottableValue(value) }
|
||||
const decoded = decodeMessage(message)?.message?.toUnicodeString()
|
||||
return { x: message.received.getTime(), y: toPlottableValue(decoded) }
|
||||
})
|
||||
.filter(data => !isNaN(data.y as any)) as any
|
||||
}
|
||||
|
||||
function nodeDotPathToHistory(startTime: number | undefined, history: q.MessageHistory, dotPath: string) {
|
||||
function nodeDotPathToHistory(
|
||||
decodeMessage: DecoderFunction,
|
||||
startTime: number | undefined,
|
||||
history: q.MessageHistory,
|
||||
dotPath: string
|
||||
) {
|
||||
return filterUsingTimeRange(startTime, history.toArray())
|
||||
.map((message: q.Message) => {
|
||||
let json: any = {}
|
||||
try {
|
||||
json = message.payload ? JSON.parse(Base64Message.toUnicodeString(message.payload)) : {}
|
||||
const decoded = decodeMessage(message)?.message
|
||||
json = decoded ? JSON.parse(decoded.toUnicodeString()) : {}
|
||||
} catch (ignore) {}
|
||||
|
||||
const value = dotProp.get(json, dotPath)
|
||||
@@ -50,14 +58,17 @@ function nodeDotPathToHistory(startTime: number | undefined, history: q.MessageH
|
||||
}
|
||||
|
||||
function TopicPlot(props: Props) {
|
||||
const decodeMessage = useDecoder(props.node)
|
||||
const startOffset = props.timeInterval ? parseDuration(props.timeInterval) : undefined
|
||||
const data = React.useMemo(
|
||||
() =>
|
||||
props.dotPath
|
||||
? nodeDotPathToHistory(startOffset, props.history, props.dotPath)
|
||||
: nodeToHistory(startOffset, props.history),
|
||||
[props.history.last(), startOffset, props.dotPath]
|
||||
)
|
||||
const data = React.useMemo(() => {
|
||||
if (!props.node) {
|
||||
return []
|
||||
}
|
||||
|
||||
return props.dotPath
|
||||
? nodeDotPathToHistory(decodeMessage, startOffset, props.history, props.dotPath)
|
||||
: nodeToHistory(decodeMessage, startOffset, props.history)
|
||||
}, [props.history.last(), startOffset, props.dotPath])
|
||||
|
||||
return (
|
||||
<PlotHistory
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import React, { memo } from 'react'
|
||||
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
|
||||
import { Theme, withStyles } from '@material-ui/core'
|
||||
import { TopicViewModel } from '../../../model/TopicViewModel'
|
||||
import { useDecoder } from '../../hooks/useDecoder'
|
||||
|
||||
export interface TreeNodeProps extends React.HTMLAttributes<HTMLElement> {
|
||||
treeNode: q.TreeNode<TopicViewModel>
|
||||
@@ -14,67 +14,72 @@ export interface TreeNodeProps extends React.HTMLAttributes<HTMLElement> {
|
||||
classes: any
|
||||
}
|
||||
|
||||
class TreeNodeTitle extends React.PureComponent<TreeNodeProps, {}> {
|
||||
private renderSourceEdge() {
|
||||
const name = this.props.name || (this.props.treeNode.sourceEdge && this.props.treeNode.sourceEdge.name)
|
||||
export const TreeNodeTitle = (props: TreeNodeProps) => {
|
||||
const decodeMessage = useDecoder(props.treeNode)
|
||||
|
||||
function renderSourceEdge() {
|
||||
const name = props.name || (props.treeNode.sourceEdge && props.treeNode.sourceEdge.name)
|
||||
|
||||
return (
|
||||
<span key="edge" className={this.props.classes.sourceEdge} data-test-topic={name}>
|
||||
<span key="edge" className={props.classes.sourceEdge} data-test-topic={name}>
|
||||
{name}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
private truncatedMessage() {
|
||||
function truncatedMessage() {
|
||||
const limit = 400
|
||||
if (!this.props.treeNode.message || !this.props.treeNode.message.payload) {
|
||||
if (!props.treeNode.message || !props.treeNode.message.payload) {
|
||||
return ''
|
||||
}
|
||||
const [value = ''] = decodeMessage(props.treeNode.message)?.message?.format(props.treeNode.type) ?? []
|
||||
|
||||
const str = Base64Message.toUnicodeString(this.props.treeNode.message.payload)
|
||||
return str.length > limit ? `${str.slice(0, limit)}…` : str
|
||||
return value.length > limit ? `${value.slice(0, limit)}…` : value
|
||||
}
|
||||
|
||||
private renderValue() {
|
||||
return this.props.treeNode.message &&
|
||||
this.props.treeNode.message.payload &&
|
||||
this.props.treeNode.message.length > 0 ? (
|
||||
<span key="value" className={this.props.classes.value}>
|
||||
function renderValue() {
|
||||
return props.treeNode.message && props.treeNode.message.payload && props.treeNode.message.length > 0 ? (
|
||||
<span key="value" className={props.classes.value}>
|
||||
{' '}
|
||||
= {this.truncatedMessage()}
|
||||
= {truncatedMessage()}
|
||||
</span>
|
||||
) : null
|
||||
}
|
||||
|
||||
private renderExpander() {
|
||||
if (this.props.treeNode.edgeCount() === 0) {
|
||||
function renderExpander() {
|
||||
if (props.treeNode.edgeCount() === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<span key="expander" className={this.props.classes.expander} onClick={this.props.toggleCollapsed}>
|
||||
{this.props.collapsed ? '▶' : '▼'}
|
||||
<span key="expander" className={props.classes.expander} onClick={props.toggleCollapsed}>
|
||||
{props.collapsed ? '▶' : '▼'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
private renderMetadata() {
|
||||
if (this.props.treeNode.edgeCount() === 0 || !this.props.collapsed) {
|
||||
function renderMetadata() {
|
||||
if (props.treeNode.edgeCount() === 0 || !props.collapsed) {
|
||||
return null
|
||||
}
|
||||
|
||||
const messages = this.props.treeNode.leafMessageCount()
|
||||
const topicCount = this.props.treeNode.childTopicCount()
|
||||
const messages = props.treeNode.leafMessageCount()
|
||||
const topicCount = props.treeNode.childTopicCount()
|
||||
return (
|
||||
<span key="metadata" className={this.props.classes.collapsedSubnodes}>{` (${topicCount} ${
|
||||
<span key="metadata" className={props.classes.collapsedSubnodes}>{` (${topicCount} ${
|
||||
topicCount === 1 ? 'topic' : 'topics'
|
||||
}, ${messages} ${messages === 1 ? 'message' : 'messages'})`}</span>
|
||||
)
|
||||
}
|
||||
|
||||
public render() {
|
||||
return [this.renderExpander(), this.renderSourceEdge(), this.renderMetadata(), this.renderValue()]
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{renderExpander()}
|
||||
{renderSourceEdge()}
|
||||
{renderMetadata()}
|
||||
{renderValue()}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = (theme: Theme) => ({
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as q from '../../../../../../backend/src/Model'
|
||||
import { useEffect } from 'react'
|
||||
import { TopicViewModel } from '../../../../model/TopicViewModel'
|
||||
|
||||
export function useViewModel(treeNode: q.TreeNode<TopicViewModel> | undefined) {
|
||||
useEffect(() => {
|
||||
if (treeNode && !treeNode?.viewModel) {
|
||||
treeNode.viewModel = new TopicViewModel(treeNode)
|
||||
}
|
||||
treeNode?.viewModel?.retain()
|
||||
|
||||
return function cleanup() {
|
||||
treeNode?.viewModel?.release()
|
||||
}
|
||||
}, [treeNode])
|
||||
|
||||
return treeNode?.viewModel
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as q from '../../../../../../backend/src/Model'
|
||||
import React, { useEffect } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { TopicViewModel } from '../../../../model/TopicViewModel'
|
||||
import { useSubscription } from '../../../hooks/useSubscription'
|
||||
import { useViewModel } from './useViewModel'
|
||||
|
||||
export function useViewModelSubscriptions(
|
||||
treeNode: q.TreeNode<TopicViewModel>,
|
||||
@@ -8,37 +10,21 @@ export function useViewModelSubscriptions(
|
||||
setSelected: (value: boolean) => void,
|
||||
setCollapsedOverride: (value: boolean) => void
|
||||
) {
|
||||
useEffect(() => {
|
||||
const selectionDidChange = () => {
|
||||
const selected = treeNode.viewModel && treeNode.viewModel.isSelected()
|
||||
treeNode.viewModel && setSelected(Boolean(selected))
|
||||
const viewModel = useViewModel(treeNode)
|
||||
|
||||
if (selected && nodeRef && nodeRef.current) {
|
||||
nodeRef.current.focus({ preventScroll: false })
|
||||
}
|
||||
}
|
||||
const selectionDidChange = useCallback(() => {
|
||||
const selected = viewModel && viewModel.isSelected()
|
||||
viewModel && setSelected(Boolean(selected))
|
||||
|
||||
const expandedDidChange = () => {
|
||||
treeNode.viewModel && setCollapsedOverride(!treeNode.viewModel.isExpanded())
|
||||
if (selected && nodeRef && nodeRef.current) {
|
||||
nodeRef.current.focus({ preventScroll: false })
|
||||
}
|
||||
}, [viewModel])
|
||||
|
||||
function addSubscriber() {
|
||||
treeNode.viewModel = new TopicViewModel()
|
||||
treeNode.viewModel.selectionChange.subscribe(selectionDidChange)
|
||||
treeNode.viewModel.expandedChange.subscribe(expandedDidChange)
|
||||
}
|
||||
const expandedDidChange = useCallback(() => {
|
||||
viewModel && setCollapsedOverride(!viewModel.isExpanded())
|
||||
}, [viewModel])
|
||||
|
||||
function removeSubscriber() {
|
||||
if (treeNode.viewModel) {
|
||||
treeNode.viewModel.selectionChange.unsubscribe(selectionDidChange)
|
||||
treeNode.viewModel.expandedChange.unsubscribe(expandedDidChange)
|
||||
treeNode.viewModel = undefined
|
||||
}
|
||||
}
|
||||
|
||||
addSubscriber()
|
||||
return function cleanup() {
|
||||
removeSubscriber()
|
||||
}
|
||||
}, [treeNode])
|
||||
useSubscription(viewModel?.selectionChange, selectionDidChange)
|
||||
useSubscription(viewModel?.expandedChange, expandedDidChange)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as compareVersions from 'compare-versions'
|
||||
import * as electron from 'electron'
|
||||
import * as os from 'os'
|
||||
import * as React from 'react'
|
||||
import compareVersions from 'compare-versions'
|
||||
import electron from 'electron'
|
||||
import os from 'os'
|
||||
import React from 'react'
|
||||
import axios from 'axios'
|
||||
import Close from '@material-ui/icons/Close'
|
||||
import CloudDownload from '@material-ui/icons/CloudDownload'
|
||||
|
||||
@@ -9,7 +9,8 @@ import { globalActions } from '../../actions'
|
||||
const copy = require('copy-text-to-clipboard')
|
||||
|
||||
interface Props {
|
||||
value: string
|
||||
value?: string
|
||||
getValue?: () => string | undefined
|
||||
actions: {
|
||||
global: typeof globalActions
|
||||
}
|
||||
@@ -28,7 +29,7 @@ class Copy extends React.PureComponent<Props, State> {
|
||||
private handleClick = (event: React.MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
|
||||
copy(this.props.value)
|
||||
copy(this.props.value ?? this.props.getValue?.())
|
||||
this.props.actions.global.showNotification('Copied to clipboard')
|
||||
this.setState({ didCopy: true })
|
||||
setTimeout(() => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as moment from 'moment'
|
||||
import * as React from 'react'
|
||||
import moment from 'moment'
|
||||
import React from 'react'
|
||||
import { AppState } from '../../reducers'
|
||||
import { connect } from 'react-redux'
|
||||
|
||||
@@ -12,6 +12,7 @@ interface Props {
|
||||
}
|
||||
|
||||
const unitMapping = {
|
||||
ms: 'milliseconds',
|
||||
s: 'seconds',
|
||||
m: 'minutes',
|
||||
h: 'hours',
|
||||
@@ -21,7 +22,7 @@ class DateFormatter extends React.PureComponent<Props, {}> {
|
||||
private intervalSince(intervalSince: Date) {
|
||||
const interval = intervalSince.getTime() - this.props.date.getTime()
|
||||
const unit = this.unitForInterval(interval)
|
||||
return `${Math.round(moment.duration(interval).as(unit) * 100) / 100} ${unitMapping[unit]}`
|
||||
return `${moment.duration(interval).as(unit).toFixed(3)} ${unitMapping[unit]}`
|
||||
}
|
||||
|
||||
private legacyDate() {
|
||||
@@ -31,10 +32,11 @@ class DateFormatter extends React.PureComponent<Props, {}> {
|
||||
private localizedDate(locale: string) {
|
||||
return moment(this.props.date)
|
||||
.locale(locale)
|
||||
.format(this.props.timeFirst ? 'LTS L' : 'L LTS')
|
||||
.format(this.props.timeFirst ? 'LTS.SSS L' : 'L LTS.SSS')
|
||||
}
|
||||
|
||||
private unitForInterval(milliseconds: number) {
|
||||
const oneSecond = 1000 * 1
|
||||
const oneMinute = 1000 * 60
|
||||
const oneHour = oneMinute * 60
|
||||
|
||||
@@ -46,7 +48,11 @@ class DateFormatter extends React.PureComponent<Props, {}> {
|
||||
return 'm'
|
||||
}
|
||||
|
||||
return 's'
|
||||
if (milliseconds > oneSecond * 0.5) {
|
||||
return 's'
|
||||
}
|
||||
|
||||
return 'ms'
|
||||
}
|
||||
|
||||
public render() {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as q from '../../../../backend/src/Model'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { TopicViewModel } from '../../model/TopicViewModel'
|
||||
import { useSubscription } from './useSubscription'
|
||||
import { useViewModel } from '../Tree/TreeNode/effects/useViewModel'
|
||||
import { DecoderEnvelope } from '../../decoders/DecoderEnvelope'
|
||||
import { Decoder } from '../../../../backend/src/Model/Decoder'
|
||||
|
||||
export type DecoderFunction = (message: q.Message) => DecoderEnvelope | undefined
|
||||
|
||||
/**
|
||||
* Provides the latest decoder for a topic
|
||||
*
|
||||
* @param treeNode
|
||||
* @returns
|
||||
*/
|
||||
export function useDecoder(treeNode: q.TreeNode<TopicViewModel> | undefined): DecoderFunction {
|
||||
const viewModel = useViewModel(treeNode)
|
||||
const [decoder, setDecoder] = useState(viewModel?.decoder)
|
||||
|
||||
useSubscription(viewModel?.onDecoderChange, setDecoder)
|
||||
|
||||
return useCallback(
|
||||
message => {
|
||||
return decoder && message.payload
|
||||
? decoder.decoder.decode(message.payload, decoder.format)
|
||||
: { message: message.payload ?? undefined, decoder: Decoder.NONE }
|
||||
},
|
||||
[decoder]
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useEffect } from 'react'
|
||||
import { EventDispatcher } from '../../../../events'
|
||||
|
||||
export function useSubscription<T>(dispatcher: EventDispatcher<T> | undefined, callback: (value: T) => void) {
|
||||
useEffect(() => {
|
||||
dispatcher?.subscribe(callback)
|
||||
|
||||
return () => dispatcher?.unsubscribe(callback)
|
||||
}, [dispatcher, callback])
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
import { Decoder } from '../../../backend/src/Model/Decoder'
|
||||
import { DecoderEnvelope } from './DecoderEnvelope'
|
||||
import { MessageDecoder } from './MessageDecoder'
|
||||
|
||||
type BinaryFormats =
|
||||
| 'int8'
|
||||
| 'int16'
|
||||
| 'int32'
|
||||
| 'int64'
|
||||
| 'uint8'
|
||||
| 'uint16'
|
||||
| 'uint32'
|
||||
| 'uint64'
|
||||
| 'float'
|
||||
| 'double'
|
||||
|
||||
/**
|
||||
* Binary decode primitive binary data type and arrays of these
|
||||
*/
|
||||
export const BinaryDecoder: MessageDecoder<BinaryFormats> = {
|
||||
formats: ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float', 'double'],
|
||||
decode(input: Base64Message, format: BinaryFormats): DecoderEnvelope {
|
||||
const decodingOption = {
|
||||
int8: [Buffer.prototype.readInt8, 1],
|
||||
int16: [Buffer.prototype.readInt16LE, 2],
|
||||
int32: [Buffer.prototype.readInt32LE, 4],
|
||||
int64: [Buffer.prototype.readBigInt64LE, 8],
|
||||
uint8: [Buffer.prototype.readUint8, 1],
|
||||
uint16: [Buffer.prototype.readUint16LE, 2],
|
||||
uint32: [Buffer.prototype.readUint32LE, 4],
|
||||
uint64: [Buffer.prototype.readBigUint64LE, 8],
|
||||
float: [Buffer.prototype.readFloatLE, 4],
|
||||
double: [Buffer.prototype.readDoubleLE, 8],
|
||||
} as const
|
||||
|
||||
const [readNumber, bytesToRead] = decodingOption[format]
|
||||
|
||||
const buf = input.toBuffer()
|
||||
let str: String[] = []
|
||||
if (buf.length % bytesToRead !== 0) {
|
||||
return {
|
||||
error: 'Data type does not align with message',
|
||||
decoder: Decoder.NONE,
|
||||
}
|
||||
}
|
||||
for (let index = 0; index < buf.length; index += bytesToRead) {
|
||||
str.push((readNumber as any).apply(buf, [index]).toString())
|
||||
}
|
||||
|
||||
return {
|
||||
message: Base64Message.fromString(JSON.stringify(str.length === 1 ? str[0] : str)),
|
||||
decoder: Decoder.NONE,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
import { Decoder } from '../../../backend/src/Model/Decoder'
|
||||
|
||||
export interface DecoderEnvelope {
|
||||
message?: Base64Message
|
||||
error?: string
|
||||
decoder: Decoder
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
import { DecoderEnvelope } from './DecoderEnvelope'
|
||||
|
||||
export interface MessageDecoder<T = string> {
|
||||
/**
|
||||
* Can be used to
|
||||
* @param topic
|
||||
*/
|
||||
formats: T[]
|
||||
canDecodeTopic?(topic: string): boolean
|
||||
canDecodeData?(data: Base64Message): boolean
|
||||
decode(input: Base64Message, format: T | string | undefined): DecoderEnvelope
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
import { Decoder } from '../../../backend/src/Model/Decoder'
|
||||
import { get } from 'sparkplug-payload'
|
||||
import { MessageDecoder } from './MessageDecoder'
|
||||
var sparkplug = get('spBv1.0')
|
||||
|
||||
export const SparkplugDecoder: MessageDecoder = {
|
||||
formats: ['Sparkplug'],
|
||||
canDecodeTopic(topic: string) {
|
||||
return !!topic.match(/^spBv1\.0\/[^/]+\/[ND](DATA|CMD|DEATH|BIRTH)\/[^/]+(\/[^/]+)?$/u)
|
||||
},
|
||||
decode(input) {
|
||||
try {
|
||||
const message = Base64Message.fromString(
|
||||
JSON.stringify(
|
||||
// @ts-ignore
|
||||
sparkplug.decodePayload(new Uint8Array(input.toBuffer()))
|
||||
)
|
||||
)
|
||||
return { message, decoder: Decoder.SPARKPLUG }
|
||||
} catch {
|
||||
return {
|
||||
error: 'Failed to decode sparkplugb payload',
|
||||
decoder: Decoder.NONE,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Base64Message } from '../../../backend/src/Model/Base64Message'
|
||||
import { Decoder } from '../../../backend/src/Model/Decoder'
|
||||
import { MessageDecoder } from './MessageDecoder'
|
||||
|
||||
export const StringDecoder: MessageDecoder = {
|
||||
formats: ['string'],
|
||||
decode(input: Base64Message) {
|
||||
return { message: input, decoder: Decoder.NONE }
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { StringDecoder } from './StringDecoder'
|
||||
import { BinaryDecoder } from './BinaryDecoder'
|
||||
import { SparkplugDecoder } from './SparkplugBDecoder'
|
||||
export * from './MessageDecoder'
|
||||
|
||||
export const decoders = [SparkplugDecoder, BinaryDecoder, StringDecoder] as const
|
||||
@@ -77,11 +77,11 @@ export function createEmptyConnection(): ConnectionOptions {
|
||||
export function makeDefaultConnections() {
|
||||
return {
|
||||
// remember: there was also iot.eclipse.org once
|
||||
'mqtt.eclipse.org': {
|
||||
'mqtt.eclipseprojects.io': {
|
||||
...createEmptyConnection(),
|
||||
id: 'mqtt.eclipse.org',
|
||||
name: 'mqtt.eclipse.org',
|
||||
host: 'mqtt.eclipse.org',
|
||||
id: 'mqtt.eclipseprojects.io',
|
||||
name: 'mqtt.eclipseprojects.io',
|
||||
host: 'mqtt.eclipseprojects.io',
|
||||
},
|
||||
'test.mosquitto.org': {
|
||||
...createEmptyConnection(),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { ConnectionOptions, createEmptyConnection } from './ConnectionOptions'
|
||||
import { v4 } from 'uuid'
|
||||
|
||||
interface LegacyConnectionSettings {
|
||||
host: string
|
||||
|
||||
@@ -1,19 +1,77 @@
|
||||
import * as q from '../../../backend/src/Model'
|
||||
import { Destroyable } from '../../../backend/src/Model/Destroyable'
|
||||
import { MessageDecoder, decoders } from '../decoders'
|
||||
import { EventDispatcher } from '../../../events'
|
||||
|
||||
function findDecoder<T extends Destroyable>(node: q.TreeNode<T>): TopicDecoder | undefined {
|
||||
const decoder = decoders.find(
|
||||
decoder =>
|
||||
decoder.canDecodeTopic?.(node.path()) || (node.message?.payload && decoder.canDecodeData?.(node.message?.payload))
|
||||
)
|
||||
|
||||
return decoder
|
||||
? {
|
||||
decoder,
|
||||
format: undefined,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
type TopicDecoder = { decoder: MessageDecoder; format: string | undefined }
|
||||
|
||||
export class TopicViewModel implements Destroyable {
|
||||
private selected: boolean
|
||||
private expanded: boolean
|
||||
private owner: q.TreeNode<TopicViewModel> | undefined
|
||||
private _decoder?: TopicDecoder
|
||||
/**
|
||||
* Reference counter for useViewModel hook
|
||||
*/
|
||||
private referenceCounter = 0
|
||||
public selectionChange = new EventDispatcher<void>()
|
||||
public expandedChange = new EventDispatcher<void>()
|
||||
public onDecoderChange = new EventDispatcher<TopicDecoder | undefined>()
|
||||
|
||||
public constructor() {
|
||||
get decoder(): TopicDecoder | undefined {
|
||||
if (!this._decoder) {
|
||||
this._decoder = this.owner && findDecoder(this.owner)
|
||||
}
|
||||
|
||||
return this._decoder
|
||||
}
|
||||
|
||||
set decoder(override: TopicDecoder | undefined) {
|
||||
this._decoder = override
|
||||
|
||||
this.onDecoderChange.dispatch(override)
|
||||
}
|
||||
|
||||
public constructor(treeNode: q.TreeNode<TopicViewModel>) {
|
||||
this.owner = treeNode
|
||||
this.selected = false
|
||||
this.expanded = false
|
||||
}
|
||||
|
||||
public retain() {
|
||||
this.referenceCounter += 1
|
||||
}
|
||||
|
||||
public release() {
|
||||
this.referenceCounter -= 1
|
||||
if (this.referenceCounter <= 0) {
|
||||
this.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
console.log('destroy', this.referenceCounter)
|
||||
if (this.owner) {
|
||||
this.owner.viewModel = undefined
|
||||
this.owner = undefined
|
||||
}
|
||||
this.selectionChange.removeAllListeners()
|
||||
this.onDecoderChange.removeAllListeners()
|
||||
this.expandedChange.removeAllListeners()
|
||||
}
|
||||
|
||||
public isSelected() {
|
||||
|
||||
+9
-21
@@ -4,38 +4,26 @@
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"strict": true,
|
||||
"lib": [
|
||||
"es2017",
|
||||
"dom"
|
||||
],
|
||||
"lib": ["es2019", "dom"],
|
||||
"moduleResolution": "node",
|
||||
"outDir": "./build/",
|
||||
"sourceMap": true,
|
||||
"module": "esnext",
|
||||
"target": "es2017",
|
||||
"target": "ES2017",
|
||||
"jsx": "react",
|
||||
"paths": {
|
||||
"react": [
|
||||
"./node_modules/@types/react"
|
||||
]
|
||||
"react": ["./node_modules/@types/react"]
|
||||
},
|
||||
"types": [
|
||||
"react"
|
||||
],
|
||||
"types": ["react"],
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"skipLibCheck": true
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": [
|
||||
"./src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"**/*.d.ts",
|
||||
".src/**/*.png",
|
||||
"./node_modules"
|
||||
],
|
||||
"include": ["./src/**/*"],
|
||||
"exclude": ["**/*.d.ts", ".src/**/*.png", "./node_modules"],
|
||||
"awesomeTypescriptLoaderOptions": {
|
||||
"useCache": true,
|
||||
"transpileModule": true,
|
||||
"errorsAsWarnings": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-2
@@ -41,6 +41,7 @@ module.exports = {
|
||||
devServer: {
|
||||
// contentBase: './dist', // content not from webpack
|
||||
hot: true,
|
||||
liveReload: true,
|
||||
},
|
||||
target: 'electron-renderer',
|
||||
mode: 'production',
|
||||
@@ -54,7 +55,15 @@ module.exports = {
|
||||
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
loader: 'ts-loader',
|
||||
use: [
|
||||
{
|
||||
loader: 'ts-loader',
|
||||
// options: {
|
||||
// configFile: './tsconfig.json',
|
||||
// },
|
||||
},
|
||||
],
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
|
||||
{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' },
|
||||
@@ -81,7 +90,6 @@ module.exports = {
|
||||
plugins: [
|
||||
new HtmlWebpackPlugin({ template: './index.html', file: './build/index.html', inject: false }),
|
||||
// new BundleAnalyzerPlugin(),
|
||||
new webpack.HotModuleReplacementPlugin(),
|
||||
// new webpack.IgnorePlugin({
|
||||
// resourceRegExp: /\.\/build\/Debug\/addon/,
|
||||
// contextRegExp: /heapdump$/
|
||||
@@ -96,4 +104,10 @@ module.exports = {
|
||||
// "react": "React",
|
||||
// "react-dom": "ReactDOM"
|
||||
},
|
||||
cache: {
|
||||
type: 'filesystem',
|
||||
},
|
||||
optimization: {
|
||||
runtimeChunk: 'single',
|
||||
},
|
||||
}
|
||||
|
||||
+441
-232
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
import * as FileAsync from 'lowdb/adapters/FileAsync'
|
||||
import * as fs from 'fs-extra'
|
||||
import * as lowdb from 'lowdb'
|
||||
import * as path from 'path'
|
||||
import FileAsync from 'lowdb/adapters/FileAsync'
|
||||
import fs from 'fs-extra'
|
||||
import lowdb from 'lowdb'
|
||||
import path from 'path'
|
||||
import { backendRpc } from '../../events'
|
||||
import { storageClearEvent, storageLoadEvent, storageStoreEvent } from '../../events/StorageEvents'
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ export class MqttSource implements DataSource<MqttOptions> {
|
||||
|
||||
public publish(msg: MqttMessage) {
|
||||
if (this.client) {
|
||||
this.client.publish(msg.topic, msg.payload ? Base64Message.toUnicodeString(msg.payload) : '', {
|
||||
this.client.publish(msg.topic, (msg.payload && new Base64Message(msg.payload))?.toBuffer() ?? '', {
|
||||
qos: msg.qos,
|
||||
retain: msg.retain,
|
||||
})
|
||||
|
||||
@@ -1,31 +1,93 @@
|
||||
import { Base64 } from 'js-base64'
|
||||
import { Decoder } from './Decoder'
|
||||
import { TopicDataType } from './TreeNode'
|
||||
|
||||
export type Base64MessageDTO = Pick<Base64Message, 'base64Message'>
|
||||
|
||||
export class Base64Message {
|
||||
private base64Message: string
|
||||
private unicodeValue: string
|
||||
public decoder: Decoder
|
||||
public length: number
|
||||
public base64Message: string
|
||||
private _unicodeValue: string | undefined
|
||||
|
||||
private constructor(base64Str: string) {
|
||||
this.base64Message = base64Str
|
||||
this.unicodeValue = Base64.decode(base64Str)
|
||||
this.length = base64Str.length
|
||||
this.decoder = Decoder.NONE
|
||||
// Todo: Rename to `encodedLength`
|
||||
public get length(): number {
|
||||
return this.base64Message.length
|
||||
}
|
||||
|
||||
public static toUnicodeString(message: Base64Message) {
|
||||
return message.unicodeValue || ''
|
||||
private get unicodeValue(): string {
|
||||
if (!this._unicodeValue) {
|
||||
this._unicodeValue = Base64.decode(this.base64Message ?? '')
|
||||
}
|
||||
|
||||
return this._unicodeValue
|
||||
}
|
||||
|
||||
constructor(base64Str?: string | Base64MessageDTO, error?: string) {
|
||||
if (typeof base64Str === 'string' || typeof base64Str === 'undefined') {
|
||||
this.base64Message = base64Str ?? ''
|
||||
} else {
|
||||
if (typeof base64Str.base64Message !== 'string') {
|
||||
throw new Error('Received unexpected type in copy constructor')
|
||||
}
|
||||
this.base64Message = base64Str.base64Message
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Override default JSON serialization behavior to only return the DTO
|
||||
* @returns
|
||||
*/
|
||||
public toJSON(): Base64MessageDTO {
|
||||
return { base64Message: this.base64Message }
|
||||
}
|
||||
|
||||
public toUnicodeString() {
|
||||
return this.unicodeValue || ''
|
||||
}
|
||||
|
||||
public static fromBuffer(buffer: Buffer) {
|
||||
return new Base64Message(buffer.toString('base64'))
|
||||
}
|
||||
|
||||
public toBuffer(): Buffer {
|
||||
return Buffer.from(this.base64Message, 'base64')
|
||||
}
|
||||
|
||||
public static fromString(str: string) {
|
||||
return new Base64Message(Base64.encode(str))
|
||||
}
|
||||
|
||||
public format(type: TopicDataType = 'string'): [string, 'json' | undefined] {
|
||||
try {
|
||||
switch (type) {
|
||||
case 'json': {
|
||||
const json = JSON.parse(this.toUnicodeString())
|
||||
return [JSON.stringify(json, undefined, ' '), 'json']
|
||||
}
|
||||
case 'hex': {
|
||||
const hex = Base64Message.toHex(this)
|
||||
return [hex, undefined]
|
||||
}
|
||||
default: {
|
||||
const str = this.toUnicodeString()
|
||||
return [str, undefined]
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const str = this.toUnicodeString()
|
||||
return [str, undefined]
|
||||
}
|
||||
}
|
||||
|
||||
public static toHex(message: Base64Message) {
|
||||
const buf = Buffer.from(message.base64Message, 'base64')
|
||||
|
||||
let str: string = ''
|
||||
buf.forEach(element => {
|
||||
let hex = element.toString(16).toUpperCase()
|
||||
str += `0x${hex.length < 2 ? '0' + hex : hex} `
|
||||
})
|
||||
return str.trimRight()
|
||||
}
|
||||
|
||||
public static toDataUri(message: Base64Message, mimeType: string) {
|
||||
return `data:${mimeType};base64,${message.base64Message}`
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export class ChangeBuffer {
|
||||
public push(val: MqttMessage) {
|
||||
if (!this.isFull()) {
|
||||
this.buffer.push({ message: val, received: new Date() })
|
||||
this.size += this.estimatedMessageOverhead + (val.payload ? val.payload.length : 0)
|
||||
this.size += this.estimatedMessageOverhead + (val.payload?.base64Message.length ?? 0)
|
||||
this.length += 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Base64Message } from './Base64Message'
|
||||
import { QoS } from '../DataSource/MqttSource'
|
||||
import { MemoryConsumptionExpressedByLength } from './RingBuffer'
|
||||
|
||||
export interface Message {
|
||||
export interface Message extends MemoryConsumptionExpressedByLength {
|
||||
// mqtt based info
|
||||
payload: Base64Message | null
|
||||
messageId?: number
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Destroyable } from './Destroyable'
|
||||
import { Edge, Message, RingBuffer, MessageHistory } from './'
|
||||
import { EventDispatcher } from '../../../events'
|
||||
|
||||
export type TopicDataType = 'string' | 'json' | 'hex'
|
||||
|
||||
export class TreeNode<ViewModel extends Destroyable> {
|
||||
public sourceEdge?: Edge<ViewModel>
|
||||
public message?: Message
|
||||
@@ -17,6 +19,7 @@ export class TreeNode<ViewModel extends Destroyable> {
|
||||
public onMessage = new EventDispatcher<Message>()
|
||||
public onDestroy = new EventDispatcher<TreeNode<ViewModel>>()
|
||||
public isTree = false
|
||||
public type: TopicDataType = 'json'
|
||||
|
||||
private cachedPath?: string
|
||||
private cachedChildTopics?: Array<TreeNode<ViewModel>>
|
||||
@@ -153,7 +156,7 @@ export class TreeNode<ViewModel extends Destroyable> {
|
||||
|
||||
public path(): string {
|
||||
if (!this.cachedPath) {
|
||||
return this.branch()
|
||||
this.cachedPath = this.branch()
|
||||
.map(node => node.sourceEdge && node.sourceEdge.name)
|
||||
.filter(name => name !== undefined)
|
||||
.join('/')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Destroyable } from './Destroyable'
|
||||
import { Edge, Tree, TreeNode } from './'
|
||||
import { MqttMessage } from '../../../events'
|
||||
import { Base64Message } from './Base64Message'
|
||||
|
||||
export abstract class TreeNodeFactory {
|
||||
private static messageCounter = 0
|
||||
@@ -30,7 +31,8 @@ export abstract class TreeNodeFactory {
|
||||
mqttMessage.retain
|
||||
node.setMessage({
|
||||
...mqttMessage,
|
||||
length: mqttMessage.payload?.length ?? 0,
|
||||
payload: mqttMessage.payload && new Base64Message(mqttMessage.payload?.base64Message),
|
||||
length: mqttMessage.payload?.base64Message.length ?? 0,
|
||||
received: receiveDate,
|
||||
messageNumber: this.messageCounter,
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export { Edge } from './Edge'
|
||||
export { TreeNode } from './TreeNode'
|
||||
export { TreeNode, TopicDataType } from './TreeNode'
|
||||
export { Message } from './Message'
|
||||
export { TreeNodeFactory } from './TreeNodeFactory'
|
||||
export { Tree } from './Tree'
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { Base64Message } from './Base64Message'
|
||||
import { Decoder } from './Decoder'
|
||||
import { get } from 'sparkplug-payload'
|
||||
var sparkplug = get("spBv1.0")
|
||||
|
||||
export const SparkplugDecoder = {
|
||||
decode(input: Buffer): Base64Message {
|
||||
try {
|
||||
const message = Base64Message.fromString(JSON.stringify(
|
||||
// @ts-ignore
|
||||
sparkplug.decodePayload(new Uint8Array(input)))
|
||||
)
|
||||
message.decoder = Decoder.SPARKPLUG
|
||||
return message
|
||||
} catch {
|
||||
const message = Base64Message.fromString("Failed to decode sparkplugb payload")
|
||||
message.decoder = Decoder.NONE
|
||||
return message
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'mocha'
|
||||
|
||||
import { expect } from 'chai'
|
||||
import { Base64Message } from '../Base64Message'
|
||||
import { makeTreeNode } from './makeTreeNode'
|
||||
|
||||
describe('TreeNode', () => {
|
||||
@@ -14,7 +13,7 @@ describe('TreeNode', () => {
|
||||
it('updateWithNode should update value', () => {
|
||||
const topics = 'foo/bar'.split('/')
|
||||
const leaf = makeTreeNode('foo/bar', '3')
|
||||
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
|
||||
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
|
||||
|
||||
const updateLeave = makeTreeNode('foo/bar', '5')
|
||||
|
||||
@@ -22,13 +21,13 @@ describe('TreeNode', () => {
|
||||
root.updateWithNode(updateLeave.firstNode())
|
||||
|
||||
expect(root.sourceEdge).to.eq(undefined)
|
||||
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('5')
|
||||
expect(leaf.message!.payload!.toUnicodeString()).to.eq('5')
|
||||
})
|
||||
|
||||
it('updateWithNode should update intermediate nodes', () => {
|
||||
const topics1 = 'foo/bar/baz'.split('/')
|
||||
const leaf = makeTreeNode('foo/bar/baz', '3')
|
||||
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
|
||||
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
|
||||
|
||||
const topics2 = 'foo/bar'.split('/')
|
||||
const updateLeave = makeTreeNode('foo/bar', '5')
|
||||
@@ -37,10 +36,10 @@ describe('TreeNode', () => {
|
||||
|
||||
const barNode = leaf.firstNode().findNode('foo/bar')
|
||||
expect(barNode && barNode.sourceEdge && barNode.sourceEdge.name).to.eq('bar')
|
||||
expect(Base64Message.toUnicodeString(barNode!.message!.payload!)).to.eq('5')
|
||||
expect(barNode!.message!.payload!.toUnicodeString()).to.eq('5')
|
||||
|
||||
expect(leaf.sourceEdge && leaf.sourceEdge.name).to.eq('baz')
|
||||
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
|
||||
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
|
||||
})
|
||||
|
||||
it('updateWithNode should add nodes to the tree', () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'mocha'
|
||||
import { expect } from 'chai'
|
||||
import { Base64Message } from '../Base64Message'
|
||||
import { makeTreeNode } from './makeTreeNode'
|
||||
|
||||
describe('TreeNodeFactory', () => {
|
||||
@@ -20,7 +19,7 @@ describe('TreeNodeFactory', () => {
|
||||
|
||||
expect(node).to.not.eq(undefined)
|
||||
expect(node.sourceEdge.name).to.eq('bar')
|
||||
expect(Base64Message.toUnicodeString(node.message.payload!)).to.eq('5')
|
||||
expect(node.message.payload!.toUnicodeString()).to.eq('5')
|
||||
|
||||
const foo = node.firstNode().findNode('foo')
|
||||
expect(foo && foo.sourceEdge && foo.sourceEdge.name).to.eq('foo')
|
||||
@@ -34,7 +33,7 @@ describe('TreeNodeFactory', () => {
|
||||
return
|
||||
}
|
||||
|
||||
expect(Base64Message.toUnicodeString(node.message.payload!)).to.eq('5')
|
||||
expect(node.message.payload!.toUnicodeString()).to.eq('5')
|
||||
expect(node.sourceEdge.name).to.eq('baz')
|
||||
|
||||
const barNode = node.sourceEdge.source
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
makePublishEvent,
|
||||
removeConnection,
|
||||
} from '../../events'
|
||||
import { SparkplugDecoder } from './Model/sparkplugb'
|
||||
|
||||
export class ConnectionManager {
|
||||
private connections: { [s: string]: DataSource<any> } = {}
|
||||
@@ -48,12 +47,7 @@ export class ConnectionManager {
|
||||
}
|
||||
|
||||
let decoded_payload = null
|
||||
// spell-checker: disable-next-line
|
||||
if (topic.match(/^spBv1\.0\/[^/]+\/[ND](DATA|CMD|DEATH|BIRTH)\/[^/]+(\/[^/]+)?$/u)) {
|
||||
decoded_payload = SparkplugDecoder.decode(buffer)
|
||||
} else {
|
||||
decoded_payload = Base64Message.fromBuffer(buffer)
|
||||
}
|
||||
decoded_payload = Base64Message.fromBuffer(buffer)
|
||||
|
||||
backendEvents.emit(messageEvent, {
|
||||
topic,
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
import { Base64Message } from '../backend/src/Model/Base64Message'
|
||||
import { Base64MessageDTO } from '../backend/src/Model/Base64Message'
|
||||
import { DataSourceState, MqttOptions } from '../backend/src/DataSource'
|
||||
import { UpdateInfo } from 'builder-util-runtime'
|
||||
import { RpcEvent } from './EventSystem/Rpc'
|
||||
@@ -32,7 +32,7 @@ export const updateAvailable: Event<UpdateInfo> = {
|
||||
|
||||
export interface MqttMessage {
|
||||
topic: string
|
||||
payload: Base64Message | null
|
||||
payload: Base64MessageDTO | null
|
||||
qos: 0 | 1 | 2
|
||||
retain: boolean
|
||||
// Set if QoS is > 0 on received messages
|
||||
|
||||
+2
-3
@@ -19,7 +19,8 @@ registerCrashReporter()
|
||||
// const electronTelemetry = electronTelemetryFactory('9b0c8ca04a361eb8160d98c5', buildOptions)
|
||||
// }
|
||||
|
||||
app.commandLine.appendSwitch('--no-sandbox')
|
||||
// disable-dev-shm-usage is required to run the debug console
|
||||
app.commandLine.appendSwitch('--no-sandbox --disable-dev-shm-usage')
|
||||
app.whenReady().then(() => {
|
||||
backendRpc.on(makeOpenDialogRpc(), async request => {
|
||||
return dialog.showOpenDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
|
||||
@@ -69,8 +70,6 @@ async function createWindow() {
|
||||
}
|
||||
})
|
||||
|
||||
console.log('icon path', iconPath)
|
||||
|
||||
// Load the index.html of the app.
|
||||
if (isDev()) {
|
||||
mainWindow.loadURL('http://localhost:8080')
|
||||
|
||||
@@ -36,6 +36,14 @@ process.on('unhandledRejection', (error: Error | any) => {
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
setTimeout(
|
||||
() => {
|
||||
console.error('Timeout reached')
|
||||
process.exit(1)
|
||||
},
|
||||
60 * 10 * 1000
|
||||
)
|
||||
|
||||
const runningUiTestOnCi = os.platform() === 'darwin' ? [] : ['--runningUiTestOnCi']
|
||||
|
||||
async function doStuff() {
|
||||
@@ -143,10 +151,17 @@ async function doStuff() {
|
||||
await sleep(3000)
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
console.log('Forced quit')
|
||||
process.exit(0)
|
||||
}, 10 * 1000)
|
||||
stopMqtt()
|
||||
console.log('Stopped mqtt client')
|
||||
|
||||
cleanUp(scenes, electronApp)
|
||||
|
||||
// Force exit since there appear to be open handles
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
doStuff()
|
||||
|
||||
+6
-12
@@ -9,15 +9,11 @@
|
||||
"moduleResolution": "node",
|
||||
"sourceRoot": "src/",
|
||||
"target": "ES2017",
|
||||
"lib": [
|
||||
"es2017",
|
||||
"dom"
|
||||
],
|
||||
"lib": ["ES2017", "dom"],
|
||||
"sourceMap": true,
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"skipLibCheck": true
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": [
|
||||
"src/electron.ts",
|
||||
@@ -26,7 +22,5 @@
|
||||
"src/spec/leakTest.ts",
|
||||
"scripts/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
||||
@@ -6769,7 +6769,16 @@ stream-shift@^1.0.2:
|
||||
resolved "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz"
|
||||
integrity sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==
|
||||
|
||||
"string-width-cjs@npm:string-width@^4.2.0", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
|
||||
"string-width-cjs@npm:string-width@^4.2.0":
|
||||
version "4.2.3"
|
||||
resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz"
|
||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||
dependencies:
|
||||
emoji-regex "^8.0.0"
|
||||
is-fullwidth-code-point "^3.0.0"
|
||||
strip-ansi "^6.0.1"
|
||||
|
||||
string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
|
||||
version "4.2.3"
|
||||
resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz"
|
||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||
@@ -6839,7 +6848,7 @@ string_decoder@~1.1.1:
|
||||
dependencies:
|
||||
safe-buffer "~5.1.0"
|
||||
|
||||
"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1:
|
||||
"strip-ansi-cjs@npm:strip-ansi@^6.0.1":
|
||||
version "6.0.1"
|
||||
resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz"
|
||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||
@@ -6853,6 +6862,13 @@ strip-ansi@^3.0.0:
|
||||
dependencies:
|
||||
ansi-regex "^2.0.0"
|
||||
|
||||
strip-ansi@^6.0.0, strip-ansi@^6.0.1:
|
||||
version "6.0.1"
|
||||
resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz"
|
||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||
dependencies:
|
||||
ansi-regex "^5.0.1"
|
||||
|
||||
strip-ansi@^7.0.1, strip-ansi@^7.1.0:
|
||||
version "7.1.0"
|
||||
resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz"
|
||||
@@ -7544,7 +7560,7 @@ workerpool@6.2.1:
|
||||
resolved "https://registry.npmjs.org/workerpool/-/workerpool-6.2.1.tgz"
|
||||
integrity sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw==
|
||||
|
||||
"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0:
|
||||
"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0":
|
||||
version "7.0.0"
|
||||
resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz"
|
||||
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
||||
@@ -7562,6 +7578,15 @@ wrap-ansi@^6.2.0:
|
||||
string-width "^4.1.0"
|
||||
strip-ansi "^6.0.0"
|
||||
|
||||
wrap-ansi@^7.0.0:
|
||||
version "7.0.0"
|
||||
resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz"
|
||||
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
||||
dependencies:
|
||||
ansi-styles "^4.0.0"
|
||||
string-width "^4.1.0"
|
||||
strip-ansi "^6.0.0"
|
||||
|
||||
wrap-ansi@^8.1.0:
|
||||
version "8.1.0"
|
||||
resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz"
|
||||
|
||||
Reference in New Issue
Block a user