Compare commits

..
Author SHA1 Message Date
Thomas Nordquist 03c5639417 Delete MCP_INTROSPECTION.md 2025-12-19 21:30:04 +01:00
copilot-swe-agent[bot]andthomasnordquist e0b2dcec0e Add test independence requirement and remove duplicate content from MCP_INTROSPECTION.md
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 20:25:56 +00:00
copilot-swe-agent[bot]andthomasnordquist 0a3dfd0b34 Fix workflow caching logic and remove hardcoded version from instructions
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 20:15:44 +00:00
copilot-swe-agent[bot]andthomasnordquist d91633a583 Simplify MCP implementation: remove unnecessary files, add Copilot agent instructions and yarn caching workflow
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 20:14:04 +00:00
copilot-swe-agent[bot]andthomasnordquist a5f908dedd Refactor test script to use constants and robust path resolution
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 19:58:25 +00:00
copilot-swe-agent[bot]andthomasnordquist 69d0d6356c Add MCP introspection test, screenshots, and improve documentation for agentic development
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 19:56:23 +00:00
copilot-swe-agent[bot]andthomasnordquist 7a99aeb2d1 Improve port argument validation to handle malformed arguments
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 19:42:33 +00:00
copilot-swe-agent[bot]andthomasnordquist 463c44dac9 Fix code review issues: add port validation and improve example script
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 19:41:26 +00:00
copilot-swe-agent[bot]andthomasnordquist 5a77542993 Fix prettier formatting in electron.ts and add verification script
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 19:39:56 +00:00
copilot-swe-agent[bot]andthomasnordquist 0046656134 Add MCP introspection support for Electron frontend with Playwright integration
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-19 19:35:14 +00:00
copilot-swe-agent[bot] 2d8b976e33 Initial plan 2025-12-19 19:26:24 +00:00
Thomas Nordquist 803413a087 Merge pull request #897 from scubanarc/license
Update license to CC by-nd
2025-08-22 21:19:01 +02:00
Jason Bauer b457559b4a Update license 2025-08-21 12:54:21 -07:00
Björn Dalfors 03ba43038c Merge pull request #812 from thomasnordquist/chore/fix-broken-test-locators
fix broken test locators
2024-06-17 09:31:25 +00:00
Björn Dalfors 8975e7b641 Merge pull request #813 from thomasnordquist/chore/dont-use-pull-request-target-for-untrusted-code
dont use pull_request_target as it opens the repo for pwnage..
2024-06-17 09:30:23 +00:00
Björn Dalfors efc9fb9736 dont use pull_request_target as it opens the repo for pwnage.. 2024-06-17 11:25:07 +02:00
Björn Dalfors 61f2389c1c fix broken test locators 2024-06-17 10:01:34 +02:00
Thomas Nordquist f539e03c7e Merge pull request #801 from thomasnordquist/feat/set-payload-from-file
feat: support save and load payload from file
2024-06-02 08:35:53 +02:00
Thomas Nordquist 724ea5acbf Merge pull request #804 from thomasnordquist/chore/add-sparkplug-to-demovideo
add sparkplug decoding to demo video
2024-06-02 08:34:48 +02:00
Björn Dalfors e009940530 fix inputs not being cleared 2024-06-01 22:24:41 +02:00
Björn Dalfors e19178780f add sparkplug decoding to demo video 2024-06-01 22:24:41 +02:00
Björn Dalfors 3229ef5643 Chore/fix workflow sha (#807)
* checkout merge commit of PR, not base branch head

https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target

* use link to test result, gif exceeds github allowed content length
2024-06-01 22:23:25 +02:00
Björn Dalfors b4a6199936 Move file operation to backend 2024-05-29 10:02:00 +02:00
Björn Dalfors bd6a1a0d2d Support specifying file encoding 2024-05-29 10:01:32 +02:00
Björn Dalfors 9d09ab2165 move filesystem operation to backend 2024-05-27 22:09:12 +02:00
Björn Dalfors f17640c9db feat: save value to file 2024-05-27 22:09:12 +02:00
Björn Dalfors 1ba0d07757 feat: support set payload from file when publishing 2024-05-27 22:09:12 +02:00
Thomas Nordquist 20a3202b5f Merge pull request #802 from thomasnordquist/tnordquist/fix-hot-reload
chore: fix webpack reload
2024-05-27 18:06:08 +02:00
Thomas Nordquist 28b99f5774 chore: fix webpack reload 2024-05-27 18:05:24 +02:00
Thomas Nordquist 42565c8bdc chore: coerce ui-test to end 2024-05-27 10:07:23 +02:00
Thomas Nordquist 8b43e20f2e Merge pull request #795 from thomasnordquist/tnordquist/decode-data-in-frontend
decode data in frontend
2024-05-25 16:28:53 +02:00
Thomas Nordquist a2a75588c9 Merge pull request #799 from thomasnordquist/tnordquist/allow-to-connect-with-double-click
feat: connect with double-click
2024-05-25 16:28:37 +02:00
Thomas Nordquist c13b60cd18 Merge pull request #800 from thomasnordquist/tnordquist/fix-eclipse-server
chore: update eclipse server url
2024-05-25 16:27:55 +02:00
Thomas Nordquist 18f8da9054 test: fix demo video 2024-05-24 22:29:49 +02:00
Thomas Nordquist f6856d66cc chore: update eclipse server url 2024-05-24 22:27:24 +02:00
Thomas Nordquist 79fbd34cfa feat: connect with double-click 2024-05-24 22:23:26 +02:00
Thomas Nordquist 3bc23e6d74 test: fix demo video 2024-05-24 22:01:13 +02:00
Thomas Nordquist e9a56ac48d Merge remote-tracking branch 'origin/master' into tnordquist/decode-data-in-frontend 2024-05-24 17:51:24 +02:00
Björn Dalfors b4bdd01808 add sparkplug messages to demovideo 2024-05-24 17:50:08 +02:00
Björn Dalfors 4406bf5de4 feat: use tahu for sparkplug decoding 2024-05-24 17:50:07 +02:00
Thomas Nordquist ae0ce79e26 Merge pull request #794 from thomasnordquist/feat/use-tahu-for-sparkplug-decoding
Feat/use tahu for sparkplug decoding
2024-05-24 10:12:21 +02:00
Thomas Nordquist bbe2ae3f29 test: fix tests 2024-05-23 23:19:37 +02:00
Thomas Nordquist a2c4388c78 fix: repair types 2024-05-23 17:05:27 +02:00
Thomas Nordquist c88978f0dd fix: fix ui updates 2024-05-22 15:12:45 +02:00
Thomas Nordquist b3a37e4794 chore: refactor 2024-05-22 14:44:06 +02:00
Thomas Nordquist 1ecb53b397 fix: update react when decoder has been overriden 2024-05-22 09:04:06 +02:00
Björn Dalfors 97fedcba08 fix sparkplug topic regexp 2024-05-21 15:26:43 +02:00
Björn Dalfors 1f23c65484 Stop click event propagation prevent panel from collapsing 2024-05-21 15:17:18 +02:00
Thomas Nordquist 980072f680 chore: decode data in frontend 2024-05-21 09:22:11 +02:00
Björn Dalfors c452b9f417 add sparkplug messages to demovideo 2024-05-20 16:42:54 +02:00
Björn Dalfors b04f5dee16 feat: use tahu for sparkplug decoding 2024-05-18 21:48:14 +02:00
Björn Dalfors 7617430a3f fix regex 2024-05-18 21:42:25 +02:00
Thomas Nordquist 10aae59c92 Merge remote-tracking branch 'fb/multi-decoder/master' into feat/use-tahu-for-sparkplug-decoding 2024-05-18 11:26:39 +02:00
Björn Dalfors f4bda3e242 feat: use tahu for sparkplug decoding 2024-05-17 16:14:32 +02:00
Björn Dalfors a346c48d3e refine sparkplug detection 2024-05-17 09:08:34 +02:00
Björn Dalfors 8a2c39ba8e fix: use sparkplugb decoder only for spBv1.0 topic 2024-05-15 15:24:30 +02:00
Thomas Nordquist 65b86ac5f6 chore: remove precondition 2024-05-11 21:55:11 +02:00
Thomas Nordquist 4ead740982 chore: allow manual update of website 2024-05-11 21:54:20 +02:00
Thomas Nordquist ddaf06b682 chore: remove precondition 2024-05-11 21:51:38 +02:00
Thomas Nordquist 9e18c4db4e chore: prevent new builds being uploaded without a release 2024-05-11 21:49:27 +02:00
Thomas Nordquist ee783f15c0 chore: move website update to separate release action 2024-05-11 21:44:28 +02:00
Thomas Nordquist 0c31843ed5 chore: reduce builds 2024-05-11 21:29:53 +02:00
Thomas Nordquist ffc93d20d8 chore: retry release beta 5 2024-05-11 21:17:47 +02:00
Thomas Nordquist 3c62da7e19 chore: only build macos dmg 2024-05-11 21:12:27 +02:00
Thomas Nordquist 6846dbbb28 chore: update website with new version 2024-05-11 21:10:57 +02:00
semantic-release-bot 270e3e3ead chore(release): 0.4.0-beta.5 [skip ci] 2024-05-11 15:47:26 +00:00
Thomas Nordquist 0d73b0f519 feat: test to trigger beta release 5 2024-05-11 17:46:23 +02:00
semantic-release-bot ee83022d19 chore(release): 0.4.0-beta.4 [skip ci] 2024-05-11 15:35:58 +00:00
Thomas Nordquist f27467ed97 fix: add macos 2024-05-11 17:34:48 +02:00
semantic-release-bot ddbf3d9f1f chore(release): 0.4.0-beta.3 [skip ci] 2024-05-11 14:19:25 +00:00
Thomas Nordquist 60bbbc54d7 chore: use GithubApp to bypass branch protection 2024-05-11 16:07:16 +02:00
Thomas Nordquist 538aa7dc29 chore: use custom token fo releases 2024-05-11 15:31:08 +02:00
Thomas Nordquist b37af291cc feat: skip package release until github and semantic-release are in sync 2024-05-11 14:42:17 +02:00
Thomas Nordquist 333a1bcabe fix: fix repository 2024-05-11 14:39:34 +02:00
Thomas Nordquist c2404a7eb6 Merge pull request #779 from thomasnordquist/dependabot/npm_and_yarn/ejs-3.1.10
Bump ejs from 3.1.9 to 3.1.10
2024-05-11 12:18:00 +02:00
dependabot[bot] bb602cd28e Bump ejs from 3.1.9 to 3.1.10
Bumps [ejs](https://github.com/mde/ejs) from 3.1.9 to 3.1.10.
- [Release notes](https://github.com/mde/ejs/releases)
- [Commits](https://github.com/mde/ejs/compare/v3.1.9...v3.1.10)

---
updated-dependencies:
- dependency-name: ejs
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-11 10:11:20 +00:00
Thomas Nordquist 898fd3896c Merge pull request #786 from thomasnordquist/tnordquist/test-ci
chore: add ci / cd piplelines as github actions
2024-05-11 12:10:36 +02:00
Thomas Nordquist 7fb0483889 chore: document release 2024-05-11 12:03:01 +02:00
Thomas Nordquist 7d77110c1f chore: upload test video as test artifact 2024-05-11 11:00:31 +02:00
Thomas Nordquist a7ce6b4419 chore: upload test video as test artifact 2024-05-10 22:30:02 +02:00
Thomas Nordquist 204f6dbcde chore: fix docker context 2024-05-10 22:17:39 +02:00
Thomas Nordquist 7fa997087f chore: build docker test image 2024-05-10 21:15:04 +02:00
semantic-release-bot a96b08eaaa chore(release): 0.4.0-beta.2 [skip ci] 2024-05-10 18:12:27 +00:00
Thomas Nordquist c9c997d13a fix: trigger build 2024-05-10 20:04:31 +02:00
semantic-release-bot 6f3e0f62e1 chore(release): 0.4.0-beta.1 [skip ci] 2024-05-10 18:03:44 +00:00
Thomas Nordquist 824b39637c chore: use newer node version 2024-05-10 19:56:01 +02:00
Thomas Nordquist 0100b2988a chore: dry-run 2024-05-10 18:52:25 +02:00
Thomas Nordquist 0e72329c77 fix: update semantic-release 2024-05-10 18:48:38 +02:00
Thomas Nordquist 9b7c3b8e9c feat: use semantic-release 2024-05-10 18:46:06 +02:00
Thomas Nordquist b9a5a5f1d8 add semantic release 2024-05-10 18:05:41 +02:00
Thomas Nordquist cc9cc411f0 skip osx builds for now 2024-05-10 17:50:07 +02:00
Thomas Nordquist 5f75079f2f add workflows 2024-05-10 17:44:23 +02:00
Björn Dalfors a6e16dcd17 Merge pull request #772 from thomasnordquist/chore/fix-spellchecker
upgrade cspell and fix spelling issues
2024-05-02 12:58:52 +02:00
Björn Dalfors f1b13a2919 upgrade cspell and fix spelling issues 2024-04-10 09:14:12 +02:00
Björn Dalfors 737afb3c1b Merge pull request #773 from thomasnordquist/chore/replace-spectron-with-playwright
Chore/replace spectron with playwright
2024-04-10 09:07:32 +02:00
Björn Dalfors e21011fce1 use --frozen-lockfile to ensure dependency integrity across builds 2024-04-08 10:46:22 +02:00
Björn Dalfors 613d0d7178 fix test script and video capture 2024-04-08 10:14:44 +02:00
Björn Dalfors bb964aba20 replace file-loader with assets to get demo mouse working again
fix mouse pointer
2024-04-06 21:19:18 +02:00
Björn Dalfors 6e5e2e0dd7 replace deprecated spectron with playwright 2024-04-05 14:35:18 +02:00
Björn Dalfors 5afccac2ac bump version 2024-04-03 17:32:57 +02:00
Björn Dalfors 4626df0bf7 Merge pull request #771 from thomasnordquist/chore/upgrade-mocha
upgrade mocha, remove deprecated mochaopts
2024-04-03 08:07:52 +01:00
Björn Dalfors 252780a51a upgrade mocha, remove deprecated mochaopts 2024-04-03 00:03:52 +02:00
Björn Dalfors 245e661159 remove accedentally added dependency 2024-04-03 00:02:38 +02:00
Björn Dalfors 659033e4eb Merge pull request #769 from thomasnordquist/dependabot/npm_and_yarn/app/webpack-dev-middleware-5.3.4
Bump webpack-dev-middleware from 5.3.3 to 5.3.4 in /app
2024-04-02 21:06:19 +01:00
dependabot[bot] 82fbf91f8a Bump webpack-dev-middleware from 5.3.3 to 5.3.4 in /app
Bumps [webpack-dev-middleware](https://github.com/webpack/webpack-dev-middleware) from 5.3.3 to 5.3.4.
- [Release notes](https://github.com/webpack/webpack-dev-middleware/releases)
- [Changelog](https://github.com/webpack/webpack-dev-middleware/blob/v5.3.4/CHANGELOG.md)
- [Commits](https://github.com/webpack/webpack-dev-middleware/compare/v5.3.3...v5.3.4)

---
updated-dependencies:
- dependency-name: webpack-dev-middleware
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 19:24:03 +00:00
Björn Dalfors 4275060003 upgrade protobufjs due cve 2024-04-02 21:21:46 +02:00
Björn Dalfors 6fe74d49fd Merge pull request #770 from thomasnordquist/dependabot/npm_and_yarn/app/follow-redirects-1.15.6
Bump follow-redirects from 1.15.5 to 1.15.6 in /app
2024-04-02 20:06:39 +01:00
Björn Dalfors 736145d9b4 Merge pull request #421 from jcwillox/patch-1
Simplify config path and increase portability
2024-04-02 19:33:26 +01:00
Björn Dalfors d5ad716086 Merge pull request #767 from thomasnordquist/dependabot/npm_and_yarn/app/express-4.19.2
Bump express from 4.18.3 to 4.19.2 in /app
2024-04-02 19:28:22 +01:00
Björn Dalfors c3f1e7c5e8 Merge pull request #763 from thomasnordquist/dependabot/npm_and_yarn/ua-parser-js-1.0.37
Bump ua-parser-js from 1.0.2 to 1.0.37
2024-04-02 19:27:31 +01:00
Björn Dalfors e1b6c709b0 Merge pull request #708 from thomasnordquist/dependabot/npm_and_yarn/minimist-1.2.8
Bump minimist from 1.2.5 to 1.2.8
2024-04-02 19:26:49 +01:00
dependabot[bot] 42de570a98 Bump follow-redirects from 1.15.5 to 1.15.6 in /app
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.5 to 1.15.6.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.5...v1.15.6)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 18:24:38 +00:00
Björn Dalfors 30469e63e5 Merge pull request #768 from thomasnordquist/chore/upgrade-dependencies-2024
upgrade dependencies
2024-04-02 19:23:07 +01:00
Björn Dalfors 899db30e3b upgrade axios 2024-04-02 19:35:01 +02:00
Björn Dalfors 51d0eaafcc yarn upgrade 2024-04-02 17:03:29 +02:00
dependabot[bot] cfd1333989 Bump express from 4.18.3 to 4.19.2 in /app
Bumps [express](https://github.com/expressjs/express) from 4.18.3 to 4.19.2.
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.18.3...4.19.2)

---
updated-dependencies:
- dependency-name: express
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 14:43:11 +00:00
dependabot[bot] 6c9d98a763 Bump ua-parser-js from 1.0.2 to 1.0.37
Bumps [ua-parser-js](https://github.com/faisalman/ua-parser-js) from 1.0.2 to 1.0.37.
- [Release notes](https://github.com/faisalman/ua-parser-js/releases)
- [Changelog](https://github.com/faisalman/ua-parser-js/blob/1.0.37/changelog.md)
- [Commits](https://github.com/faisalman/ua-parser-js/compare/1.0.2...1.0.37)

---
updated-dependencies:
- dependency-name: ua-parser-js
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 14:39:11 +00:00
dependabot[bot] 040549c40a Bump minimist from 1.2.5 to 1.2.8
Bumps [minimist](https://github.com/minimistjs/minimist) from 1.2.5 to 1.2.8.
- [Release notes](https://github.com/minimistjs/minimist/releases)
- [Changelog](https://github.com/minimistjs/minimist/blob/main/CHANGELOG.md)
- [Commits](https://github.com/minimistjs/minimist/compare/v1.2.5...v1.2.8)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 14:38:09 +00:00
Björn Dalfors 0c6d777999 Merge pull request #757 from thomasnordquist/chore/upgrade-electron
Chore/upgrade electron
2024-04-02 15:34:34 +01:00
Björn Dalfors 65c53fd670 use node 18 to support github electron-builder action 2024-04-02 16:17:40 +02:00
Björn Dalfors 1b7c9c52f6 move sparkplug protocol to js file as file is not included when packaging
maybe there is a better way to resolve this..
2024-04-02 13:16:34 +02:00
mhorsche 626b9cab7d Specific int/uint byte size
- possible data types are: 'json', 'string', 'hex', 'uint8', 'uint16', 'uint32', 'uint64', 'int8', 'int16', 'int32', 'int64', 'float', 'double'
- default is 'json'
2022-06-21 21:14:59 +02:00
Max Horsche 567f6d2d50 Added support for binary data types
- Select data type (string, json, hex, uint, int, float) for each topic individually
- Default data type is 'string'
- Show milliseconds in message received timestamp
2021-01-11 10:11:34 +01:00
Josh Willox 3fa47f0318 Simplify config path 2020-08-10 19:35:46 +10:00
108 changed files with 7406 additions and 3814 deletions
+13 -7
View File
@@ -1,4 +1,11 @@
{
"import": [
"@cspell/dict-typescript/cspell-ext.json"
],
"ignoreRegExpList": [
"import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t\\{\\},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*\\{(?:[ \\n\\t]*[^ \\n\\t\"'\\{\\}]+[ \\n\\t]*,?)+\\})?[ \\n\\t]*)|[ \n\\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t\\{\\}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])\n",
"^import\\s+(['\"]).*\\1$"
],
"language": "en",
"words": [
"Bbreak",
@@ -8,15 +15,13 @@
"nowrap",
"subheader",
"basepath",
"webdriverio",
"repo",
"hexagonalize",
"pixelize",
"Transistions",
"squashfs",
"squashfs",
"provisionprofile",
"Nsis",
"webdriverio",
"Appx",
"Hashable",
"clickaway",
@@ -26,8 +31,6 @@
"Monokai",
"plottable",
"snackbar",
"webdriverio",
"prismjs",
"Nordquist",
"debounced",
"mosquitto",
@@ -47,6 +50,9 @@
"mixins",
"Explorerdmg",
"heapsnapshot",
"noconflict"
"noconflict",
"sparkplugb",
"protojson",
"typesafe"
]
}
}
+3
View File
@@ -0,0 +1,3 @@
package.ts @thomasnordquist
.github @thomasnordquist
scripts @thomasnordquist
+105
View File
@@ -0,0 +1,105 @@
# GitHub Copilot Agent Instructions for MQTT Explorer
## Project Setup
### Building and Running
```bash
# Install dependencies
yarn install
# Build the project
yarn build
# Start the application
yarn start
# Start in development mode
yarn dev
```
### Running with MCP Introspection (for testing)
```bash
# Build first
yarn build
# Start with MCP introspection enabled
electron . --enable-mcp-introspection
# Or with custom port
electron . --enable-mcp-introspection --remote-debugging-port=9223
```
## Writing Tests
### Requirements for All Tests
1. **Tests MUST be deterministic** - They should produce the same results every time they run
2. **Tests MUST be independent** - Each test should be able to run in isolation without depending on other tests
3. **Include screenshots** - Visual verification is required for UI changes
4. **Handle asynchronous operations properly** - This is an MQTT message queue tool
### Handling MQTT Asynchronous Operations
MQTT is inherently asynchronous. When writing tests:
- **Wait for message propagation**: Use proper wait strategies (e.g., `await page.waitForSelector()`, `await sleep()`)
- **Don't assume immediate updates**: Messages take time to send, receive, and update the UI
- **Use event-based waiting**: Wait for specific UI elements or state changes rather than fixed timeouts when possible
- **Account for network latency**: MQTT broker communication involves network round trips
### Example Test Pattern
```typescript
// 1. Perform action (e.g., publish message)
await publishMessage(topic, payload)
// 2. Wait for UI to update (not just arbitrary sleep)
await page.waitForSelector(`text="${expectedValue}"`, { timeout: 5000 })
// 3. Verify state
const value = await page.textContent('.message-value')
expect(value).toBe(expectedValue)
// 4. Take screenshot for verification
await page.screenshot({ path: 'test-result.png' })
```
### Running Tests
```bash
# Run all tests
yarn test
# Run specific test suites
yarn test:app
yarn test:backend
yarn test:mcp
# Run linters
yarn lint
yarn lint:fix
```
## MCP Introspection Testing
The project supports MCP (Model Context Protocol) for automated testing with Playwright:
- Use `yarn test:mcp` to run automated UI tests
- Tests launch the app with remote debugging enabled on port 9222
- Connect to `http://localhost:9222` via Chrome DevTools Protocol
## Project Structure
- `app/` - Frontend React application
- `backend/` - Backend models, tests, and connection management
- `src/` - Electron main process and bindings
- `src/spec/` - Test specifications including MCP introspection tests
## Important Notes
- Always run `yarn build` before starting the application
- The app uses Electron (see `package.json` for version)
- MQTT communication is handled via [mqttjs](https://github.com/mqttjs/MQTT.js)
- All code changes should pass linting (`yarn lint`)
+29
View File
@@ -0,0 +1,29 @@
on:
push:
branches:
- master
- release
- beta
paths:
- Dockerfile
- .github
jobs:
create-image:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest
+39
View File
@@ -0,0 +1,39 @@
name: Copilot Agent Setup
on:
workflow_call:
jobs:
setup:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
- name: Cache yarn dependencies
uses: actions/cache@v4
id: yarn-cache
with:
path: |
${{ steps.yarn-cache-dir-path.outputs.dir }}
node_modules
app/node_modules
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Build project
run: yarn build
+53
View File
@@ -0,0 +1,53 @@
name: Build
on:
push:
branches:
- release
- beta
concurrency:
group: ${{ github.ref }}
cancel-in-progress: false
jobs:
build:
strategy:
matrix:
build:
- os: ubuntu-latest
task: linux
- os: windows-latest
task: win
- os: macos-latest
task: mac
runs-on: ${{ matrix.build.os }}
steps:
- if: matrix.build.os == 'ubuntu-latest'
run: sudo snap install snapcraft --classic
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install -g yarn
- run: yarn
- id: create_token # get ReleaseBot access token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.RELEASE_BOT_APP_ID }}
private_key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}
- name: Semantic Release
uses: cycjimmy/semantic-release-action@v4
id: semantic # Need an `id` for output variables
env:
GITHUB_TOKEN: ${{ steps.create_token.outputs.token }}
- run: yarn build
if: steps.semantic.outputs.new_release_published == 'true'
- run: yarn prepare-release
if: steps.semantic.outputs.new_release_published == 'true'
- run: yarn package ${{ matrix.build.task }}
if: steps.semantic.outputs.new_release_published == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
+38
View File
@@ -0,0 +1,38 @@
on:
pull_request_target: # Use pull_request_target
branches: [master, beta, release]
jobs:
test:
runs-on: ubuntu-latest
container:
image: ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest
volumes:
- ./:/app
options: --user root
steps:
- uses: actions/checkout@v4
- name: Install Packages
run: yarn install --frozen-lockfile
- name: Build
run: yarn build
- name: Test
run: yarn test
- name: UI-Test
run: yarn ui-test
- name: Post-processing
run: ./scripts/prepareVideo.sh
- uses: hkusu/s3-upload-action@v2
id: upload # specify some ID for use in subsequent steps
with:
aws-access-key-id: ${{ vars.AWS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: 'eu-central-1'
aws-bucket: ${{ vars.AWS_BUCKET }}
file-path: './ui-test.gif'
content-type: image/gif
output-file-url: 'true'
- name: Show URL
run: echo '${{ steps.upload.outputs.file-url }}'
id: artifact-upload-step
- run: echo '<picture><img src="${{ steps.upload.outputs.file-url }}"></picture>' >> $GITHUB_STEP_SUMMARY
+17
View File
@@ -0,0 +1,17 @@
name: Update Website
on: [release, workflow_dispatch]
jobs:
update-website:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: gh-pages
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install
- run: npm run readme
- uses: stefanzweifel/git-auto-commit-action@v5
+5
View File
@@ -9,3 +9,8 @@ test.png
.awcache
.scannerwork
screen*.png
# MCP introspection artifacts
mqtt-explorer-mcp-screenshot.png
screenshot-mcp-*.png
test-mcp-introspection.js
-1
View File
@@ -1 +0,0 @@
engine-strict=true
+30
View File
@@ -0,0 +1,30 @@
{
"branches": [
"release",
{
"name": "beta",
"prerelease": true
}
],
repositoryUrl: "git@github.com:thomasnordquist/MQTT-Explorer.git",
"plugins": [
"@semantic-release/commit-analyzer",
"semantic-release-export-data",
"@semantic-release/changelog",
[
"@semantic-release/npm",
{
"npmPublish": false
}
],
[
"@semantic-release/git",
{
"assets": [
"package.json",
"yarn.lock"
]
}
]
]
}
-46
View File
@@ -1,46 +0,0 @@
language: node_js
services:
- xvfb
cache:
directories:
- node_modules
- $HOME/.cache/electron
- $HOME/.cache/electron-builder
- $HOME/.npm/_prebuilds
node_js:
- "10"
os:
- linux
- osx
osx_image: xcode10.2
dist: bionic
services:
- docker
install:
- yarn install
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get update && sudo apt-get -y install snap squashfs-tools && sudo snap install snapcraft --classic; fi;
script:
- yarn run build
- yarn lint
- yarn test
- export TRAVIS_BUILD_NUMBER="" # Override travis build number since it is uses for tagging the binary version https://github.com/electron-userland/electron-builder/issues/3730
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then docker run -e GH_TOKEN=$GH_TOKEN -e GIT_TAG=$TRAVIS_TAG --rm -v `pwd`:/app thomasnordquist/ui-test-recording-env sh -c "cd app && docker/testMounted.sh"; fi
- if [[ "$TRAVIS_TAG" != "" ]]; then yarn run prepare-release; fi
- |
if [[ "$TRAVIS_OS_NAME" == "linux" ]] && [[ "$TRAVIS_TAG" != "" ]]; then
openssl aes-256-cbc -d -in res/snapstore-credentials.enc -out credentials -k $SNAPSTORE_CREDENTIALS_DECRYPTION_KEY;
snapcraft login --with credentials;
rm credentials;
yarn run package linux;
fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]] && [[ "$TRAVIS_TAG" != "" ]]; then yarn run package -- mac; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]] && [[ "$TRAVIS_TAG" != "" ]]; then unset CSC_LINK; yarn run package -- win; fi
+2 -3
View File
@@ -1,7 +1,7 @@
FROM node:11-stretch
FROM node:20
RUN DEBIAN_FRONTEND="noninteractive" apt-get update \
&& apt-get install -y --no-install-recommends nano ffmpeg xvfb git-core tmux locales mosquitto x11vnc
&& apt-get install -y --no-install-recommends ca-certificates nano ffmpeg xvfb git-core tmux locales mosquitto x11vnc
RUN apt-get install -yq --no-install-recommends libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 libnss3
# Generate locales for TMUX
@@ -12,6 +12,5 @@ ENV LC_ALL en_US.UTF-8
CMD /bin/bash
COPY cloneBuildAndTest.sh ./
VOLUME /app
EXPOSE 5900
+26 -24
View File
@@ -1,10 +1,8 @@
## creative commons
# Attribution-NoDerivatives 4.0 International
# Creative Commons Attribution-NonCommercial 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
### Using Creative Commons Public Licenses
**Using Creative Commons Public Licenses**
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
@@ -12,31 +10,35 @@ Creative Commons public licenses provide a standard set of terms and conditions
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-NoDerivatives 4.0 International Public License
## Creative Commons Attribution-NonCommercial 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
d. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
e. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
f. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
g. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
h. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
i. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
j. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning.
### Section 2 Scope.
@@ -44,9 +46,9 @@ a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
B. produce and reproduce, but not Share, Adapted Material.
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
@@ -56,9 +58,9 @@ a. ___License grant.___
5. __Downstream recipients.__
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
@@ -68,7 +70,7 @@ b. ___Other rights.___
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
### Section 3 License Conditions.
@@ -76,7 +78,7 @@ Your exercise of the Licensed Rights is expressly made subject to the following
a. ___Attribution.___
1. If You Share the Licensed Material, You must:
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
@@ -94,17 +96,17 @@ a. ___Attribution.___
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database, provided You do not Share Adapted Material;
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
+17 -6
View File
@@ -6,11 +6,12 @@
[![Build status](https://ci.appveyor.com/api/projects/status/c35tkm29rm4m5364/branch/master?svg=true)](https://ci.appveyor.com/project/thomasnordquist/mqtt-explorer/branch/master)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/47b26e03fce543ceac7914214482334a)](https://app.codacy.com/app/thomasnordquist/MQTT-Explorer?utm_source=github.com&utm_medium=referral&utm_content=thomasnordquist/MQTT-Explorer&utm_campaign=Badge_Grade_Dashboard)
| | | |
|:---:|:---:|:---:|
|[![screen_composite](https://mqtt-explorer.com/img/screen-composite_small.png)](https://mqtt-explorer.com/img/screen-composite.png)|[![screen2_small](https://mqtt-explorer.com/img/screen2_small.png)](https://mqtt-explorer.com/img/screen2.png)|[![screen3_small](https://mqtt-explorer.com/img/screen3_small.png)](https://mqtt-explorer.com/img/screen3.png)|
| | | |
| :---------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: |
| [![screen_composite](https://mqtt-explorer.com/img/screen-composite_small.png)](https://mqtt-explorer.com/img/screen-composite.png) | [![screen2_small](https://mqtt-explorer.com/img/screen2_small.png)](https://mqtt-explorer.com/img/screen2.png) | [![screen3_small](https://mqtt-explorer.com/img/screen3_small.png)](https://mqtt-explorer.com/img/screen3.png) |
# The App has moved to [mqtt-explorer.com](https://mqtt-explorer.com)
MQTT Explorer is a comprehensive and easy-to-use MQTT Client.
Downloads can be found at the link above.
@@ -29,6 +30,7 @@ yarn start
## Develop
Launch Application
```bash
npm install -g yarn
yarn
@@ -63,6 +65,15 @@ npm run build
node dist/src/spec/webdriverio.js
```
## Create a release
Create a PR to `release` branch.
There needs to be a "feat: some new feature" or "fix: some bugfix" commit for a new release to be created
## Create a beta release
Create a PR to `beta` branch. A "feat" or "fix" commit is necessary to create a new version.
## Write docs
```
@@ -88,7 +99,7 @@ The readme will be generated from the docs.
## License
![CC-BY-ND 4.0](https://img.shields.io/badge/License-CC%20BY--ND%204.0-blue.svg)
[CC-BY-ND 4.0](https://creativecommons.org/licenses/by-nd/4.0/)
![CC-BY-Nc 4.0](https://img.shields.io/badge/License-CC%20BY--NC%204.0-blue.svg)
[CC-BY-Nc 4.0](https://creativecommons.org/licenses/by-nC/4.0/)
The license is a little restrictive to distributing derived work, this may change in the future if the interest arises or more people work on this project.
The license allows for anyone to adapt, share, and redistribute the material, as long as it is non-commercial.
+8 -8
View File
@@ -7,10 +7,10 @@
"build": "webpack --mode production",
"dev": "node_modules/.bin/webpack-dev-server --mode development --progress",
"test": "cross-env TS_NODE_PROJECT=test/tsconfig.json yarn mochatest",
"mochatest": "mocha --require ts-node/register src/**/*.spec.ts"
"mochatest": "mocha --require ts-node/register --require source-map-support/register --recursive src/*/**/*.spec.ts"
},
"engines": {
"node": "19"
"node": ">=18"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -21,7 +21,7 @@
"@material-ui/styles": "4.11",
"@types/react-transition-group": "^4",
"ace-builds": "^1.4.11",
"axios": "^0.26.0",
"axios": "^0.28.0",
"compare-versions": "^3.5.0",
"copy-text-to-clipboard": "^2.1.0",
"d3": "^5.9.7",
@@ -75,17 +75,17 @@
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"lodash": "^4.17.21",
"mocha": "^9.2.1",
"mocha": "^10.4.0",
"moment": "^2.29.1",
"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 -3
View File
@@ -9,12 +9,11 @@ import {
import { default as persistentStorage, StorageIdentifier } from '../utils/PersistentStorage'
import { Dispatch } from 'redux'
import { showError } from './Global'
import { promises as fsPromise } from 'fs'
import * as path from 'path'
import { ActionTypes, Action } from '../reducers/ConnectionManager'
import { Subscription } from '../../../backend/src/DataSource/MqttSource'
import { connectionsMigrator } from './migrations/Connection'
import { rendererRpc } from '../../../events'
import { rendererRpc, readFromFile } from '../../../events'
import { makeOpenDialogRpc } from '../../../events/OpenDialogRequest'
export interface ConnectionDictionary {
@@ -81,7 +80,7 @@ async function openCertificate(): Promise<CertificateParameters> {
throw rejectReasons.noCertificateSelected
}
const data = await fsPromise.readFile(selectedFile)
const data = await rendererRpc.call(readFromFile, { filePath: selectedFile })
if (data.length > 16_384 || data.length < 64) {
throw rejectReasons.certificateSizeDoesNotMatch
}
+48 -2
View File
@@ -2,7 +2,10 @@ 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, rendererRpc, readFromFile } from '../../../events'
import { makeOpenDialogRpc } from '../../../events/OpenDialogRequest'
import { showError } from './Global'
import { Base64 } from 'js-base64'
export const setTopic = (topic?: string): Action => {
return {
@@ -11,6 +14,49 @@ export const setTopic = (topic?: string): Action => {
}
}
export const openFile = (encoding: 'utf8' = 'utf8') => async (dispatch: Dispatch<any>, getState: () => AppState) => {
try {
const file = await getFileContent(encoding)
if (file) {
dispatch(
setPayload(file.data))
}
} catch (error) {
dispatch(showError(error))
}
}
type FileParameters = {
name: string,
data: string
}
async function getFileContent(encoding: string): Promise<FileParameters | undefined> {
const rejectReasons = {
noFileSelected: 'No file selected',
errorReadingFile: 'Error reading file'
}
const { canceled, filePaths } = await rendererRpc.call(makeOpenDialogRpc(), {
properties: ['openFile'],
securityScopedBookmarks: true,
})
if (canceled) {
return
}
const selectedFile = filePaths[0]
if (!selectedFile) {
throw rejectReasons.noFileSelected
}
try {
const data = await rendererRpc.call(readFromFile, { filePath: selectedFile, encoding })
return { name: selectedFile, data: data.toString(encoding) }
} catch (error) {
throw rejectReasons.errorReadingFile
}
}
export const setPayload = (payload?: string): Action => {
return {
payload,
@@ -41,7 +87,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,
+10 -9
View File
@@ -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)
}
+2 -7
View File
@@ -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>
+20 -1
View File
@@ -1,5 +1,5 @@
import Editor from './Editor'
import FormatAlignLeft from '@material-ui/icons/FormatAlignLeft'
import { AttachFileOutlined, FormatAlignLeft } from '@material-ui/icons'
import Message from './Model/Message'
import Navigation from '@material-ui/icons/Navigation'
import PublishHistory from './PublishHistory'
@@ -116,6 +116,10 @@ const EditorMode = memo(function EditorMode(props: {
props.actions.setEditorMode(value)
}, [])
const openFile = useCallback(() => {
props.actions.openFile()
}, [])
const formatJson = useCallback(() => {
if (props.payload) {
try {
@@ -132,6 +136,7 @@ const EditorMode = memo(function EditorMode(props: {
<div style={{ width: '100%', lineHeight: '64px', textAlign: 'center' }}>
<EditorModeSelect value={props.editorMode} onChange={updateMode} focusEditor={props.focusEditor} />
<FormatJsonButton editorMode={props.editorMode} focusEditor={props.focusEditor} formatJson={formatJson} />
<OpenFileButton editorMode={props.editorMode} openFile={openFile} />
<div style={{ float: 'right' }}>
<PublishButton publish={props.publish} focusEditor={props.focusEditor} />
</div>
@@ -163,6 +168,20 @@ const FormatJsonButton = React.memo(function FormatJsonButton(props: {
)
})
const OpenFileButton = React.memo(function OpenFileButton(props: { editorMode: string; openFile: () => void }) {
return (
<Tooltip title="Open file">
<Fab
style={{ width: '36px', height: '36px', margin: '0 8px' }}
onClick={props.openFile}
id="sidebar-publish-open-file"
>
<AttachFileOutlined style={{ fontSize: '20px' }} />
</Fab>
</Tooltip>
)
})
const PublishButton = memo(function PublishButton(props: { publish: () => void; focusEditor: () => void }) {
const handleClickPublish = useCallback(
(e: React.MouseEvent) => {
+2 -4
View File
@@ -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>
&nbsp;
<MessageId message={message} />
</span>
<div style={{ float: 'right' }}>
<Copy value={value} />
</div>
&nbsp;
<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))
@@ -1,19 +1,20 @@
import * as q from '../../../../../backend/src/Model'
import ActionButtons from './ActionButtons'
import Copy from '../../helper/Copy'
import Save from '../../helper/Save'
import DateFormatter from '../../helper/DateFormatter'
import MessageHistory from './MessageHistory'
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 +36,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 +56,16 @@ function ValuePanel(props: Props) {
)
}
const getDecodedValue = useCallback(() => {
return node?.message && decodeMessage(node.message)?.message?.toUnicodeString()
}, [node, decodeMessage])
const getData = () => {
if (node?.message && node.message.payload) {
return node.message.payload.base64Message
}
}
function messageMetaInfo() {
if (!props.node || !props.node.message) {
return null
@@ -85,14 +97,16 @@ 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
const saveValue = value ? <Save getData={getData} /> : null
return (
<Panel>
<span>Value {copyValue}</span>
<span>
Value {copyValue} {saveValue}
</span>
<span style={{ width: '100%' }}>
{renderViewOptions()}
<div style={{ marginBottom: '-8px', marginTop: '8px' }}>
@@ -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) => {
+24 -13
View File
@@ -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}>
<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)
}
+4 -4
View File
@@ -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'
+3 -2
View File
@@ -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(() => {
+11 -5
View File
@@ -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() {
+85
View File
@@ -0,0 +1,85 @@
import * as React from 'react'
import { connect } from 'react-redux'
import Check from '@material-ui/icons/Check'
import CustomIconButton from './CustomIconButton'
import { SaveAlt } from '@material-ui/icons'
import { bindActionCreators } from 'redux'
import { rendererRpc, writeToFile } from '../../../../events'
import { makeSaveDialogRpc } from '../../../../events/OpenDialogRequest'
import { globalActions } from '../../actions'
export async function saveToFile(data: string): Promise<string | undefined> {
const rejectReasons = {
errorWritingFile: 'Error writing file',
}
const { canceled, filePath } = await rendererRpc.call(makeSaveDialogRpc(), {
securityScopedBookmarks: true,
})
if (!canceled && filePath !== undefined) {
try {
const filename = await rendererRpc.call(writeToFile, { filePath, data })
return filePath
} catch (error) {
throw rejectReasons.errorWritingFile
}
}
}
interface Props {
getData: () => string | undefined
actions: {
global: typeof globalActions
}
}
interface State {
didSave: boolean
}
class Save extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props)
this.state = { didSave: false }
}
private handleClick = async (event: React.MouseEvent) => {
event.stopPropagation()
const data = this.props.getData()
if (data != undefined) {
const filename = await saveToFile(data)
this.props.actions.global.showNotification(`Saved to ${filename}`)
this.setState({ didSave: true })
setTimeout(() => {
this.setState({ didSave: false })
}, 1500)
}
}
public render() {
const icon = !this.state.didSave ? (
<SaveAlt fontSize="inherit" />
) : (
<Check fontSize="inherit" style={{ cursor: 'default' }} />
)
return (
<CustomIconButton onClick={this.handleClick} tooltip="Save to file">
<div style={{ marginTop: '2px' }}>{icon}</div>
</CustomIconButton>
)
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
global: bindActionCreators(globalActions, dispatch),
},
}
}
export default connect(undefined, mapDispatchToProps)(Save)
+31
View File
@@ -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])
}
+56
View File
@@ -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,
}
},
}
+8
View File
@@ -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
}
+13
View File
@@ -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
}
+28
View File
@@ -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,
}
}
},
}
+10
View File
@@ -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 }
},
}
+6
View File
@@ -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
+4 -4
View File
@@ -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
+59 -1
View File
@@ -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() {
-3
View File
@@ -1,3 +0,0 @@
--require ts-node/register
--require source-map-support/register
--recursive ./src/**/*.spec.ts
+9 -21
View File
@@ -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
}
}
}
+21 -12
View File
@@ -1,6 +1,6 @@
// const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
entry: {
@@ -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' },
@@ -63,13 +72,8 @@ module.exports = {
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
test: /\.(png|jpg|gif)$/i,
type: 'asset/resource',
},
// {
// test: /\.node$/,
@@ -86,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$/
@@ -101,4 +104,10 @@ module.exports = {
// "react": "React",
// "react-dom": "ReactDOM"
},
};
cache: {
type: 'filesystem',
},
optimization: {
runtimeChunk: 'single',
},
}
+525 -296
View File
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -10,12 +10,10 @@ install:
- ps: Install-Product node 19
build_script:
- yarn
- yarn install --frozen-lockfile
- yarn build
- yarn prepare-release
- yarn package appx
- yarn prepare-release
- yarn package linux
test_script:
- yarn lint
+6 -6
View File
@@ -4,15 +4,15 @@
"description": "",
"main": "build/index.js",
"scripts": {
"test": "mocha",
"test": "mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"build": "tsc",
"test-inspect": "mocha --inspect-brk",
"coverage": "nyc mocha",
"test-inspect": "mocha --inspect-brk --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"coverage": "nyc mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"debug": "ts-node --inspect ./src/index.ts",
"postinstall": "yarn build"
},
"engines": {
"node": "19"
"node": ">=18"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -41,9 +41,9 @@
"peerDependencies": {
"fs-extra": "^8.0.1",
"js-base64": "^2.5.1",
"long": "^4.0.0",
"lowdb": "^1.0.0",
"mqtt": "^3.0.0",
"protobufjs": "~6.11.2",
"long": "^4.0.0"
"protobufjs": "^6.11.4"
}
}
+4 -4
View File
@@ -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'
+1 -1
View File
@@ -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,
})
+74 -12
View File
@@ -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}`
}
+1 -1
View File
@@ -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
}
}
+2 -1
View File
@@ -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
+4 -1
View File
@@ -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('/')
+3 -1
View File
@@ -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 -1
View File
@@ -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'
-22
View File
@@ -1,22 +0,0 @@
import { readFileSync } from 'fs'
import * as protobuf from 'protobufjs'
import { Base64Message } from './Base64Message'
import { Decoder } from './Decoder'
const buffer = readFileSync(require.resolve('../../../../res/sparkplug_b.proto'))
const root = protobuf.parse(buffer.toString()).root
export let SparkplugPayload = root.lookupType('com.cirruslink.sparkplug.protobuf.Payload')
export const SparkplugDecoder = {
decode(input: Buffer): Base64Message | undefined {
try {
const message = Base64Message.fromString(
JSON.stringify(SparkplugPayload.toObject(SparkplugPayload.decode(new Uint8Array(input))))
)
message.decoder = Decoder.SPARKPLUG
return message
} catch {
// ignore
}
},
}
+5 -6
View File
@@ -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
+4 -2
View File
@@ -10,7 +10,6 @@ import {
makePublishEvent,
removeConnection,
} from '../../events'
import { SparkplugDecoder } from './Model/sparkplugb'
export class ConnectionManager {
private connections: { [s: string]: DataSource<any> } = {}
@@ -47,9 +46,12 @@ export class ConnectionManager {
buffer = buffer.slice(0, 20000)
}
let decoded_payload = null
decoded_payload = Base64Message.fromBuffer(buffer)
backendEvents.emit(messageEvent, {
topic,
payload: SparkplugDecoder.decode(buffer) ?? Base64Message.fromBuffer(buffer),
payload: decoded_payload,
qos: packet.qos,
retain: packet.retain,
messageId: packet.messageId,
-3
View File
@@ -1,3 +0,0 @@
--require ts-node/register
--require source-map-support/register
--recursive ./src/**/*.spec.ts
+25 -18
View File
@@ -5,7 +5,7 @@
"@protobufjs/aspromise@^1.1.1", "@protobufjs/aspromise@^1.1.2":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@protobufjs/aspromise/-/aspromise-1.1.2.tgz#9b8b0cc663d669a7d8f6f5d0893a14d348f30fbf"
integrity sha1-m4sMxmPWaafY9vXQiToU00jzD78=
integrity sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==
"@protobufjs/base64@^1.1.2":
version "1.1.2"
@@ -20,12 +20,12 @@
"@protobufjs/eventemitter@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz#355cbc98bafad5978f9ed095f397621f1d066b70"
integrity sha1-NVy8mLr61ZePntCV85diHx0Ga3A=
integrity sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==
"@protobufjs/fetch@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/fetch/-/fetch-1.1.0.tgz#ba99fb598614af65700c1619ff06d454b0d84c45"
integrity sha1-upn7WYYUr2VwDBYZ/wbUVLDYTEU=
integrity sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==
dependencies:
"@protobufjs/aspromise" "^1.1.1"
"@protobufjs/inquire" "^1.1.0"
@@ -33,47 +33,49 @@
"@protobufjs/float@^1.0.2":
version "1.0.2"
resolved "https://registry.yarnpkg.com/@protobufjs/float/-/float-1.0.2.tgz#5e9e1abdcb73fc0a7cb8b291df78c8cbd97b87d1"
integrity sha1-Xp4avctz/Ap8uLKR33jIy9l7h9E=
integrity sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==
"@protobufjs/inquire@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/inquire/-/inquire-1.1.0.tgz#ff200e3e7cf2429e2dcafc1140828e8cc638f089"
integrity sha1-/yAOPnzyQp4tyvwRQIKOjMY48Ik=
integrity sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==
"@protobufjs/path@^1.1.2":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@protobufjs/path/-/path-1.1.2.tgz#6cc2b20c5c9ad6ad0dccfd21ca7673d8d7fbf68d"
integrity sha1-bMKyDFya1q0NzP0hynZz2Nf79o0=
integrity sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==
"@protobufjs/pool@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/pool/-/pool-1.1.0.tgz#09fd15f2d6d3abfa9b65bc366506d6ad7846ff54"
integrity sha1-Cf0V8tbTq/qbZbw2ZQbWrXhG/1Q=
integrity sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==
"@protobufjs/utf8@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570"
integrity sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=
integrity sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==
"@types/long@^4.0.1":
version "4.0.1"
resolved "https://registry.yarnpkg.com/@types/long/-/long-4.0.1.tgz#459c65fa1867dafe6a8f322c4c51695663cc55e9"
integrity sha512-5tXH6Bx/kNGd3MgffdmP4dy2Z+G4eaXw0SE81Tq3BNadtnMR5/ySMzX4SLEzHJzSmPNn4HIdpQsBvXMUykr58w==
version "4.0.2"
resolved "https://registry.yarnpkg.com/@types/long/-/long-4.0.2.tgz#b74129719fc8d11c01868010082d483b7545591a"
integrity sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==
"@types/node@>=13.7.0":
version "16.4.13"
resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.13.tgz#7dfd9c14661edc65cccd43a29eb454174642370d"
integrity sha512-bLL69sKtd25w7p1nvg9pigE4gtKVpGTPojBFLMkGHXuUgap2sLqQt2qUnqmVCDfzGUL0DRNZP+1prIZJbMeAXg==
version "20.12.2"
resolved "https://registry.yarnpkg.com/@types/node/-/node-20.12.2.tgz#9facdd11102f38b21b4ebedd9d7999663343d72e"
integrity sha512-zQ0NYO87hyN6Xrclcqp7f8ZbXNbRfoGWNcMvHTPQp9UUrwI0mI7XBz+cu7/W6/VClYo2g63B0cjull/srU7LgQ==
dependencies:
undici-types "~5.26.4"
long@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28"
integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==
protobufjs@^6.11.2:
version "6.11.2"
resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-6.11.2.tgz#de39fabd4ed32beaa08e9bb1e30d08544c1edf8b"
integrity sha512-4BQJoPooKJl2G9j3XftkIXjoC9C0Av2NOrWmbLWT1vH32GcSUHjM0Arra6UfTsVyfMAuFzaLucXn1sadxJydAw==
protobufjs@^6.11.4:
version "6.11.4"
resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-6.11.4.tgz#29a412c38bf70d89e537b6d02d904a6f448173aa"
integrity sha512-5kQWPaJHi1WoCpjTGszzQ32PG2F4+wRY6BmAT4Vfw56Q2FZ4YZzK20xUYQH4YkfehY1e6QSICrJquM6xXZNcrw==
dependencies:
"@protobufjs/aspromise" "^1.1.2"
"@protobufjs/base64" "^1.1.2"
@@ -88,3 +90,8 @@ protobufjs@^6.11.2:
"@types/long" "^4.0.1"
"@types/node" ">=13.7.0"
long "^4.0.0"
undici-types@~5.26.4:
version "5.26.5"
resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617"
integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==
+1 -5
View File
@@ -1,11 +1,7 @@
#!/bin/bash
set -e
git clone https://github.com/thomasnordquist/MQTT-Explorer.git /app
cd /app
git checkout travis-ui-tests
yarn
yarn install --frozen-lockfile
yarn build
yarn ui-test
+10 -2
View File
@@ -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
@@ -54,3 +54,11 @@ export function makeConnectionMessageEvent(connectionId: string): Event<MqttMess
export const getAppVersion: RpcEvent<void, string> = {
topic: 'getAppVersion',
}
export const writeToFile: RpcEvent<{ filePath: string, data: string, encoding?: string }, void> = {
topic: 'writeFile',
}
export const readFromFile: RpcEvent<{ filePath: string, encoding?: string }, Buffer> = {
topic: 'readFromFile',
}
+7 -1
View File
@@ -1,4 +1,4 @@
import { OpenDialogOptions, OpenDialogReturnValue } from 'electron'
import { OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue } from 'electron'
import { RpcEvent } from './EventSystem/Rpc'
export function makeOpenDialogRpc(): RpcEvent<OpenDialogOptions, OpenDialogReturnValue> {
@@ -6,3 +6,9 @@ export function makeOpenDialogRpc(): RpcEvent<OpenDialogOptions, OpenDialogRetur
topic: 'openDialog',
}
}
export function makeSaveDialogRpc(): RpcEvent<SaveDialogOptions, SaveDialogReturnValue> {
return {
topic: 'saveDialog',
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-playwright"
],
"env": {
"PLAYWRIGHT_BROWSERS_PATH": "0"
}
}
}
}
+21 -11
View File
@@ -1,24 +1,28 @@
{
"name": "MQTT-Explorer",
"version": "0.4.0-beta1",
"version": "0.4.0-beta.5",
"description": "Explore your message queues",
"main": "dist/src/electron.js",
"engines": {
"node": "19"
"node": ">=18"
},
"private": "true",
"scripts": {
"start": "electron .",
"test": "yarn test:app && yarn test:backend",
"test:app": "cd app && yarn test",
"test:backend": "cd backend && yarn test",
"test:mcp": "tsc && node dist/src/spec/testMcpIntrospection.js",
"install": "cd app && yarn && cd ..",
"dev": "npm-run-all --parallel dev:*",
"dev:app": "cd app && npm run dev",
"dev:electron": "tsc && electron . --development",
"lint": "npm-run-all --parallel lint:prettier lint:tslint",
"lint": "npm-run-all --parallel lint:prettier lint:tslint lint:spellcheck",
"lint:fix": "npm-run-all lint:tslint:fix lint:prettier:fix",
"lint:prettier": "prettier --check \"**/*.ts{x,}\"",
"lint:prettier:fix": "prettier --write \"**/*.ts{x,}\"",
"lint:tslint": "tslint -p ./",
"lint:tslint:fix": "tslint -p ./ --fix",
"lint:spellcheck": "cspell -e ./build -e \"node_modules\" \"**/*.ts{x,}\"",
"build": "tsc && cd app && yarn run build && cd ..",
"prepare-release": "ts-node scripts/prepare-release.ts",
@@ -74,7 +78,11 @@
"license": "CC-BY-ND-4.0",
"devDependencies": {
"@babel/runtime": "^7.17.2",
"@cspell/dict-typescript": "^3.1.2",
"@electron/notarize": "^2.3.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/commit-analyzer": "^12.0.0",
"@semantic-release/git": "^10.0.1",
"@types/chai": "^4.1.7",
"@types/fs-extra": "8",
"@types/lowdb": "^1.0.6",
@@ -87,28 +95,30 @@
"@types/uuid": "^8.3.4",
"builder-util-runtime": "^9",
"chai": "^4.2.0",
"cspell": "^4.0.28",
"electron": "29.1.1",
"cspell": "^8.6.1",
"electron": "29.2.0",
"electron-builder": "^24.13.3",
"mocha": "7.1",
"mocha": "^10.4.0",
"mustache": "4",
"npm-run-all": "^4.1.5",
"nyc": "15",
"playwright": "^1.43.0",
"prettier": "^3.2.5",
"redux-thunk": "^2.3.0",
"semantic-release": "^23.0.8",
"semantic-release-export-data": "^1.0.1",
"source-map-support": "^0.5.9",
"spectron": "19",
"sparkplug-client": "^3.2.4",
"ts-node": "^10.9.2",
"tslint": "^6.1.3",
"tslint-config-airbnb": "^5.11.2",
"tslint-react": "^5.0.0",
"tslint-react-recommended": "^1.0.15",
"typescript": "^4.5.5",
"webdriverio": "7.16"
"typescript": "^4.5.5"
},
"dependencies": {
"about-window": "^1.12.1",
"axios": "^0.19.0",
"axios": "^0.28.0",
"dot-prop": "^5.0.0",
"electron-log": "4.4.6",
"electron-updater": "^4.6",
@@ -118,8 +128,8 @@
"lowdb": "^1.0.0",
"mime": "^2.4.4",
"mqtt": "^4.3.6",
"protobufjs": "~6.11.2",
"sha1": "^1.1.1",
"sparkplug-payload": "^1.0.3",
"uuid": "^8.3.2",
"yarn-run-all": "^3.1.1"
}
+14 -14
View File
@@ -7,7 +7,16 @@ const linuxAppImage: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: true,
arm64: false,
arm64: true,
projectDir: './build/clean',
publish: 'always',
}
const linuxSnap: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: false, // not supported to build on x64
arm64: false, // not supported to build on x64
projectDir: './build/clean',
publish: 'always',
}
@@ -16,16 +25,7 @@ const linuxDeb: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: true,
arm64: false,
projectDir: './build/clean',
publish: 'always',
}
const linuxSnap: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: false,
arm64: false,
arm64: true,
projectDir: './build/clean',
publish: 'always',
}
@@ -61,7 +61,7 @@ const mac: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: false,
arm64: false,
arm64: true,
projectDir: './build/clean',
publish: 'always',
}
@@ -82,8 +82,8 @@ async function executeBuild() {
break
case 'mac':
await buildWithOptions(mac, { platform: 'mac', package: 'dmg' })
await buildWithOptions(mac, { platform: 'mac', package: 'mas' })
await buildWithOptions(mac, { platform: 'mac', package: 'zip' })
// await buildWithOptions(mac, { platform: 'mac', package: 'mas' })
// await buildWithOptions(mac, { platform: 'mac', package: 'zip' })
break
default:
await buildWithOptions({ ...mac, projectDir: '' }, { platform: 'mac', package: 'mas-dev' })
-197
View File
@@ -1,197 +0,0 @@
syntax = "proto2";
//
// To compile:
// cd client_libraries/java
// protoc --proto_path=../../ --java_out=src/main/java ../../sparkplug_b.proto
//
package com.cirruslink.sparkplug.protobuf;
option java_package = "com.cirruslink.sparkplug.protobuf";
option java_outer_classname = "SparkplugBProto";
message Payload {
/*
// Indexes of Data Types
// Unknown placeholder for future expansion.
Unknown = 0;
// Basic Types
Int8 = 1;
Int16 = 2;
Int32 = 3;
Int64 = 4;
UInt8 = 5;
UInt16 = 6;
UInt32 = 7;
UInt64 = 8;
Float = 9;
Double = 10;
Boolean = 11;
String = 12;
DateTime = 13;
Text = 14;
// Additional Metric Types
UUID = 15;
DataSet = 16;
Bytes = 17;
File = 18;
Template = 19;
// Additional PropertyValue Types
PropertySet = 20;
PropertySetList = 21;
*/
message Template {
message Parameter {
optional string name = 1;
optional uint32 type = 2;
oneof value {
uint32 int_value = 3;
uint64 long_value = 4;
float float_value = 5;
double double_value = 6;
bool boolean_value = 7;
string string_value = 8;
ParameterValueExtension extension_value = 9;
}
message ParameterValueExtension {
extensions 1 to max;
}
}
optional string version = 1; // The version of the Template to prevent mismatches
repeated Metric metrics = 2; // Each metric is the name of the metric and the datatype of the member but does not contain a value
repeated Parameter parameters = 3;
optional string template_ref = 4; // Reference to a template if this is extending a Template or an instance - must exist if an instance
optional bool is_definition = 5;
extensions 6 to max;
}
message DataSet {
message DataSetValue {
oneof value {
uint32 int_value = 1;
uint64 long_value = 2;
float float_value = 3;
double double_value = 4;
bool boolean_value = 5;
string string_value = 6;
DataSetValueExtension extension_value = 7;
}
message DataSetValueExtension {
extensions 1 to max;
}
}
message Row {
repeated DataSetValue elements = 1;
extensions 2 to max; // For third party extensions
}
optional uint64 num_of_columns = 1;
repeated string columns = 2;
repeated uint32 types = 3;
repeated Row rows = 4;
extensions 5 to max; // For third party extensions
}
message PropertyValue {
optional uint32 type = 1;
optional bool is_null = 2;
oneof value {
uint32 int_value = 3;
uint64 long_value = 4;
float float_value = 5;
double double_value = 6;
bool boolean_value = 7;
string string_value = 8;
PropertySet propertyset_value = 9;
PropertySetList propertysets_value = 10; // List of Property Values
PropertyValueExtension extension_value = 11;
}
message PropertyValueExtension {
extensions 1 to max;
}
}
message PropertySet {
repeated string keys = 1; // Names of the properties
repeated PropertyValue values = 2;
extensions 3 to max;
}
message PropertySetList {
repeated PropertySet propertyset = 1;
extensions 2 to max;
}
message MetaData {
// Bytes specific metadata
optional bool is_multi_part = 1;
// General metadata
optional string content_type = 2; // Content/Media type
optional uint64 size = 3; // File size, String size, Multi-part size, etc
optional uint64 seq = 4; // Sequence number for multi-part messages
// File metadata
optional string file_name = 5; // File name
optional string file_type = 6; // File type (i.e. xml, json, txt, cpp, etc)
optional string md5 = 7; // md5 of data
// Catchalls and future expansion
optional string description = 8; // Could be anything such as json or xml of custom properties
extensions 9 to max;
}
message Metric {
optional string name = 1; // Metric name - should only be included on birth
optional uint64 alias = 2; // Metric alias - tied to name on birth and included in all later DATA messages
optional uint64 timestamp = 3; // Timestamp associated with data acquisition time
optional uint32 datatype = 4; // DataType of the metric/tag value
optional bool is_historical = 5; // If this is historical data and should not update real time tag
optional bool is_transient = 6; // Tells consuming clients such as MQTT Engine to not store this as a tag
optional bool is_null = 7; // If this is null - explicitly say so rather than using -1, false, etc for some datatypes.
optional MetaData metadata = 8; // Metadata for the payload
optional PropertySet properties = 9;
oneof value {
uint32 int_value = 10;
uint64 long_value = 11;
float float_value = 12;
double double_value = 13;
bool boolean_value = 14;
string string_value = 15;
bytes bytes_value = 16; // Bytes, File
DataSet dataset_value = 17;
Template template_value = 18;
MetricValueExtension extension_value = 19;
}
message MetricValueExtension {
extensions 1 to max;
}
}
optional uint64 timestamp = 1; // Timestamp at message sending time
repeated Metric metrics = 2; // Repeated forever - no limit in Google Protobufs
optional uint64 seq = 3; // Sequence number
optional string uuid = 4; // UUID to track message type in terms of schema definitions
optional bytes body = 5; // To optionally bypass the whole definition above
extensions 6 to max; // For third party extensions
}
+3 -3
View File
@@ -17,18 +17,18 @@ async function prepareRelease() {
// Install app dependencies
chdir('app')
await exec('yarn')
await exec('yarn', ['install', '--frozen-lockfile'])
chdir('..')
// Install electron dependencies
await exec('yarn')
await exec('yarn', ['install', '--frozen-lockfile'])
// Build App and Electron backend
await exec('yarn', ['build'])
// Clean up
await fs.remove('node_modules')
await exec('yarn', ['install', '--production']) // Do not clean up, electron version detection will fail otherwise
await exec('yarn', ['install', '--production', '--frozen-lockfile']) // Do not clean up, electron version detection will fail otherwise
await fs.remove(path.join('app', 'node_modules'))
chdir(originalDir)
+232
View File
@@ -0,0 +1,232 @@
/********************************************************************************
* Copyright (c) 2016-2018 Cirrus Link Solutions and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Cirrus Link Solutions - initial implementation
********************************************************************************/
var SparkplugClient = require('sparkplug-client')
/*
* Main sample function which includes the run() function for running the sample
*/
var sample = (function () {
var config = {
serverUrl: 'tcp://127.0.0.1:1883',
username: '',
password: '',
groupId: 'Sparkplug Devices',
edgeNode: 'JavaScript Edge Node',
clientId: 'JavaScriptSimpleEdgeNode',
version: 'spBv1.0',
},
hwVersion = 'Emulated Hardware',
swVersion = 'v1.0.0',
deviceId = 'Emulated Device',
sparkPlugClient,
publishPeriod = 5000,
// Generates a random integer
randomInt = function () {
return 1 + Math.floor(Math.random() * 10)
},
// Get BIRTH payload for the edge node
getNodeBirthPayload = function () {
return {
timestamp: new Date().getTime(),
metrics: [
{
name: 'Node Control/Rebirth',
type: 'boolean',
value: false,
},
{
name: 'Template1',
type: 'template',
value: {
isDefinition: true,
metrics: [
{ name: 'myBool', value: false, type: 'boolean' },
{ name: 'myInt', value: 0, type: 'int' },
],
parameters: [
{
name: 'param1',
type: 'string',
value: 'value1',
},
],
},
},
],
}
},
// Get BIRTH payload for the device
getDeviceBirthPayload = function () {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'float' },
{ name: 'my_int', value: randomInt(), type: 'int' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'long' },
{ name: 'Inputs/0', value: true, type: 'boolean' },
{ name: 'Inputs/1', value: 0, type: 'int' },
{ name: 'Inputs/2', value: 1.23, type: 'float' },
{ name: 'Outputs/0', value: true, type: 'boolean' },
{ name: 'Outputs/1', value: 0, type: 'int' },
{ name: 'Outputs/2', value: 1.23, type: 'float' },
{ name: 'Properties/hw_version', value: hwVersion, type: 'string' },
{ name: 'Properties/sw_version', value: swVersion, type: 'string' },
{
name: 'my_dataset',
type: 'dataset',
value: {
numOfColumns: 2,
types: ['string', 'string'],
columns: ['str1', 'str2'],
rows: [
['x', 'a'],
['y', 'b'],
],
},
},
{
name: 'TemplateInstance1',
type: 'template',
value: {
templateRef: 'Template1',
isDefinition: false,
metrics: [
{ name: 'myBool', value: true, type: 'boolean' },
{ name: 'myInt', value: 100, type: 'int' },
],
parameters: [
{
name: 'param1',
type: 'string',
value: 'value2',
},
],
},
},
],
}
},
// Get data payload for the device
getDataPayload = function () {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'float' },
{ name: 'my_int', value: randomInt(), type: 'int' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'long' },
],
}
},
// Runs the sample
run = function () {
// Create the SparkplugClient
sparkplugClient = SparkplugClient.newClient(config)
// Create Incoming Message Handler
sparkplugClient.on('message', function (topic, payload) {
console.log(topic, payload)
})
// Create 'birth' handler
sparkplugClient.on('birth', function () {
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
})
// Create node command handler
sparkplugClient.on('ncmd', function (payload) {
var timestamp = payload.timestamp,
metrics = payload.metrics
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name == 'Node Control/Rebirth' && metric.value) {
console.log("Received 'Rebirth' command")
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
}
}
}
})
// Create device command handler
sparkplugClient.on('dcmd', function (deviceId, payload) {
var timestamp = payload.timestamp,
metrics = payload.metrics,
inboundMetricMap = {},
outboundMetric = [],
outboundPayload
console.log('Command recevied for device ' + deviceId)
// Loop over the metrics and store them in a map
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
inboundMetricMap[metric.name] = metric.value
}
}
if (inboundMetricMap['Outputs/0'] !== undefined && inboundMetricMap['Outputs/0'] !== null) {
console.log('Outputs/0: ' + inboundMetricMap['Outputs/0'])
outboundMetric.push({ name: 'Inputs/0', value: inboundMetricMap['Outputs/0'], type: 'boolean' })
outboundMetric.push({ name: 'Outputs/0', value: inboundMetricMap['Outputs/0'], type: 'boolean' })
console.log('Updated value for Inputs/0 ' + inboundMetricMap['Outputs/0'])
} else if (inboundMetricMap['Outputs/1'] !== undefined && inboundMetricMap['Outputs/1'] !== null) {
console.log('Outputs/1: ' + inboundMetricMap['Outputs/1'])
outboundMetric.push({ name: 'Inputs/1', value: inboundMetricMap['Outputs/1'], type: 'int' })
outboundMetric.push({ name: 'Outputs/1', value: inboundMetricMap['Outputs/1'], type: 'int' })
console.log('Updated value for Inputs/1 ' + inboundMetricMap['Outputs/1'])
} else if (inboundMetricMap['Outputs/2'] !== undefined && inboundMetricMap['Outputs/2'] !== null) {
console.log('Outputs/2: ' + inboundMetricMap['Outputs/2'])
outboundMetric.push({ name: 'Inputs/2', value: inboundMetricMap['Outputs/2'], type: 'float' })
outboundMetric.push({ name: 'Outputs/2', value: inboundMetricMap['Outputs/2'], type: 'float' })
console.log('Updated value for Inputs/2 ' + inboundMetricMap['Outputs/2'])
}
outboundPayload = {
timestamp: new Date().getTime(),
metrics: outboundMetric,
}
// Publish device data
sparkplugClient.publishDeviceData(deviceId, outboundPayload)
})
for (var i = 1; i < 101; i++) {
// Set up a device data publish for i*publishPeriod milliseconds from now
setTimeout(function () {
// Publish device data
sparkplugClient.publishDeviceData(deviceId, getDataPayload())
// End the client connection after the last publish
if (i === 100) {
sparkplugClient.stop()
}
}, i * publishPeriod)
}
}
return { run: run }
})()
// Run the sample
sample.run()
+26 -17
View File
@@ -1,10 +1,25 @@
#!/bin/bash
function finish {
echo "Exiting, cleaning up"
tmux send-keys -t record q || echo "No tmux was running"
#echo kill $PID_XVFB $PID_CHROMEDRIVER $PID_MOSQUITTO
#kill $PID_XVFB $PID_CHROMEDRIVER $PID_MOSQUITTO
set +e
echo "Exiting, cleaning up.."
echo "Stopping TMUX session (record).."
tmux kill-session -t record || echo "Already stopped"
if [[ ! -z "$PID_MOSQUITTO" ]]; then
echo "Stopping mosquitto ($PID_MOSQUITTO).."
kill "$PID_MOSQUITTO" || echo "Already stopped"
fi
if [[ ! -z "$PID_VNC" ]]; then
echo "Stopping VNC ($PID_VNC).."
kill "$PID_VNC" || echo "Already stopped"
fi
if [[ ! -z "$PID_XVFB" ]]; then
echo "Stopping XVFB ($PID_XVFB).."
kill "$PID_XVFB" || echo "Already stopped"
fi
}
trap finish EXIT
@@ -18,28 +33,25 @@ export PID_XVFB=$!
sleep 2
# Debug with VNC
while [ "$TEST_EXIT_CODE" = "" ]; do x11vnc -localhost -passwd "bierbier" -display :$SCR; done &
x11vnc -localhost -rfbport 5900 -passwd "bierbier" -display :$SCR &
export PID_VNC=$!
# Start mqtt broker
mosquitto &
export PID_MOSQUITTO=$!
DISPLAY=:$SCR ./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515 &
export PID_CHROMEDRIVER=$!
sleep 2
# Delete old video
rm ./app.mp4 || echo no need to delete ./app.mp4
rm -f ./app*.mp4
rm -f ./qrawvideorgb24.yuv
# Start recoring in tmux
#tmux new-session -d -s record ffmpeg -f x11grab -draw_mouse 0 -video_size $DIMENSIONS -i :$SCR -codec:v libx264 -r 20 ./app.mp4
# tmux new-session -d -s record ffmpeg -f x11grab -draw_mouse 0 -video_size $DIMENSIONS -i :$SCR -codec:v libx264 -r 20 ./app.mp4
tmux new-session -d -s record ffmpeg -f x11grab -draw_mouse 0 -video_size $DIMENSIONS -i :$SCR -r 20 -vcodec rawvideo -pix_fmt yuv420p qrawvideorgb24.yuv
# Start tests
node dist/src/spec/demoVideo.js
DISPLAY=:$SCR node dist/src/spec/demoVideo.js
TEST_EXIT_CODE=$?
echo "Webriver exitet with $TEST_EXIT_CODE"
echo "Test script exited with $TEST_EXIT_CODE"
# Stop recording
tmux send-keys -t record q
@@ -47,7 +59,4 @@ tmux send-keys -t record q
# Ensure video is written
sleep 5
# Process the video
./scripts/prepareVideo.sh
exit $TEST_EXIT_CODE
+2 -1
View File
@@ -27,7 +27,7 @@ async function createDraft(tag: string) {
draft: true,
},
})
// @ts-ignore
return cleanUploadUrl(response.data.upload_url)
}
@@ -76,6 +76,7 @@ async function uploadFile(uploadUrl: string, file: string) {
const data = fs.readFileSync(file)
const mimeType = mime.getType(path.extname(file))
// @ts-ignore
return axios({
data,
method: 'post',
+21
View File
@@ -17,10 +17,12 @@ export async function waitForDevServer() {
}
export function loadDevTools() {
/* spell-checker: disable */
// Redux
// BrowserWindow.addDevToolsExtension(
// path.join(os.homedir(), '/Library/Application Support/Google/Chrome/Default/Extensions/lmhkpmbekcpmknklioeibfkpmmfibljd/2.17.0_0/')
// )
/* spell-checker: enable */
}
export function isDev() {
@@ -30,3 +32,22 @@ export function isDev() {
export function runningUiTestOnCi() {
return Boolean(process.argv.find(arg => arg === '--runningUiTestOnCi'))
}
export function enableMcpIntrospection() {
return Boolean(process.argv.find(arg => arg === '--enable-mcp-introspection'))
}
export function getRemoteDebuggingPort() {
const portArg = process.argv.find(arg => arg.startsWith('--remote-debugging-port='))
if (portArg) {
const parts = portArg.split('=')
if (parts.length === 2 && parts[1]) {
const port = parseInt(parts[1], 10)
// Return the port only if it's a valid number between 1 and 65535
if (!isNaN(port) && port > 0 && port <= 65535) {
return port
}
}
}
return enableMcpIntrospection() ? 9222 : undefined
}
+35 -7
View File
@@ -4,14 +4,22 @@ import ConfigStorage from '../backend/src/ConfigStorage'
import { app, BrowserWindow, Menu, dialog } from 'electron'
import { autoUpdater } from 'electron-updater'
import { ConnectionManager } from '../backend/src/index'
import { promises as fsPromise } from 'fs'
// import { electronTelemetryFactory } from 'electron-telemetry'
import { menuTemplate } from './MenuTemplate'
import buildOptions from './buildOptions'
import { waitForDevServer, isDev, runningUiTestOnCi, loadDevTools } from './development'
import {
waitForDevServer,
isDev,
runningUiTestOnCi,
loadDevTools,
enableMcpIntrospection,
getRemoteDebuggingPort,
} from './development'
import { shouldAutoUpdate, handleAutoUpdate } from './autoUpdater'
import { registerCrashReporter } from './registerCrashReporter'
import { makeOpenDialogRpc } from '../events/OpenDialogRequest'
import { backendRpc, getAppVersion } from '../events'
import { makeOpenDialogRpc, makeSaveDialogRpc } from '../events/OpenDialogRequest'
import { backendRpc, getAppVersion, writeToFile, readFromFile } from '../events'
registerCrashReporter()
@@ -19,12 +27,34 @@ 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')
// Enable remote debugging for MCP introspection
const remoteDebuggingPort = getRemoteDebuggingPort()
if (remoteDebuggingPort) {
app.commandLine.appendSwitch('--remote-debugging-port', remoteDebuggingPort.toString())
log.info(`Remote debugging enabled on port ${remoteDebuggingPort}`)
}
app.whenReady().then(() => {
backendRpc.on(makeOpenDialogRpc(), async request => {
return dialog.showOpenDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})
backendRpc.on(makeSaveDialogRpc(), async request => {
return dialog.showSaveDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})
backendRpc.on(getAppVersion, async () => app.getVersion())
backendRpc.on(writeToFile, async ({ filePath, data, encoding }) => {
await fsPromise.writeFile(filePath, Buffer.from(data, 'base64'), { encoding })
})
backendRpc.on(readFromFile, async ({ filePath, encoding }) => {
return fsPromise.readFile(filePath, { encoding })
})
})
autoUpdater.logger = log
@@ -33,7 +63,7 @@ log.info('App starting...')
const connectionManager = new ConnectionManager()
connectionManager.manageConnections()
const configStorage = new ConfigStorage(path.join(app.getPath('appData'), app.name, 'settings.json'))
const configStorage = new ConfigStorage(path.join(app.getPath('userData'), 'settings.json'))
configStorage.init()
// Keep a global reference of the window object, if you don't, the window will
@@ -69,8 +99,6 @@ async function createWindow() {
}
})
console.log('icon path', iconPath)
// Load the index.html of the app.
if (isDev()) {
mainWindow.loadURL('http://localhost:8080')
+1
View File
@@ -19,6 +19,7 @@ export type SceneNames =
| 'settings'
| 'customize_subscriptions'
| 'keyboard_shortcuts'
| 'sparkplugb-decoding'
| 'end'
export class SceneBuilder {
+93 -63
View File
@@ -1,7 +1,11 @@
import * as fs from 'fs'
import * as os from 'os'
import * as webdriverio from 'webdriverio'
import * as path from 'path'
import { ElectronApplication, _electron as electron } from 'playwright'
import mockMqtt, { stop as stopMqtt } from './mock-mqtt'
import { default as MockSparkplug } from './mock-sparkplugb'
import { clearOldTopics } from './scenarios/clearOldTopics'
import { clearSearch, searchTree } from './scenarios/searchTree'
import { clickOnHistory, createFakeMousePointer, hideText, showText, sleep } from './util'
@@ -10,134 +14,160 @@ import { copyTopicToClipboard } from './scenarios/copyTopicToClipboard'
import { copyValueToClipboard } from './scenarios/copyValueToClipboard'
import { disconnect } from './scenarios/disconnect'
import { publishTopic } from './scenarios/publishTopic'
import { SceneBuilder } from './SceneBuilder'
import { Scene, SceneBuilder } from './SceneBuilder'
import { showAdvancedConnectionSettings } from './scenarios/showAdvancedConnectionSettings'
import { showJsonPreview } from './scenarios/showJsonPreview'
import { showMenu } from './scenarios/showMenu'
import { showNumericPlot } from './scenarios/showNumericPlot'
import { showOffDiffCapability } from './scenarios/showOffDiffCapability'
import { showZoomLevel } from './scenarios/showZoomLevel'
import { showSparkPlugDecoding } from './scenarios/showSparkplugDecoding'
/**
* A convenience method that handles gracefully cleaning up the test run.
*/
const cleanUp = async (scenes: SceneBuilder, electronApp: ElectronApplication) => {
// Exit app.
fs.writeFileSync('scenes.json', JSON.stringify(scenes.scenes, undefined, ' '))
await electronApp.close()
}
process.on('unhandledRejection', (error: Error | any) => {
console.error('unhandledRejection', error.message, error.stack)
process.exit(1)
})
const runningUiTestOnCi = os.platform() === 'darwin' ? [] : ['--runningUiTestOnCi']
const options = {
host: '127.0.0.1', // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver.
path: '/wd/hub',
capabilities: {
browserName: 'chrome',
'goog:chromeOptions': {
binary: `${__dirname}/../../../node_modules/.bin/electron`,
args: [
`--app=${__dirname}/../../..`,
'--force-device-scale-factor=1',
'--no-sandbox',
'--disable-dev-shm-usage',
'--disable-extensions',
].concat(runningUiTestOnCi),
windowTypes: ['app', 'webview'],
},
setTimeout(
() => {
console.error('Timeout reached')
process.exit(1)
},
}
60 * 10 * 1000
)
const runningUiTestOnCi = os.platform() === 'darwin' ? [] : ['--runningUiTestOnCi']
async function doStuff() {
console.log('Waiting for MQTT Broker on port 1880 (no auth)')
await mockMqtt()
console.log('start webdriver')
const browser = await webdriverio.remote(options)
await createFakeMousePointer(browser)
console.log('Starting playwright/electron')
// Launch Electron app.
const electronApp: ElectronApplication = await electron.launch({
args: [`${__dirname}/../../..`, ...runningUiTestOnCi],
})
console.log('Playwright started')
// Get the first window that the app opens, wait if necessary.
const page = await electronApp.firstWindow({ timeout: 3000 })
// Print the title.
console.log(await page.title())
// Capture a screenshot.
await page.screenshot({ path: 'intro.png' })
// Direct Electron console to Node terminal.
page.on('console', console.log)
// Wait for Username input to be visible
await browser.$('//label[contains(text(), "Username")]/..//input')
await page.locator('//label[contains(text(), "Username")]/..//input')
const scenes = new SceneBuilder()
await scenes.record('connect', async () => {
await connectTo('127.0.0.1', browser)
await connectTo('127.0.0.1', page)
await MockSparkplug.run() // Start sparkplug client after connect or birth topics will be missed
await sleep(1000)
})
await scenes.record('numeric_plots', async () => {
await showText('Plot topic history', 1500, browser)
await showNumericPlot(browser)
await showText('Plot topic history', 1500, page)
await showNumericPlot(page)
await sleep(2000)
})
await scenes.record('json-formatting', async () => {
await showJsonPreview(browser)
await showText('Formatted messages', 1500, browser, 'top')
await showJsonPreview(page)
await showText('Formatted messages', 1500, page, 'top')
await sleep(1500)
})
await scenes.record('diffs', async () => {
await showOffDiffCapability(browser)
await hideText(browser)
await showOffDiffCapability(page)
await hideText(page)
})
await scenes.record('publish_topic', async () => {
await showText('Publish topics', 1500, browser, 'top')
await clickOnHistory(browser)
await publishTopic(browser)
await sleep(1000)
})
// disable this scenario for now until expandTopic is sorted out
// await scenes.record('publish_topic', async () => {
// await showText('Publish topics', 1500, page, 'top')
// await clickOnHistory(page)
// await publishTopic(page)
// await sleep(1000)
// })
await scenes.record('clipboard', async () => {
await showText('Copy to Clipboard', 1500, browser)
await copyTopicToClipboard(browser)
await hideText(browser)
await copyValueToClipboard(browser)
await showText('Copy to Clipboard', 1500, page)
await copyTopicToClipboard(page)
await hideText(page)
await copyValueToClipboard(page)
await sleep(1000)
})
await scenes.record('topic_filter', async () => {
await showText('Search topic hierarchy', 0, browser, 'middle')
await searchTree('temp', browser)
await hideText(browser)
await showText('Topics containing "temp"', 1500, browser)
await showText('Search topic hierarchy', 0, page, 'middle')
await searchTree('temp', page)
await hideText(page)
await showText('Topics containing "temp"', 1500, page)
await sleep(1500)
await clearSearch(browser)
await clearSearch(page)
await sleep(1000)
})
await scenes.record('delete_retained_topics', async () => {
await hideText(browser)
await showText('Delete retained topics', 5000, browser)
await clearOldTopics(browser)
await hideText(browser)
await scenes.record('sparkplugb-decoding', async () => {
await showText('SparkplugB Decoding', 2000, page, 'top')
await showSparkPlugDecoding(page)
})
// disable this scenario for now until expandTopic is sorted out
// await scenes.record('delete_retained_topics', async () => {
// await hideText(page)
// await showText('Delete retained topics', 5000, page)
// await clearOldTopics(page)
// await hideText(page)
// })
await scenes.record('settings', async () => {
await showText('Settings', 1500, browser)
await showMenu(browser)
await showText('Settings', 1500, page)
await showMenu(page)
})
await scenes.record('customize_subscriptions', async () => {
await sleep(2000)
await disconnect(browser)
await showText('Customize Subscriptions', 1500, browser, 'top')
await showAdvancedConnectionSettings(browser)
await disconnect(page)
await showText('Customize Subscriptions', 1500, page, 'top')
await showAdvancedConnectionSettings(page)
})
await scenes.record('keyboard_shortcuts', async () => {
await showText('Keyboard shortcuts', 1500, browser, 'middle')
await showText('Keyboard shortcuts', 1500, page, 'middle')
await sleep(1750)
await showZoomLevel(browser)
await showZoomLevel(page)
})
await scenes.record('end', async () => {
await showText('The End', 3000, browser, 'middle')
await showText('The End', 3000, page, 'middle')
await sleep(3000)
})
browser.closeWindow()
setTimeout(() => {
console.log('Forced quit')
process.exit(0)
}, 10 * 1000)
stopMqtt()
console.log('Stopped mqtt client')
fs.writeFileSync('scenes.json', JSON.stringify(scenes.scenes, undefined, ' '))
cleanUp(scenes, electronApp)
// Force exit since there appear to be open handles
process.exit(0)
}
doStuff()
+20 -38
View File
@@ -1,5 +1,6 @@
import * as os from 'os'
import * as webdriverio from 'webdriverio'
import { ElectronApplication, _electron as electron } from 'playwright'
import mockMqtt, { stopUpdates as stopMqttUpdates } from './mock-mqtt'
import { ClassNameMapping, countInstancesOf, createFakeMousePointer, getHeapDump, setFast, sleep } from './util'
import { clearSearch, searchTree } from './scenarios/searchTree'
@@ -13,67 +14,53 @@ process.on('unhandledRejection', (error: Error | any) => {
const runningUiTestOnCi = os.platform() === 'darwin' ? [] : ['--runningUiTestOnCi']
const options = {
host: '127.0.0.1', // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver.
capabilities: {
browserName: 'chrome',
'goog:chromeOptions': {
binary: `${__dirname}/../../../node_modules/.bin/electron`,
args: [
`--app=${__dirname}/../../..`,
'--force-device-scale-factor=1',
'--no-sandbox',
'--disable-dev-shm-usage',
'--disable-extensions',
].concat(runningUiTestOnCi),
windowTypes: ['app', 'webview'],
},
},
}
async function doStuff() {
console.log('Waiting for MQTT Broker on port 1880 (no auth)')
await mockMqtt()
console.log('start webdriver')
const browser = await webdriverio.remote(options)
console.log('Starting playwright/electron')
// Launch Electron app.
const electronApp: ElectronApplication = await electron.launch({
args: [`${__dirname}/../../..`, ...runningUiTestOnCi],
})
console.log('Playwright started')
// Get the first window that the app opens, wait if necessary.
const browser = await electronApp.firstWindow({ timeout: 3000 })
// Print the title.
console.log(await browser.title())
// Capture a screenshot.
await browser.screenshot({ path: 'intro.png' })
// Direct Electron console to Node terminal.
browser.on('console', console.log)
setFast()
await createFakeMousePointer(browser)
// Wait for Username input to be visible
await browser.$('//label[contains(text(), "Username")]/..//input')
await browser.locator('//label[contains(text(), "Username")]/..//input')
await connectTo('127.0.0.1', browser)
stopMqttUpdates()
await sleep(1000, true)
const heapDump = await getHeapDump(browser)
const initialTreeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.Tree)
const initialNodeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.TreeNode)
console.log(initialTreeOccurrences, initialNodeOccurrences)
await doX(3, async () => {
await reconnect(browser)
})
await sleep(1000, true)
await doX(15, async () => {
await searchTree('temp', browser)
await reconnect(browser)
})
await searchTree('ab', browser)
await clearSearch(browser)
await searchTree('temp', browser)
await clearSearch(browser)
await sleep(1000, true)
await waitForGarbageCollectorToDetermineLeak(browser, initialTreeOccurrences, initialNodeOccurrences)
}
async function waitForGarbageCollectorToDetermineLeak(
browser: any,
initialTreeOccurrences: number,
@@ -90,7 +77,6 @@ async function waitForGarbageCollectorToDetermineLeak(
const heapDump = await getHeapDump(browser)
const currentTreeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.Tree)
const currentNodeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.TreeNode)
// Temporary "leaks" are expected due to React Fibers memoization
if (
Math.abs(initialTreeOccurrences - currentTreeOccurrences) > 1 ||
@@ -107,21 +93,17 @@ async function waitForGarbageCollectorToDetermineLeak(
} else {
leak = false
}
const treeDelta = lastTreeOccurrences >= 0 ? currentTreeOccurrences - lastTreeOccurrences : -1
const nodeDelta = lastTreeOccurrences >= 0 ? currentNodeOccurrences - lastNodeOccurrences : -1
delta = treeDelta + nodeDelta
lastTreeOccurrences = currentTreeOccurrences
lastNodeOccurrences = currentNodeOccurrences
}
if (leak) {
console.error('leak')
process.exit(100)
}
}
async function doX(x: number, action: () => Promise<any>) {
for (let i = 0; i < x; i += 1) {
await action()
+249
View File
@@ -0,0 +1,249 @@
/********************************************************************************
* Copyright (c) 2016-2018 Cirrus Link Solutions and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Cirrus Link Solutions - initial implementation
********************************************************************************/
import * as SparkplugClient from 'sparkplug-client'
import type { UPayload } from 'sparkplug-client'
import type { UMetric } from 'sparkplug-payload/lib/sparkplugbpayload'
/*
* Main sample function which includes the run() function for running the sample
*/
export interface MockSparkplugClient {
stop: () => void
}
var sample = (function () {
var config = {
serverUrl: 'tcp://127.0.0.1:1883',
username: '',
password: '',
groupId: 'Sparkplug Devices',
edgeNode: 'JavaScript Edge Node',
clientId: 'JavaScriptSimpleEdgeNode',
version: 'spBv1.0',
},
hwVersion = 'Emulated Hardware',
swVersion = 'v1.0.0',
deviceId = 'Emulated Device',
sparkPlugClient,
publishPeriod = 5000,
// Generates a random integer
randomInt = function () {
return 1 + Math.floor(Math.random() * 10)
},
// Get BIRTH payload for the edge node
getNodeBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{
name: 'Node Control/Rebirth',
type: 'Boolean',
value: false,
},
{
name: 'Template1',
type: 'Template',
value: {
isDefinition: true,
metrics: [
{ name: 'myBool', value: false, type: 'Boolean' },
{ name: 'myInt', value: 0, type: 'UInt32' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value1',
},
],
},
},
],
}
},
// Get BIRTH payload for the device
getDeviceBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'Float' },
{ name: 'my_int', value: randomInt(), type: 'Int8' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'Int64' },
{ name: 'Inputs/0', value: true, type: 'Boolean' },
{ name: 'Inputs/1', value: 0, type: 'Int8' },
{ name: 'Inputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Outputs/0', value: true, type: 'Boolean' },
{ name: 'Outputs/1', value: 0, type: 'Int16' },
{ name: 'Outputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Properties/hw_version', value: hwVersion, type: 'String' },
{ name: 'Properties/sw_version', value: swVersion, type: 'String' },
{
name: 'my_dataset',
type: 'DataSet',
value: {
numOfColumns: 2,
types: ['String', 'String'],
columns: ['str1', 'str2'],
rows: [
['x', 'a'],
['y', 'b'],
],
},
},
{
name: 'TemplateInstance1',
type: 'Template',
value: {
templateRef: 'Template1',
isDefinition: false,
metrics: [
{ name: 'myBool', value: true, type: 'Boolean' },
{ name: 'myInt', value: 100, type: 'Int8' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value2',
},
],
},
},
],
}
},
// Get data payload for the device
getDataPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'UInt64' },
{ name: 'my_int', value: randomInt(), type: 'Int16' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'UInt64' },
],
}
},
// Runs the sample
run = async function (): Promise<MockSparkplugClient> {
// Create the SparkplugClient
const sparkplugClient = SparkplugClient.newClient(config)
let updateInterval: NodeJS.Timeout | null = null
const connected = new Promise<MockSparkplugClient>((resolve) => {
// Create 'birth' handler
sparkplugClient.on('birth', () => {
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
resolve({
stop: () => {
if (updateInterval) {
clearInterval(updateInterval)
}
sparkplugClient.stop()
}
})
})
})
// Create Incoming Message Handler
sparkplugClient.on('message', function (topic: string, payload: UPayload) {
console.log(topic, payload)
})
// Create node command handler
// spell-checker: disable-next-line
sparkplugClient.on('ncmd', function (payload: UPayload) {
var timestamp = payload.timestamp,
metrics = payload.metrics
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name == 'Node Control/Rebirth' && metric.value) {
console.log("Received 'Rebirth' command")
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
}
}
}
})
// Create device command handler
// spell-checker: disable-next-line
sparkplugClient.on('dcmd', function (deviceId: string, payload: UPayload) {
var timestamp = payload.timestamp,
metrics = payload.metrics,
inboundMetricMap: { [name: string]: any } = {},
outboundMetric: Array<UMetric> = [],
outboundPayload: UPayload
console.log('Command received for device ' + deviceId)
// Loop over the metrics and store them in a map
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name !== undefined && metric.name !== null) {
inboundMetricMap[metric.name] = metric.value
}
}
}
if (inboundMetricMap['Outputs/0'] !== undefined && inboundMetricMap['Outputs/0'] !== null) {
console.log('Outputs/0: ' + inboundMetricMap['Outputs/0'])
outboundMetric.push({ name: 'Inputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
outboundMetric.push({ name: 'Outputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
console.log('Updated value for Inputs/0 ' + inboundMetricMap['Outputs/0'])
} else if (inboundMetricMap['Outputs/1'] !== undefined && inboundMetricMap['Outputs/1'] !== null) {
console.log('Outputs/1: ' + inboundMetricMap['Outputs/1'])
outboundMetric.push({ name: 'Inputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
outboundMetric.push({ name: 'Outputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
console.log('Updated value for Inputs/1 ' + inboundMetricMap['Outputs/1'])
} else if (inboundMetricMap['Outputs/2'] !== undefined && inboundMetricMap['Outputs/2'] !== null) {
console.log('Outputs/2: ' + inboundMetricMap['Outputs/2'])
outboundMetric.push({ name: 'Inputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
outboundMetric.push({ name: 'Outputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
console.log('Updated value for Inputs/2 ' + inboundMetricMap['Outputs/2'])
}
outboundPayload = {
timestamp: new Date().getTime(),
metrics: outboundMetric,
}
// Publish device data
sparkplugClient.publishDeviceData(deviceId, outboundPayload)
})
updateInterval = setInterval(function () {
// Publish device data
sparkplugClient.publishDeviceData(deviceId, getDataPayload())
}, 2000)
return connected
}
return { run: run }
})()
export default sample
+5 -5
View File
@@ -1,15 +1,15 @@
import { Browser, Element } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn, expandTopic, moveToCenterOfElement, sleep, writeText } from '../util'
export async function clearOldTopics(browser: Browser<'async'>) {
export async function clearOldTopics(browser: Page) {
const topics = ['hello', 'test 123']
for (const topic of topics) {
await expandTopic(topic, browser)
await sleep(1000)
const deleteButton = await browser.$('//button[contains(@title, "Delete retained topic")]')
await moveToCenterOfElement(deleteButton, browser)
await clickOn(deleteButton, browser)
const deleteButton = await browser.locator('//button[contains(@title, "Delete retained topic")]')
await moveToCenterOfElement(deleteButton)
await clickOn(deleteButton)
await sleep(700)
}
}
+5 -6
View File
@@ -1,11 +1,10 @@
import { Browser, Element } from 'webdriverio'
import { clickOn, setTextInInput } from '../util'
export async function connectTo(host: string, browser: Browser<'async'>) {
import { Page, Locator } from 'playwright'
export async function connectTo(host: string, browser: Page) {
await setTextInInput('Host', host, browser)
await browser.saveScreenshot('screen1.png')
await browser.screenshot({ path: 'screen1.png' })
const connectButton = await browser.$('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton, browser)
const connectButton = await browser.locator('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton)
}
+4 -4
View File
@@ -1,7 +1,7 @@
import { Browser } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn } from '../util'
export async function copyTopicToClipboard(browser: Browser<'async'>) {
const copyButton = await browser.$('//span[contains(text(), "Topic")]//button')
await clickOn(copyButton, browser, 1)
export async function copyTopicToClipboard(browser: Page) {
const copyButton = await browser.locator('//span[contains(text(), "Topic")]//button[1]')
await clickOn(copyButton, 1)
}
+4 -4
View File
@@ -1,7 +1,7 @@
import { Browser } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn } from '../util'
export async function copyValueToClipboard(browser: Browser<'async'>) {
const copyButton = await browser.$('//span[contains(text(), "Value")]//button')
await clickOn(copyButton, browser, 1)
export async function copyValueToClipboard(browser: Page) {
const copyButton = await browser.getByRole('button', { name: 'Value' }).getByRole('button').first()
await clickOn(copyButton, 1)
}
+4 -4
View File
@@ -1,7 +1,7 @@
import { Browser, Element } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn } from '../util'
export async function disconnect(browser: Browser<'async'>) {
const disconnectButton = await browser.$('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton, browser)
export async function disconnect(browser: Page) {
const disconnectButton = await browser.locator('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton)
}
+17 -16
View File
@@ -1,4 +1,4 @@
import { Browser, Element } from 'webdriverio'
import { Page, Locator } from 'playwright'
import {
clickOn,
sleep,
@@ -9,30 +9,31 @@ import {
showText,
} from '../util'
export async function publishTopic(browser: Browser<'async'>) {
export async function publishTopic(browser: Page) {
await expandTopic('kitchen/lamp/state', browser)
const topicInput = await browser.$('//input[contains(@value,"kitchen/lamp/state")][1]')
await clickOn(topicInput, browser)
await deleteTextWithBackspaces(topicInput, browser, 120, 5)
await writeText('set', browser, 300)
const topicInput = await browser.locator('//input[contains(@value,"kitchen/lamp/state")][1]')
await clickOn(topicInput)
await deleteTextWithBackspaces(topicInput, 120, 5)
await writeText('set', topicInput)
const payloadInput = await browser.$('//*[contains(@class, "ace_text-input")]')
const payloadInput = await browser.locator('//*[contains(@class, "ace_text-input")]')
await writeTextPayload(payloadInput, 'off')
await sleep(500)
const formatJsonButton = await browser.$('#sidebar-publish-format-json')
await clickOn(formatJsonButton, browser)
const formatJsonButton = await browser.locator('#sidebar-publish-format-json')
await clickOn(formatJsonButton)
const publishButton = await browser.$('#publish-button')
await moveToCenterOfElement(publishButton, browser)
const publishButton = await browser.locator('#publish-button')
await moveToCenterOfElement(publishButton)
await showText('Lamp turns on', 1000, browser, 'top')
await sleep(500)
await clickOn(publishButton, browser)
await clickOn(publishButton)
const sidebarDrawer = await browser.$('#Sidebar')
await sidebarDrawer.scrollIntoView()
const sidebarDrawer = await browser.locator('#Sidebar')
await sidebarDrawer.scrollIntoViewIfNeeded()
}
async function writeTextPayload(payloadInput: any, text: string) {
await payloadInput.setValue(text)
async function writeTextPayload(payloadInput: Locator, text: string) {
await clickOn(payloadInput)
await writeText(text, payloadInput)
}
+6 -6
View File
@@ -1,9 +1,9 @@
import { Browser, Element } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn } from '../util'
export async function reconnect(browser: Browser<'async'>) {
const disconnectButton = await browser.$('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton, browser)
const connectButton = await browser.$('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton, browser)
export async function reconnect(browser: Page) {
const disconnectButton = await browser.locator('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton)
const connectButton = await browser.locator('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton)
}
+9 -9
View File
@@ -1,15 +1,15 @@
import { Browser, Element } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn, deleteTextWithBackspaces, showText, sleep, writeText } from '../util'
export async function searchTree(text: string, browser: Browser<'async'>) {
const searchField = await browser.$('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, browser, 1)
await writeText(text, browser, 100)
export async function searchTree(text: string, browser: Page) {
const searchField = await browser.locator('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, 1)
await writeText(text, searchField)
await sleep(1500)
}
export async function clearSearch(browser: Browser<'async'>) {
const searchField = await browser.$('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, browser, 1)
await deleteTextWithBackspaces(searchField, browser, 100)
export async function clearSearch(browser: Page) {
const searchField = await browser.locator('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, 1)
await deleteTextWithBackspaces(searchField, 100)
}
@@ -1,30 +1,30 @@
import { Browser } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn, sleep, setInputText } from '../util'
export async function showAdvancedConnectionSettings(browser: Browser<'async'>) {
const advancedSettingsButton = await browser.$('//button/span[contains(text(),"Advanced")]')
const addButton = await browser.$('//button/span[contains(text(),"Add")]')
const topicInput = await browser.$('//*[contains(@class, "advanced-connection-settings-topic-input")]//input')
export async function showAdvancedConnectionSettings(browser: Page) {
const advancedSettingsButton = await browser.locator('//button/span[contains(text(),"Advanced")]')
const addButton = await browser.locator('//button/span[contains(text(),"Add")]')
const topicInput = await browser.locator('//*[contains(@class, "advanced-connection-settings-topic-input")]//input')
await clickOn(advancedSettingsButton, browser)
await clickOn(advancedSettingsButton)
await setInputText(topicInput, 'garden/#', browser)
await clickOn(addButton, browser)
await clickOn(addButton)
await setInputText(topicInput, 'livingroom/#', browser)
await clickOn(addButton, browser)
await clickOn(addButton)
await deleteFirstSubscribedTopic(browser)
await deleteFirstSubscribedTopic(browser)
await sleep(1000)
const backButton = await browser.$('//button/span[contains(text(),"Back")]')
await clickOn(backButton, browser)
const backButton = await browser.locator('//button/span[contains(text(),"Back")]').first()
await clickOn(backButton)
const connectButton = await browser.$('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton, browser)
const connectButton = await browser.locator('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton)
}
async function deleteFirstSubscribedTopic(browser: Browser<'async'>) {
const deleteButton = await browser.$('.advanced-connection-settings-topic-list button')
await clickOn(deleteButton, browser)
async function deleteFirstSubscribedTopic(browser: Page) {
const deleteButton = await browser.locator('.advanced-connection-settings-topic-list button').first()
await clickOn(deleteButton)
}
+3 -3
View File
@@ -1,8 +1,8 @@
import { Browser, Element } from 'webdriverio'
import { Page, Locator } from 'playwright'
import { expandTopic, sleep } from '../util'
export async function showJsonPreview(browser: Browser<'async'>) {
export async function showJsonPreview(browser: Page) {
await expandTopic('actuality/showcase', browser)
await browser.saveScreenshot('screen3.png')
await browser.screenshot({ path: 'screen3.png' })
await sleep(1000)
}
+14 -14
View File
@@ -1,31 +1,31 @@
import { Browser } from 'webdriverio'
import { Page } from 'playwright'
import { clickOn, showText, sleep } from '../util'
export async function showMenu(browser: Browser<'async'>) {
const menuButton = await browser.$('//button[contains(@aria-label, "Menu")]')
await clickOn(menuButton, browser)
export async function showMenu(browser: Page) {
const menuButton = await browser.locator('//button[contains(@aria-label, "Menu")]')
await clickOn(menuButton)
// const brokerStatistics = await browser.$('//div[contains(@class, "BrokerStatistics")]/div[1]')
// moveToCenterOfElement(brokerStatistics, browser)
await sleep(2000)
await browser.saveScreenshot('screen4.png')
await browser.screenshot({ path: 'screen4.png' })
const topicOrder = await browser.$('//input[@name="node-order"]/../div')
await clickOn(topicOrder, browser)
const topicOrder = await browser.locator('//input[@name="node-order"]/../div')
await clickOn(topicOrder)
await sleep(1000)
const alphabetically = await browser.$('//li[contains(@data-value, "abc")]')
await clickOn(alphabetically, browser)
const alphabetically = await browser.locator('//li[contains(@data-value, "abc")]')
await clickOn(alphabetically)
await sleep(2000)
await showText('Dark Mode', 1500, browser, 'top')
await sleep(1500)
const themeSwitch = await browser.$('//*[contains(text(), "Dark Mode")]/..//input')
await clickOn(themeSwitch, browser)
const themeSwitch = await browser.locator('//*[contains(text(), "Dark Mode")]/..//input')
await clickOn(themeSwitch)
await sleep(3000)
await browser.saveScreenshot('screen_dark_mode.png')
await clickOn(themeSwitch, browser)
await browser.screenshot({ path: 'screen_dark_mode.png' })
await clickOn(themeSwitch)
await clickOn(menuButton, browser)
await clickOn(menuButton)
}
+26 -22
View File
@@ -1,10 +1,10 @@
import { Browser, Element } from 'webdriverio'
import { moveToCenterOfElement, clickOn, clickOnHistory, expandTopic, sleep, writeText } from '../util'
import { Page } from 'playwright'
import { moveToCenterOfElement, clickOn, clickOnHistory, expandTopic, sleep } from '../util'
export async function showNumericPlot(browser: Browser<'async'>) {
export async function showNumericPlot(browser: Page) {
await expandTopic('kitchen/coffee_maker', browser)
let heater = await valuePreviewGuttersShowChartIcon('heater', browser)
await moveToCenterOfElement(heater, browser)
await moveToCenterOfElement(heater)
await sleep(1000)
// Refocus and click
heater = await valuePreviewGuttersShowChartIcon('heater', browser)
@@ -12,7 +12,7 @@ export async function showNumericPlot(browser: Browser<'async'>) {
await sleep(1000)
let temperature = await valuePreviewGuttersShowChartIcon('temperature', browser)
await moveToCenterOfElement(temperature, browser)
await moveToCenterOfElement(temperature)
await sleep(1000)
// Refocus and click
temperature = await valuePreviewGuttersShowChartIcon('temperature', browser)
@@ -30,7 +30,7 @@ export async function showNumericPlot(browser: Browser<'async'>) {
await clickAway('temperature', browser)
await sleep(2500)
await browser.saveScreenshot('screen_chart_panel.png')
await browser.screenshot({ path: 'screen_chart_panel.png' })
await removeChart('heater', browser)
await sleep(750)
@@ -42,34 +42,38 @@ export async function showNumericPlot(browser: Browser<'async'>) {
await clickOnHistory(browser)
}
async function valuePreviewGuttersShowChartIcon(name: string, browser: Browser<'async'>) {
async function valuePreviewGuttersShowChartIcon(name: string, browser: Page) {
for (let retries = 0; retries < 2; retries += 1) {
try {
return await browser.$(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`)
return await browser.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`).first()
} catch {
// ignore
}
}
return browser.$(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`)
return browser.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`).first()
}
async function chartSettings(name: string, browser: Browser<'async'>) {
const settings = await browser.$(`//*[contains(@data-test-type, "ChartSettings")][contains(@data-test, "${name}")]`)
return clickOn(settings, browser)
async function chartSettings(name: string, browser: Page) {
const settings = await browser.locator(
`//*[contains(@data-test-type, "ChartSettings")][contains(@data-test, "${name}")]`
)
return clickOn(settings)
}
async function clickAway(name: string, browser: Browser<'async'>) {
const settings = await browser.$(`//*[contains(@data-test-type, "ChartPaper")][contains(@data-test, "${name}")]`)
await moveToCenterOfElement(settings, browser)
await browser.keys(['Escape'])
async function clickAway(name: string, browser: Page) {
const settings = await browser.locator(
`//*[contains(@data-test-type, "ChartPaper")][contains(@data-test, "${name}")]`
)
await moveToCenterOfElement(settings)
await settings.press('Escape')
}
async function removeChart(name: string, browser: Browser<'async'>) {
const remove = await browser.$(`//*[contains(@data-test-type, "RemoveChart")][contains(@data-test, "${name}")]`)
return clickOn(remove, browser)
async function removeChart(name: string, browser: Page) {
const remove = await browser.locator(`//*[contains(@data-test-type, "RemoveChart")][contains(@data-test, "${name}")]`)
return clickOn(remove)
}
async function clickOnMenuPoint(name: string, browser: Browser<'async'>) {
const item = await browser.$(`//li/span[contains(text(), "${name}")]`)
return clickOn(item, browser)
async function clickOnMenuPoint(name: string, browser: Page) {
const item = await browser.locator(`//li/span[contains(text(), "${name}")]`)
return clickOn(item)
}

Some files were not shown because too many files have changed in this diff Show More