Compare commits
45 Commits
v2.0.1
...
a31a0b4829
| Author | SHA1 | Date | |
|---|---|---|---|
| a31a0b4829 | |||
|
|
959d1e3c1f | ||
|
|
bda5aa9238 | ||
|
|
4e5da3f322 | ||
|
|
826576516f | ||
|
|
933c7cc307 | ||
|
|
9471f0b5ac | ||
|
|
4d774937df | ||
|
|
3702654ec3 | ||
|
|
7d63422555 | ||
|
|
fa6fc5fb34 | ||
|
|
86d865ce1b | ||
|
|
516dd6b611 | ||
|
|
df421fcccb | ||
|
|
a050189e12 | ||
|
|
7bcdc3276f | ||
|
|
9f9e25a796 | ||
|
|
c4a095a094 | ||
|
|
bf4716e8df | ||
|
|
574e832152 | ||
|
|
2a84799832 | ||
|
|
8adf3c8261 | ||
|
|
b3245aba9b | ||
|
|
dac2149fbd | ||
|
|
e501f6d125 | ||
|
|
341f26f197 | ||
|
|
5e28643a76 | ||
|
|
b35132451c | ||
|
|
6b0aeae504 | ||
|
|
950c77886a | ||
|
|
51221d37d0 | ||
|
|
d02baa4e8d | ||
|
|
41b3db0457 | ||
|
|
b6c488b7d4 | ||
|
|
c4b09b7a14 | ||
|
|
e201779341 | ||
|
|
321d19c5c2 | ||
|
|
56c417fd0e | ||
|
|
d3576031bb | ||
|
|
f6c3b38976 | ||
|
|
cc8fa9d611 | ||
|
|
49be089a23 | ||
|
|
157736a99d | ||
|
|
86f3f0c8e3 | ||
|
|
c991503e33 |
65
.github/workflows/docker-build.yml
vendored
Normal file
65
.github/workflows/docker-build.yml
vendored
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# Tagging based on: https://docs.docker.com/build/ci/github-actions/manage-tags-labels/
|
||||||
|
# Multi platform based on: https://docs.docker.com/build/ci/github-actions/multi-platform/
|
||||||
|
name: build
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- "**"
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
inverter_gui_pipeline:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: "Setup"
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: '1.22'
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
uses: golangci/golangci-lint-action@v3
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: go test -v -race -coverprofile=coverage.txt -covermode=atomic ./...
|
||||||
|
|
||||||
|
- name: Upload code coverage
|
||||||
|
uses: codecov/codecov-action@v3
|
||||||
|
|
||||||
|
- name: Generate docker image labels and tags
|
||||||
|
id: docker_meta
|
||||||
|
uses: docker/metadata-action@v4
|
||||||
|
with:
|
||||||
|
images: ghcr.io/diebietse/invertergui
|
||||||
|
tags: |
|
||||||
|
type=ref,event=branch
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v2
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v2
|
||||||
|
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build and push to GitHub Container Registry
|
||||||
|
uses: docker/build-push-action@v4
|
||||||
|
with:
|
||||||
|
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.docker_meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -22,3 +22,5 @@ _testmain.go
|
|||||||
*.exe
|
*.exe
|
||||||
*.test
|
*.test
|
||||||
*.prof
|
*.prof
|
||||||
|
|
||||||
|
vendor/
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
run:
|
|
||||||
deadline: 10m
|
|
||||||
|
|
||||||
linters:
|
|
||||||
enable-all: false
|
|
||||||
enable:
|
|
||||||
# Enabled by default in golangci-lint v1.13.2
|
|
||||||
- deadcode
|
|
||||||
- errcheck
|
|
||||||
- govet
|
|
||||||
- ineffassign
|
|
||||||
- typecheck
|
|
||||||
- varcheck
|
|
||||||
# Disabled by default in golangci-lint v1.13.2
|
|
||||||
- dupl
|
|
||||||
- goconst
|
|
||||||
- gofmt
|
|
||||||
- golint
|
|
||||||
- unconvert
|
|
||||||
# The following result in high memory usage (>1GB)
|
|
||||||
# https://github.com/golangci/golangci-lint/issues/337
|
|
||||||
- staticcheck
|
|
||||||
- structcheck
|
|
||||||
- gosimple
|
|
||||||
- unused
|
|
||||||
|
|
||||||
issues:
|
|
||||||
max-per-linter: 0
|
|
||||||
max-same-issues: 0
|
|
||||||
28
.travis.yml
28
.travis.yml
@@ -1,28 +0,0 @@
|
|||||||
sudo: false
|
|
||||||
|
|
||||||
language: go
|
|
||||||
|
|
||||||
env:
|
|
||||||
- GO111MODULE=on
|
|
||||||
|
|
||||||
go:
|
|
||||||
- 1.14.x
|
|
||||||
|
|
||||||
git:
|
|
||||||
depth: 1
|
|
||||||
|
|
||||||
install: true
|
|
||||||
|
|
||||||
notifications:
|
|
||||||
email: false
|
|
||||||
|
|
||||||
before_script:
|
|
||||||
- curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.26.0
|
|
||||||
- go mod vendor
|
|
||||||
|
|
||||||
script:
|
|
||||||
- golangci-lint run
|
|
||||||
- go test -v -race -coverprofile=coverage.txt -covermode=atomic ./...
|
|
||||||
|
|
||||||
after_success:
|
|
||||||
- bash <(curl -s https://codecov.io/bash)
|
|
||||||
10
.vscode/settings.json
vendored
10
.vscode/settings.json
vendored
@@ -10,5 +10,13 @@
|
|||||||
"[go]": {
|
"[go]": {
|
||||||
"editor.insertSpaces": false,
|
"editor.insertSpaces": false,
|
||||||
"editor.tabSize": 4
|
"editor.tabSize": 4
|
||||||
}
|
},
|
||||||
|
"cSpell.words": [
|
||||||
|
"diebietse",
|
||||||
|
"ghaction",
|
||||||
|
"ghcr",
|
||||||
|
"golangci",
|
||||||
|
"invertergui",
|
||||||
|
"semver"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
22
Dockerfile
22
Dockerfile
@@ -1,14 +1,14 @@
|
|||||||
FROM golang:alpine as builder
|
FROM golang:1.22-alpine as builder
|
||||||
RUN apk add git
|
|
||||||
RUN mkdir /build
|
RUN mkdir /build
|
||||||
COPY . /build/
|
COPY . /build/
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
RUN go build -o invertergui ./cmd/invertergui
|
RUN CGO_ENABLED=0 go build -o invertergui ./cmd/invertergui
|
||||||
FROM alpine
|
|
||||||
RUN adduser -S -D -H -h /app inverteruser
|
FROM scratch
|
||||||
RUN addgroup inverteruser dialout
|
|
||||||
USER inverteruser
|
# Group ID 20 is dialout, needed for tty read/write access
|
||||||
COPY --from=builder /build/invertergui /app/
|
USER 3000:20
|
||||||
WORKDIR /app
|
COPY --from=builder /build/invertergui /bin/
|
||||||
ENTRYPOINT [ "./invertergui" ]
|
ENTRYPOINT [ "/bin/invertergui" ]
|
||||||
CMD []
|
EXPOSE 8080
|
||||||
|
|||||||
12
Makefile
12
Makefile
@@ -39,21 +39,15 @@ gofmt:
|
|||||||
gofmt -l -s -w .
|
gofmt -l -s -w .
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -v ./...
|
|
||||||
|
|
||||||
test-race:
|
|
||||||
go test -v -race ./...
|
go test -v -race ./...
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
docker build --tag invertergui .
|
docker build --tag invertergui .
|
||||||
|
|
||||||
statik:
|
|
||||||
statik -f -p=frontend -src=./frontend/root
|
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
docker run --rm -it \
|
docker run --rm -it \
|
||||||
-w /src -v $(shell pwd):/src \
|
-w /src -v $(shell pwd):/src \
|
||||||
golangci/golangci-lint:v1.26 golangci-lint run \
|
golangci/golangci-lint:v1.56 golangci-lint run \
|
||||||
-v -c .golangci.yml
|
-v -c .golangci.yml
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
@@ -62,3 +56,7 @@ clean:
|
|||||||
vendor:
|
vendor:
|
||||||
go mod tidy
|
go mod tidy
|
||||||
go mod vendor
|
go mod vendor
|
||||||
|
|
||||||
|
.PHONY: upgrade-vendor
|
||||||
|
upgrade-vendor:
|
||||||
|
go get -u ./...
|
||||||
|
|||||||
134
README.md
134
README.md
@@ -1,10 +1,13 @@
|
|||||||
# Inverter GUI
|
# Inverter GUI
|
||||||
|
|
||||||
[](https://travis-ci.org/diebietse/invertergui)
|
[![release][release-badge]][release-link]
|
||||||
|
[![publish-docker-image][publish-docker-badge]][publish-docker-link]
|
||||||
|
![license][license-link]
|
||||||
|
[![codecov][codecov-badge]][codecov-link]
|
||||||
|
|
||||||
The invertergui allows the monitoring of a [Victron Multiplus](https://www.victronenergy.com/inverters-chargers/multiplus-12v-24v-48v-800va-3kva) via the [MK3/MK2 USB](https://www.victronenergy.com/accessories/interface-mk3-usb) or the MK2 RS232.
|
The invertergui allows the monitoring of a [Victron Multiplus](https://www.victronenergy.com/inverters-chargers/multiplus-12v-24v-48v-800va-3kva) via the [MK3/MK2 USB](https://www.victronenergy.com/accessories/interface-mk3-usb) or the MK2 RS232.
|
||||||
|
|
||||||
The [`diebietse/invertergui`](https://hub.docker.com/r/diebietse/invertergui) docker image is a build of this repository.
|
The [`ghcr.io/diebietse/invertergui`](https://github.com/orgs/diebietse/packages/container/package/invertergui) docker image is a build of this repository.
|
||||||
|
|
||||||
## Demo
|
## Demo
|
||||||
|
|
||||||
@@ -13,12 +16,12 @@ The [`diebietse/invertergui`](https://hub.docker.com/r/diebietse/invertergui) do
|
|||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
```console
|
```console
|
||||||
docker run --name invertergui --device /dev/ttyUSB0:/dev/ttyUSB0 -p 8080:8080 diebietse/invertergui
|
docker run --name invertergui --device /dev/ttyUSB0:/dev/ttyUSB0 -p 8080:8080 ghcr.io/diebietse/invertergui
|
||||||
```
|
```
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
This project makes use of [Go Modules](https://github.com/golang/go/wiki/Modules). The minimum version for Go is 1.11.x.
|
This project makes use of [Go Modules](https://github.com/golang/go/wiki/Modules). The minimum supported version for Go is 1.22
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
|
|
||||||
@@ -27,19 +30,25 @@ Usage:
|
|||||||
invertergui [OPTIONS]
|
invertergui [OPTIONS]
|
||||||
|
|
||||||
Application Options:
|
Application Options:
|
||||||
--address= The IP/DNS and port of the machine that the application is running on. (default: :8080)
|
--address= The IP/DNS and port of the machine that the application is running on. (default: :8080) [$ADDRESS]
|
||||||
[$ADDRESS]
|
--data.source= Set the source of data for the inverter gui. "serial", "tcp" or "mock" (default: serial) [$DATA_SOURCE]
|
||||||
--data.source= Set the source of data for the inverter gui. "serial", "tcp" or "mock" (default: serial)
|
|
||||||
[$DATA_SOURCE]
|
|
||||||
--data.host= Host to connect when source is set to tcp. (default: localhost:8139) [$DATA_HOST]
|
--data.host= Host to connect when source is set to tcp. (default: localhost:8139) [$DATA_HOST]
|
||||||
--data.device= TTY device to use when source is set to serial. (default: /dev/ttyUSB0) [$DATA_DEVICE]
|
--data.device= TTY device to use when source is set to serial. (default: /dev/ttyUSB0) [$DATA_DEVICE]
|
||||||
--cli.enabled Enable CLI output. [$CLI_ENABLED]
|
--cli.enabled Enable CLI output. [$CLI_ENABLED]
|
||||||
--mqtt.enabled Enable MQTT publishing. [$MQTT_ENABLED]
|
--mqtt.enabled Enable MQTT publishing. [$MQTT_ENABLED]
|
||||||
--mqtt.broker= Set the host port and scheme of the MQTT broker. (default: tcp://localhost:1883) [$MQTT_BROKER]
|
--mqtt.broker= Set the host port and scheme of the MQTT broker. (default: tcp://localhost:1883) [$MQTT_BROKER]
|
||||||
--mqtt.client_id= Set the client ID for the MQTT connection. (default: interter-gui) [$MQTT_CLIENT_ID]
|
--mqtt.client_id= Set the client ID for the MQTT connection. (default: inverter-gui) [$MQTT_CLIENT_ID]
|
||||||
--mqtt.topic= Set the MQTT topic updates published to. (default: invertergui/updates) [$MQTT_TOPIC]
|
--mqtt.topic= Set the MQTT topic updates published to. (default: invertergui/updates) [$MQTT_TOPIC]
|
||||||
|
--mqtt.command_topic= Set the MQTT topic that receives write commands for Victron settings/RAM variables. (default: invertergui/settings/set) [$MQTT_COMMAND_TOPIC]
|
||||||
|
--mqtt.status_topic= Set the MQTT topic where write command status updates are published. (default: invertergui/settings/status) [$MQTT_STATUS_TOPIC]
|
||||||
|
--mqtt.ha.enabled Enable Home Assistant MQTT discovery integration. [$MQTT_HA_ENABLED]
|
||||||
|
--mqtt.ha.discovery_prefix= Set Home Assistant MQTT discovery prefix. (default: homeassistant) [$MQTT_HA_DISCOVERY_PREFIX]
|
||||||
|
--mqtt.ha.node_id= Set Home Assistant node ID used for discovery topics and unique IDs. (default: invertergui) [$MQTT_HA_NODE_ID]
|
||||||
|
--mqtt.ha.device_name= Set Home Assistant device display name. (default: Victron Inverter) [$MQTT_HA_DEVICE_NAME]
|
||||||
--mqtt.username= Set the MQTT username [$MQTT_USERNAME]
|
--mqtt.username= Set the MQTT username [$MQTT_USERNAME]
|
||||||
--mqtt.password= Set the MQTT password [$MQTT_PASSWORD]
|
--mqtt.password= Set the MQTT password [$MQTT_PASSWORD]
|
||||||
|
--mqtt.password-file= Path to a file containing the MQTT password [$MQTT_PASSWORD_FILE]
|
||||||
|
--loglevel= The log level to generate logs at. ("panic", "fatal", "error", "warn", "info", "debug", "trace") (default: info) [$LOGLEVEL]
|
||||||
|
|
||||||
Help Options:
|
Help Options:
|
||||||
-h, --help Show this help message
|
-h, --help Show this help message
|
||||||
@@ -80,6 +89,20 @@ Battery Power: -0.659 W
|
|||||||
Battery Charge: 100.000 %
|
Battery Charge: 100.000 %
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The web UI also includes a **Remote Panel Control** section for:
|
||||||
|
|
||||||
|
- Remote Panel Mode (`on`, `off`, `charger_only`, `inverter_only`)
|
||||||
|
- Remote Panel Current Limit (AC input current limit in amps)
|
||||||
|
- Remote Panel Standby (prevent sleep while turned off)
|
||||||
|
|
||||||
|
The combined mode + current limit action maps to the same behavior as
|
||||||
|
`set_remote_panel_state` in `victron-mk3`.
|
||||||
|
|
||||||
|
The backing HTTP API endpoints are:
|
||||||
|
|
||||||
|
- `GET/POST /api/remote-panel/state`
|
||||||
|
- `GET/POST /api/remote-panel/standby`
|
||||||
|
|
||||||
### Munin
|
### Munin
|
||||||
|
|
||||||
The Munin plugin location is at /munin (http://localhost:8080/munin).
|
The Munin plugin location is at /munin (http://localhost:8080/munin).
|
||||||
@@ -279,16 +302,97 @@ The MQTT client will publish updates to the given broker at the set topic.
|
|||||||
```bash
|
```bash
|
||||||
--mqtt.enabled Enable MQTT publishing. [$MQTT_ENABLED]
|
--mqtt.enabled Enable MQTT publishing. [$MQTT_ENABLED]
|
||||||
--mqtt.broker= Set the host port and scheme of the MQTT broker. (default: tcp://localhost:1883) [$MQTT_BROKER]
|
--mqtt.broker= Set the host port and scheme of the MQTT broker. (default: tcp://localhost:1883) [$MQTT_BROKER]
|
||||||
--mqtt.client_id= Set the client ID for the MQTT connection. (default: interter-gui) [$MQTT_CLIENT_ID]
|
--mqtt.client_id= Set the client ID for the MQTT connection. (default: inverter-gui) [$MQTT_CLIENT_ID]
|
||||||
--mqtt.topic= Set the MQTT topic updates published to. (default: invertergui/updates) [$MQTT_TOPIC]
|
--mqtt.topic= Set the MQTT topic updates published to. (default: invertergui/updates) [$MQTT_TOPIC]
|
||||||
|
--mqtt.command_topic= Set the MQTT topic that receives write commands for Victron settings/RAM variables. (default: invertergui/settings/set) [$MQTT_COMMAND_TOPIC]
|
||||||
|
--mqtt.status_topic= Set the MQTT topic where write command status updates are published. (default: invertergui/settings/status) [$MQTT_STATUS_TOPIC]
|
||||||
|
--mqtt.ha.enabled Enable Home Assistant MQTT discovery integration. [$MQTT_HA_ENABLED]
|
||||||
|
--mqtt.ha.discovery_prefix= Set Home Assistant MQTT discovery prefix. (default: homeassistant) [$MQTT_HA_DISCOVERY_PREFIX]
|
||||||
|
--mqtt.ha.node_id= Set Home Assistant node ID used for discovery topics and unique IDs. (default: invertergui) [$MQTT_HA_NODE_ID]
|
||||||
|
--mqtt.ha.device_name= Set Home Assistant device display name. (default: Victron Inverter) [$MQTT_HA_DEVICE_NAME]
|
||||||
--mqtt.username= Set the MQTT username [$MQTT_USERNAME]
|
--mqtt.username= Set the MQTT username [$MQTT_USERNAME]
|
||||||
--mqtt.password= Set the MQTT password [$MQTT_PASSWORD]
|
--mqtt.password= Set the MQTT password [$MQTT_PASSWORD]
|
||||||
|
--mqtt.password-file= Path to a file containing the MQTT password [$MQTT_PASSWORD_FILE]
|
||||||
```
|
```
|
||||||
|
|
||||||
The MQTT client can be enabled by setting the environment variable `MQTT_ENABLED=true` or flag `--mqtt.enabled`.
|
The MQTT client can be enabled by setting the environment variable `MQTT_ENABLED=true` or flag `--mqtt.enabled`.
|
||||||
All MQTT configuration can be done via flags or as environment variables.
|
All MQTT configuration can be done via flags or as environment variables.
|
||||||
The URI for the broker can be configured format should be `scheme://host:port`, where "scheme" is one of "tcp", "ssl", or "ws".
|
The URI for the broker can be configured format should be `scheme://host:port`, where "scheme" is one of "tcp", "ssl", or "ws".
|
||||||
|
|
||||||
|
When `--mqtt.command_topic` is configured, the application subscribes to that topic and accepts JSON write commands.
|
||||||
|
The recommended command for inverter control follows the same model used by `victron-mk3`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"request_id": "optional-correlation-id",
|
||||||
|
"kind": "panel_state",
|
||||||
|
"switch": "on",
|
||||||
|
"current_limit": 16.5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`switch` supports `charger_only`, `inverter_only`, `on`, and `off` (or numeric values `1..4`).
|
||||||
|
`current_limit` is in amps and optional. If omitted, only the switch state is changed.
|
||||||
|
To update only the current limit (while preserving the last known mode), send:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"kind": "panel_state",
|
||||||
|
"current_limit": 12.0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If no prior mode is known (for example on a fresh broker state), this command is rejected until a mode command is sent once.
|
||||||
|
|
||||||
|
Standby can be controlled with:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"kind": "standby",
|
||||||
|
"standby": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Low-level writes are still supported:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"kind": "setting",
|
||||||
|
"id": 15,
|
||||||
|
"value": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`kind` supports `panel_state`, `setting`, and `ram_var` (with aliases for each).
|
||||||
|
The result is published to `--mqtt.status_topic` with status `ok` or `error`.
|
||||||
|
|
||||||
|
### Home Assistant
|
||||||
|
|
||||||
|
Enable Home Assistant auto-discovery with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
--mqtt.ha.enabled
|
||||||
|
```
|
||||||
|
|
||||||
|
When enabled, `invertergui` publishes retained discovery payloads and availability under:
|
||||||
|
|
||||||
|
- `{topic-root}/homeassistant/availability` (`online`/`offline`)
|
||||||
|
- `{discovery_prefix}/sensor/{node_id}/.../config`
|
||||||
|
- `{discovery_prefix}/binary_sensor/{node_id}/.../config`
|
||||||
|
- `{discovery_prefix}/select/{node_id}/remote_panel_mode/config` (if command topic is configured)
|
||||||
|
- `{discovery_prefix}/number/{node_id}/remote_panel_current_limit/config` (if command topic is configured)
|
||||||
|
- `{discovery_prefix}/switch/{node_id}/remote_panel_standby/config` (if command topic is configured)
|
||||||
|
|
||||||
|
The discovered entities include battery/input/output sensors, a data-valid diagnostic binary sensor,
|
||||||
|
plus remote panel controls for:
|
||||||
|
|
||||||
|
- `Remote Panel Mode` (`on`, `off`, `charger_only`, `inverter_only`)
|
||||||
|
- `Remote Panel Current Limit` (AC input current limit in amps)
|
||||||
|
- `Remote Panel Standby` (prevent device sleep while off)
|
||||||
|
|
||||||
|
The combined mode + current limit behavior is provided through the `panel_state` MQTT command kind,
|
||||||
|
which mirrors `victron_mk3.set_remote_panel_state`.
|
||||||
|
|
||||||
## TTY Device
|
## TTY Device
|
||||||
|
|
||||||
The intertergui application makes use of a serial tty device to monitor the Multiplus.
|
The intertergui application makes use of a serial tty device to monitor the Multiplus.
|
||||||
@@ -350,4 +454,12 @@ The last four lines are optional, but is useful when debugging and logging conne
|
|||||||
|
|
||||||
This repos includes a [Grafana](https://grafana.com/) dashboard in the [grafana folder](./grafana/prometheus-dashboard.json) that you can import. This is useful if you are using prometheus to log your data and want to display it in a nice way.
|
This repos includes a [Grafana](https://grafana.com/) dashboard in the [grafana folder](./grafana/prometheus-dashboard.json) that you can import. This is useful if you are using prometheus to log your data and want to display it in a nice way.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
[publish-docker-badge]: https://github.com/diebietse/invertergui/actions/workflows/docker-build.yml/badge.svg
|
||||||
|
[publish-docker-link]: https://github.com/diebietse/invertergui/actions/workflows/docker-build.yml
|
||||||
|
[license-link]: https://img.shields.io/github/license/diebietse/invertergui.svg
|
||||||
|
[release-badge]: https://img.shields.io/github/v/release/diebietse/invertergui
|
||||||
|
[release-link]: https://github.com/diebietse/invertergui/releases
|
||||||
|
[codecov-badge]: https://codecov.io/gh/diebietse/invertergui/branch/master/graph/badge.svg?token=xTLfEzoqYF
|
||||||
|
[codecov-link]: https://codecov.io/gh/diebietse/invertergui
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/jessevdk/go-flags"
|
"github.com/jessevdk/go-flags"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,13 +19,23 @@ type config struct {
|
|||||||
Enabled bool `long:"cli.enabled" env:"CLI_ENABLED" description:"Enable CLI output."`
|
Enabled bool `long:"cli.enabled" env:"CLI_ENABLED" description:"Enable CLI output."`
|
||||||
}
|
}
|
||||||
MQTT struct {
|
MQTT struct {
|
||||||
Enabled bool `long:"mqtt.enabled" env:"MQTT_ENABLED" description:"Enable MQTT publishing."`
|
Enabled bool `long:"mqtt.enabled" env:"MQTT_ENABLED" description:"Enable MQTT publishing."`
|
||||||
Broker string `long:"mqtt.broker" env:"MQTT_BROKER" default:"tcp://localhost:1883" description:"Set the host port and scheme of the MQTT broker."`
|
Broker string `long:"mqtt.broker" env:"MQTT_BROKER" default:"tcp://localhost:1883" description:"Set the host port and scheme of the MQTT broker."`
|
||||||
ClientID string `long:"mqtt.client_id" env:"MQTT_CLIENT_ID" default:"interter-gui" description:"Set the client ID for the MQTT connection."`
|
ClientID string `long:"mqtt.client_id" env:"MQTT_CLIENT_ID" default:"inverter-gui" description:"Set the client ID for the MQTT connection."`
|
||||||
Topic string `long:"mqtt.topic" env:"MQTT_TOPIC" default:"invertergui/updates" description:"Set the MQTT topic updates published to."`
|
Topic string `long:"mqtt.topic" env:"MQTT_TOPIC" default:"invertergui/updates" description:"Set the MQTT topic updates published to."`
|
||||||
Username string `long:"mqtt.username" env:"MQTT_USERNAME" default:"" description:"Set the MQTT username"`
|
CommandTopic string `long:"mqtt.command_topic" env:"MQTT_COMMAND_TOPIC" default:"invertergui/settings/set" description:"Set the MQTT topic that receives write commands for Victron settings/RAM variables."`
|
||||||
Password string `long:"mqtt.password" env:"MQTT_PASSWORD" default:"" description:"Set the MQTT password"`
|
StatusTopic string `long:"mqtt.status_topic" env:"MQTT_STATUS_TOPIC" default:"invertergui/settings/status" description:"Set the MQTT topic where write command status updates are published."`
|
||||||
|
HA struct {
|
||||||
|
Enabled bool `long:"mqtt.ha.enabled" env:"MQTT_HA_ENABLED" description:"Enable Home Assistant MQTT discovery integration."`
|
||||||
|
DiscoveryPrefix string `long:"mqtt.ha.discovery_prefix" env:"MQTT_HA_DISCOVERY_PREFIX" default:"homeassistant" description:"Set Home Assistant MQTT discovery prefix."`
|
||||||
|
NodeID string `long:"mqtt.ha.node_id" env:"MQTT_HA_NODE_ID" default:"invertergui" description:"Set Home Assistant node ID used for discovery topics and unique IDs."`
|
||||||
|
DeviceName string `long:"mqtt.ha.device_name" env:"MQTT_HA_DEVICE_NAME" default:"Victron Inverter" description:"Set Home Assistant device display name."`
|
||||||
|
}
|
||||||
|
Username string `long:"mqtt.username" env:"MQTT_USERNAME" default:"" description:"Set the MQTT username"`
|
||||||
|
Password string `long:"mqtt.password" env:"MQTT_PASSWORD" default:"" description:"Set the MQTT password"`
|
||||||
|
PasswordFile string `long:"mqtt.password-file" env:"MQTT_PASSWORD_FILE" default:"" description:"Path to a file containing the MQTT password"`
|
||||||
}
|
}
|
||||||
|
Loglevel string `long:"loglevel" env:"LOGLEVEL" default:"info" description:"The log level to generate logs at. (\"panic\", \"fatal\", \"error\", \"warn\", \"info\", \"debug\", \"trace\")"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseConfig() (*config, error) {
|
func parseConfig() (*config, error) {
|
||||||
@@ -30,5 +44,30 @@ func parseConfig() (*config, error) {
|
|||||||
if _, err := parser.Parse(); err != nil {
|
if _, err := parser.Parse(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := resolvePasswordFile(conf); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return conf, nil
|
return conf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func resolvePasswordFile(conf *config) error {
|
||||||
|
if conf.MQTT.PasswordFile != "" && conf.MQTT.Password != "" {
|
||||||
|
return fmt.Errorf("mqtt.password and mqtt.password-file are mutually exclusive")
|
||||||
|
}
|
||||||
|
if conf.MQTT.PasswordFile != "" {
|
||||||
|
password, err := readPasswordFile(conf.MQTT.PasswordFile)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
conf.MQTT.Password = password
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readPasswordFile(path string) (string, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("could not read MQTT password file: %w", err)
|
||||||
|
}
|
||||||
|
return strings.TrimRight(string(data), "\n\r"), nil
|
||||||
|
}
|
||||||
|
|||||||
107
cmd/invertergui/config_test.go
Normal file
107
cmd/invertergui/config_test.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testInlineSecret = "inline-secret"
|
||||||
|
|
||||||
|
func TestReadPasswordFile(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
content string
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "plain password",
|
||||||
|
content: "secret",
|
||||||
|
expected: "secret",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "password with trailing newline",
|
||||||
|
content: "secret\n",
|
||||||
|
expected: "secret",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "password with trailing carriage return and newline",
|
||||||
|
content: "secret\r\n",
|
||||||
|
expected: "secret",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty file",
|
||||||
|
content: "",
|
||||||
|
expected: "",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "password")
|
||||||
|
if err := os.WriteFile(path, []byte(tt.content), 0o600); err != nil {
|
||||||
|
t.Fatalf("failed to write test file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := readPasswordFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if got != tt.expected {
|
||||||
|
t.Errorf("got %q, want %q", got, tt.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadPasswordFile_NotFound(t *testing.T) {
|
||||||
|
_, err := readPasswordFile("/nonexistent/path/password")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for missing file, got nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvePassword_MutuallyExclusive(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "password")
|
||||||
|
if err := os.WriteFile(path, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatalf("failed to write test file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
conf := &config{}
|
||||||
|
conf.MQTT.Password = testInlineSecret
|
||||||
|
conf.MQTT.PasswordFile = path
|
||||||
|
|
||||||
|
err := resolvePasswordFile(conf)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error when both mqtt.password and mqtt.password-file are set, got nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvePassword_FromFile(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "password")
|
||||||
|
if err := os.WriteFile(path, []byte("file-secret\n"), 0o600); err != nil {
|
||||||
|
t.Fatalf("failed to write test file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
conf := &config{}
|
||||||
|
conf.MQTT.PasswordFile = path
|
||||||
|
|
||||||
|
if err := resolvePasswordFile(conf); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if conf.MQTT.Password != "file-secret" {
|
||||||
|
t.Errorf("got %q, want %q", conf.MQTT.Password, "file-secret")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvePassword_NoFile(t *testing.T) {
|
||||||
|
conf := &config{}
|
||||||
|
conf.MQTT.Password = testInlineSecret
|
||||||
|
|
||||||
|
if err := resolvePasswordFile(conf); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if conf.MQTT.Password != testInlineSecret {
|
||||||
|
t.Errorf("got %q, want %q", conf.MQTT.Password, testInlineSecret)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,14 +37,14 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/diebietse/invertergui/mk2core"
|
"invertergui/mk2core"
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
"github.com/diebietse/invertergui/plugins/cli"
|
"invertergui/plugins/cli"
|
||||||
"github.com/diebietse/invertergui/plugins/mqttclient"
|
"invertergui/plugins/mqttclient"
|
||||||
"github.com/diebietse/invertergui/plugins/munin"
|
"invertergui/plugins/munin"
|
||||||
"github.com/diebietse/invertergui/plugins/prometheus"
|
"invertergui/plugins/prometheus"
|
||||||
"github.com/diebietse/invertergui/plugins/webui"
|
"invertergui/plugins/webui"
|
||||||
"github.com/diebietse/invertergui/plugins/webui/static"
|
"invertergui/plugins/webui/static"
|
||||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
"github.com/tarm/serial"
|
"github.com/tarm/serial"
|
||||||
@@ -58,6 +58,11 @@ func main() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
log.Info("Starting invertergui")
|
log.Info("Starting invertergui")
|
||||||
|
logLevel, err := logrus.ParseLevel(conf.Loglevel)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Could not parse log level: %v", err)
|
||||||
|
}
|
||||||
|
logrus.SetLevel(logLevel)
|
||||||
|
|
||||||
mk2, err := getMk2Device(conf.Data.Source, conf.Data.Host, conf.Data.Device)
|
mk2, err := getMk2Device(conf.Data.Source, conf.Data.Host, conf.Data.Device)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -72,9 +77,15 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Webgui
|
// Webgui
|
||||||
gui := webui.NewWebGui(core.NewSubscription())
|
var writer mk2driver.SettingsWriter
|
||||||
|
if w, ok := mk2.(mk2driver.SettingsWriter); ok {
|
||||||
|
writer = w
|
||||||
|
}
|
||||||
|
gui := webui.NewWebGui(core.NewSubscription(), writer)
|
||||||
http.Handle("/", static.New())
|
http.Handle("/", static.New())
|
||||||
http.Handle("/ws", http.HandlerFunc(gui.ServeHub))
|
http.Handle("/ws", http.HandlerFunc(gui.ServeHub))
|
||||||
|
http.Handle("/api/remote-panel/state", http.HandlerFunc(gui.ServeRemotePanelState))
|
||||||
|
http.Handle("/api/remote-panel/standby", http.HandlerFunc(gui.ServeRemotePanelStandby))
|
||||||
|
|
||||||
// Munin
|
// Munin
|
||||||
mu := munin.NewMunin(core.NewSubscription())
|
mu := munin.NewMunin(core.NewSubscription())
|
||||||
@@ -88,13 +99,24 @@ func main() {
|
|||||||
// MQTT
|
// MQTT
|
||||||
if conf.MQTT.Enabled {
|
if conf.MQTT.Enabled {
|
||||||
mqttConf := mqttclient.Config{
|
mqttConf := mqttclient.Config{
|
||||||
Broker: conf.MQTT.Broker,
|
Broker: conf.MQTT.Broker,
|
||||||
Topic: conf.MQTT.Topic,
|
Topic: conf.MQTT.Topic,
|
||||||
ClientID: conf.MQTT.ClientID,
|
CommandTopic: conf.MQTT.CommandTopic,
|
||||||
|
StatusTopic: conf.MQTT.StatusTopic,
|
||||||
|
ClientID: conf.MQTT.ClientID,
|
||||||
|
HomeAssistant: mqttclient.HomeAssistantConfig{
|
||||||
|
Enabled: conf.MQTT.HA.Enabled,
|
||||||
|
DiscoveryPrefix: conf.MQTT.HA.DiscoveryPrefix,
|
||||||
|
NodeID: conf.MQTT.HA.NodeID,
|
||||||
|
DeviceName: conf.MQTT.HA.DeviceName,
|
||||||
|
},
|
||||||
Username: conf.MQTT.Username,
|
Username: conf.MQTT.Username,
|
||||||
Password: conf.MQTT.Password,
|
Password: conf.MQTT.Password,
|
||||||
}
|
}
|
||||||
if err := mqttclient.New(core.NewSubscription(), mqttConf); err != nil {
|
if writer == nil {
|
||||||
|
log.Warn("MK2 data source does not support write commands; MQTT command topic will be ignored")
|
||||||
|
}
|
||||||
|
if err := mqttclient.New(core.NewSubscription(), writer, mqttConf); err != nil {
|
||||||
log.Fatalf("Could not setup MQTT client: %v", err)
|
log.Fatalf("Could not setup MQTT client: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
coverage:
|
|
||||||
precision: 2
|
|
||||||
round: down
|
|
||||||
range: "65...100"
|
|
||||||
35
go.mod
35
go.mod
@@ -1,14 +1,31 @@
|
|||||||
module github.com/diebietse/invertergui
|
module invertergui
|
||||||
|
|
||||||
|
go 1.26
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/eclipse/paho.mqtt.golang v1.2.0
|
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||||
github.com/gorilla/websocket v1.4.0
|
github.com/gorilla/websocket v1.5.3
|
||||||
github.com/jessevdk/go-flags v1.4.0
|
github.com/jessevdk/go-flags v1.6.1
|
||||||
github.com/prometheus/client_golang v0.9.2
|
github.com/prometheus/client_golang v1.23.2
|
||||||
github.com/rakyll/statik v0.1.5
|
github.com/sirupsen/logrus v1.9.4
|
||||||
github.com/sirupsen/logrus v1.6.0
|
github.com/stretchr/testify v1.11.1
|
||||||
github.com/stretchr/testify v1.3.0
|
|
||||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
|
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
|
||||||
)
|
)
|
||||||
|
|
||||||
go 1.14
|
require (
|
||||||
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/kr/text v0.2.0 // indirect
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
github.com/prometheus/client_model v0.6.2 // indirect
|
||||||
|
github.com/prometheus/common v0.67.5 // indirect
|
||||||
|
github.com/prometheus/procfs v0.19.2 // indirect
|
||||||
|
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||||
|
golang.org/x/net v0.50.0 // indirect
|
||||||
|
golang.org/x/sync v0.19.0 // indirect
|
||||||
|
golang.org/x/sys v0.41.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.11 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
|
|||||||
121
go.sum
121
go.sum
@@ -1,44 +1,93 @@
|
|||||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0=
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/eclipse/paho.mqtt.golang v1.2.0 h1:1F8mhG9+aO5/xpdtFkW4SxOJB67ukuDC3t2y2qayIX0=
|
github.com/eclipse/paho.mqtt.golang v1.4.3 h1:2kwcUGn8seMUfWndX0hGbvH8r7crgcJguQNCyp70xik=
|
||||||
github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts=
|
github.com/eclipse/paho.mqtt.golang v1.4.3/go.mod h1:CSYvoAlsMkhYOXh/oKyxa8EcBci6dVkLCbo5tTC1RIE=
|
||||||
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
|
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||||
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc=
|
||||||
|
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
|
||||||
|
github.com/jessevdk/go-flags v1.6.1 h1:Cvu5U8UGrLay1rZfv/zP7iLpSHGUZ/Ou68T0iX1bBK4=
|
||||||
|
github.com/jessevdk/go-flags v1.6.1/go.mod h1:Mk8T1hIAWpOiJiHa9rJASDK2UGWji0EuPGBnNLMooyc=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/prometheus/client_golang v0.9.2 h1:awm861/B8OKDd2I/6o1dy3ra4BamzKhYOiGItCeZ740=
|
github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU=
|
||||||
github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM=
|
github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k=
|
||||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 h1:idejC8f05m9MGOsuEi1ATq9shN03HrxNkD/luQvxCv8=
|
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||||
github.com/prometheus/common v0.0.0-20181126121408-4724e9255275 h1:PnBWHBf+6L0jOqq0gIVUe6Yk0/QMZ640k6NvkxcBf+8=
|
github.com/prometheus/client_model v0.6.0 h1:k1v3CzpSRUTrKMppY35TLwPvxHqBu0bYgxZzqGIgaos=
|
||||||
github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
|
github.com/prometheus/client_model v0.6.0/go.mod h1:NTQHnmxFpouOD0DpvP4XujX3CdOAGQPoaGhyTchlyt8=
|
||||||
github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a h1:9a8MnZMP0X2nLJdBg+pBmGgkJlSaKC2KaQmTCk1XDtE=
|
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||||
github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||||
github.com/rakyll/statik v0.1.5 h1:Ly2UjURzxnsSYS0zI50fZ+srA+Fu7EbpV5hglvJvJG0=
|
github.com/prometheus/common v0.50.0 h1:YSZE6aa9+luNa2da6/Tik0q0A5AbR+U003TItK57CPQ=
|
||||||
github.com/rakyll/statik v0.1.5/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs=
|
github.com/prometheus/common v0.50.0/go.mod h1:wHFBCEVWVmHMUpg7pYcOm2QUR/ocQdYSJVQJKnHc3xQ=
|
||||||
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
|
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
|
||||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
|
||||||
|
github.com/prometheus/procfs v0.13.0 h1:GqzLlQyfsPbaEHaQkO7tbDlriv/4o5Hudv6OXHGKX7o=
|
||||||
|
github.com/prometheus/procfs v0.13.0/go.mod h1:cd4PFCR54QLnGKPaKGA6l+cfuNXtht43ZKY6tow0Y1g=
|
||||||
|
github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
|
||||||
|
github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||||
|
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||||
|
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||||
|
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||||
|
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
|
||||||
|
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07 h1:UyzmZLoiDWMRywV4DUYb9Fbt8uiOSooupjTq10vpvnU=
|
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07 h1:UyzmZLoiDWMRywV4DUYb9Fbt8uiOSooupjTq10vpvnU=
|
||||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
|
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
|
||||||
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc h1:a3CU5tJYVj92DY2LaA1kUkrsqD5/3mLDhx2NcNqyW+0=
|
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||||
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ=
|
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
|
||||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||||
|
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
|
||||||
|
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||||
|
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
|
||||||
|
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||||
|
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
|
||||||
|
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||||
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package mk2core
|
package mk2core
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Core struct {
|
type Core struct {
|
||||||
|
|||||||
371
mk2driver/mk2.go
371
mk2driver/mk2.go
@@ -14,6 +14,7 @@ import (
|
|||||||
type scaling struct {
|
type scaling struct {
|
||||||
scale float64
|
scale float64
|
||||||
offset float64
|
offset float64
|
||||||
|
signed bool
|
||||||
supported bool
|
supported bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,20 +42,33 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
infoFrameHeader = 0x20
|
infoFrameHeader = 0x20
|
||||||
frameHeader = 0xff
|
frameHeader = 0xff
|
||||||
|
bootupFrameHeader = 0x0
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
acL1InfoFrame = 0x08
|
acL1InfoFrame = 0x08
|
||||||
dcInfoFrame = 0x0C
|
dcInfoFrame = 0x0C
|
||||||
|
interfaceFrame = 0x48 // H
|
||||||
setTargetFrame = 0x41
|
setTargetFrame = 0x41
|
||||||
infoReqFrame = 0x46
|
infoReqFrame = 0x46 //F
|
||||||
ledFrame = 0x4C
|
ledFrame = 0x4C
|
||||||
|
stateFrame = 0x53 // S
|
||||||
vFrame = 0x56
|
vFrame = 0x56
|
||||||
winmonFrame = 0x57
|
winmonFrame = 0x57
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
panelStateVariant2Flags = 0x80
|
||||||
|
|
||||||
|
interfacePanelDetectFlag = 0x01
|
||||||
|
interfaceStandbyFlag = 0x02
|
||||||
|
|
||||||
|
panelCurrentLimitUnknown = 0x8000
|
||||||
|
panelCurrentLimitMax = 0x7FFF
|
||||||
|
)
|
||||||
|
|
||||||
// info frame types
|
// info frame types
|
||||||
const (
|
const (
|
||||||
infoReqAddrDC = 0x00
|
infoReqAddrDC = 0x00
|
||||||
@@ -64,12 +78,21 @@ const (
|
|||||||
// winmon frame commands
|
// winmon frame commands
|
||||||
const (
|
const (
|
||||||
commandReadRAMVar = 0x30
|
commandReadRAMVar = 0x30
|
||||||
|
commandWriteRAMVar = 0x32
|
||||||
|
commandWriteSetting = 0x33
|
||||||
|
commandWriteData = 0x34
|
||||||
commandGetRAMVarInfo = 0x36
|
commandGetRAMVarInfo = 0x36
|
||||||
|
|
||||||
commandReadRAMResponse = 0x85
|
commandUnsupportedResponse = 0x80
|
||||||
commandGetRAMVarInfoResponse = 0x8E
|
commandReadRAMResponse = 0x85
|
||||||
|
commandWriteRAMResponse = 0x87
|
||||||
|
commandWriteSettingResponse = 0x88
|
||||||
|
commandWriteNotAllowedResponse = 0x9B
|
||||||
|
commandGetRAMVarInfoResponse = 0x8E
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const writeResponseTimeout = 3 * time.Second
|
||||||
|
|
||||||
type mk2Ser struct {
|
type mk2Ser struct {
|
||||||
info *Mk2Info
|
info *Mk2Info
|
||||||
p io.ReadWriter
|
p io.ReadWriter
|
||||||
@@ -78,6 +101,10 @@ type mk2Ser struct {
|
|||||||
run chan struct{}
|
run chan struct{}
|
||||||
frameLock bool
|
frameLock bool
|
||||||
infochan chan *Mk2Info
|
infochan chan *Mk2Info
|
||||||
|
commandMu sync.Mutex
|
||||||
|
writeAck chan byte
|
||||||
|
stateAck chan struct{}
|
||||||
|
ifaceAck chan byte
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,6 +115,9 @@ func NewMk2Connection(dev io.ReadWriter) (Mk2, error) {
|
|||||||
mk2.scaleCount = 0
|
mk2.scaleCount = 0
|
||||||
mk2.frameLock = false
|
mk2.frameLock = false
|
||||||
mk2.scales = make([]scaling, 0, ramVarMaxOffset)
|
mk2.scales = make([]scaling, 0, ramVarMaxOffset)
|
||||||
|
mk2.writeAck = make(chan byte, 4)
|
||||||
|
mk2.stateAck = make(chan struct{}, 1)
|
||||||
|
mk2.ifaceAck = make(chan byte, 1)
|
||||||
mk2.setTarget()
|
mk2.setTarget()
|
||||||
mk2.run = make(chan struct{})
|
mk2.run = make(chan struct{})
|
||||||
mk2.infochan = make(chan *Mk2Info)
|
mk2.infochan = make(chan *Mk2Info)
|
||||||
@@ -152,6 +182,233 @@ func (m *mk2Ser) C() chan *Mk2Info {
|
|||||||
return m.infochan
|
return m.infochan
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) WriteRAMVar(id uint16, value int16) error {
|
||||||
|
return m.writeByID(commandWriteRAMVar, commandWriteRAMResponse, id, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) WriteSetting(id uint16, value int16) error {
|
||||||
|
return m.writeByID(commandWriteSetting, commandWriteSettingResponse, id, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) SetPanelState(switchState PanelSwitchState, currentLimitA *float64) error {
|
||||||
|
if !validPanelSwitchState(switchState) {
|
||||||
|
return fmt.Errorf("invalid panel switch state: %d", switchState)
|
||||||
|
}
|
||||||
|
|
||||||
|
currentLimitRaw, err := encodePanelCurrentLimit(currentLimitA)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
m.commandMu.Lock()
|
||||||
|
defer m.commandMu.Unlock()
|
||||||
|
|
||||||
|
m.clearStateResponses()
|
||||||
|
m.sendCommandLocked([]byte{
|
||||||
|
stateFrame,
|
||||||
|
byte(switchState),
|
||||||
|
byte(currentLimitRaw),
|
||||||
|
byte(currentLimitRaw >> 8),
|
||||||
|
0x01,
|
||||||
|
panelStateVariant2Flags,
|
||||||
|
})
|
||||||
|
|
||||||
|
return m.waitForStateResponse()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) SetStandby(enabled bool) error {
|
||||||
|
lineState := byte(interfacePanelDetectFlag)
|
||||||
|
if enabled {
|
||||||
|
lineState |= interfaceStandbyFlag
|
||||||
|
}
|
||||||
|
|
||||||
|
m.commandMu.Lock()
|
||||||
|
defer m.commandMu.Unlock()
|
||||||
|
|
||||||
|
m.clearInterfaceResponses()
|
||||||
|
m.sendCommandLocked([]byte{
|
||||||
|
interfaceFrame,
|
||||||
|
lineState,
|
||||||
|
})
|
||||||
|
|
||||||
|
return m.waitForInterfaceResponse(enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validPanelSwitchState(switchState PanelSwitchState) bool {
|
||||||
|
switch switchState {
|
||||||
|
case PanelSwitchChargerOnly, PanelSwitchInverterOnly, PanelSwitchOn, PanelSwitchOff:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodePanelCurrentLimit(currentLimitA *float64) (uint16, error) {
|
||||||
|
if currentLimitA == nil {
|
||||||
|
return panelCurrentLimitUnknown, nil
|
||||||
|
}
|
||||||
|
if *currentLimitA < 0 {
|
||||||
|
return 0, fmt.Errorf("current_limit must be >= 0, got %.3f", *currentLimitA)
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := math.Round(*currentLimitA * 10)
|
||||||
|
if raw > panelCurrentLimitMax {
|
||||||
|
return 0, fmt.Errorf("current_limit %.3f A is above MK2 maximum %.1f A", *currentLimitA, panelCurrentLimitMax/10.0)
|
||||||
|
}
|
||||||
|
return uint16(raw), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) writeByID(selectCommand, expectedResponse byte, id uint16, value int16) error {
|
||||||
|
m.commandMu.Lock()
|
||||||
|
defer m.commandMu.Unlock()
|
||||||
|
|
||||||
|
m.clearWriteResponses()
|
||||||
|
|
||||||
|
m.sendCommandLocked([]byte{
|
||||||
|
winmonFrame,
|
||||||
|
selectCommand,
|
||||||
|
byte(id),
|
||||||
|
byte(id >> 8),
|
||||||
|
})
|
||||||
|
|
||||||
|
rawValue := uint16(value)
|
||||||
|
m.sendCommandLocked([]byte{
|
||||||
|
winmonFrame,
|
||||||
|
commandWriteData,
|
||||||
|
byte(rawValue),
|
||||||
|
byte(rawValue >> 8),
|
||||||
|
})
|
||||||
|
|
||||||
|
return m.waitForWriteResponse(expectedResponse)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) clearWriteResponses() {
|
||||||
|
if m.writeAck == nil {
|
||||||
|
m.writeAck = make(chan byte, 4)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-m.writeAck:
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) waitForWriteResponse(expectedResponse byte) error {
|
||||||
|
if m.writeAck == nil {
|
||||||
|
return errors.New("write response channel is not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case response := <-m.writeAck:
|
||||||
|
switch response {
|
||||||
|
case expectedResponse:
|
||||||
|
return nil
|
||||||
|
case commandUnsupportedResponse:
|
||||||
|
return errors.New("write command is not supported by this device firmware")
|
||||||
|
case commandWriteNotAllowedResponse:
|
||||||
|
return errors.New("write command rejected by device access level")
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unexpected write response 0x%02x", response)
|
||||||
|
}
|
||||||
|
case <-time.After(writeResponseTimeout):
|
||||||
|
return fmt.Errorf("timed out waiting for write response after %s", writeResponseTimeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) pushWriteResponse(response byte) {
|
||||||
|
if m.writeAck == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case m.writeAck <- response:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) clearStateResponses() {
|
||||||
|
if m.stateAck == nil {
|
||||||
|
m.stateAck = make(chan struct{}, 1)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-m.stateAck:
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) waitForStateResponse() error {
|
||||||
|
if m.stateAck == nil {
|
||||||
|
return errors.New("panel state response channel is not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-m.stateAck:
|
||||||
|
return nil
|
||||||
|
case <-time.After(writeResponseTimeout):
|
||||||
|
return fmt.Errorf("timed out waiting for panel state response after %s", writeResponseTimeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) pushStateResponse() {
|
||||||
|
if m.stateAck == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case m.stateAck <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) clearInterfaceResponses() {
|
||||||
|
if m.ifaceAck == nil {
|
||||||
|
m.ifaceAck = make(chan byte, 1)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-m.ifaceAck:
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) waitForInterfaceResponse(expectedStandby bool) error {
|
||||||
|
if m.ifaceAck == nil {
|
||||||
|
return errors.New("interface response channel is not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case lineState := <-m.ifaceAck:
|
||||||
|
standbyEnabled := lineState&interfaceStandbyFlag != 0
|
||||||
|
if standbyEnabled != expectedStandby {
|
||||||
|
return fmt.Errorf("unexpected standby line state 0x%02x", lineState)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case <-time.After(writeResponseTimeout):
|
||||||
|
return fmt.Errorf("timed out waiting for standby response after %s", writeResponseTimeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) pushInterfaceResponse(lineState byte) {
|
||||||
|
if m.ifaceAck == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case m.ifaceAck <- lineState:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (m *mk2Ser) readByte() byte {
|
func (m *mk2Ser) readByte() byte {
|
||||||
buffer := make([]byte, 1)
|
buffer := make([]byte, 1)
|
||||||
_, err := io.ReadFull(m.p, buffer)
|
_, err := io.ReadFull(m.p, buffer)
|
||||||
@@ -164,6 +421,7 @@ func (m *mk2Ser) readByte() byte {
|
|||||||
|
|
||||||
// Adds error to error slice.
|
// Adds error to error slice.
|
||||||
func (m *mk2Ser) addError(err error) {
|
func (m *mk2Ser) addError(err error) {
|
||||||
|
logrus.Errorf("Mk2 serial slice error: %q", err.Error())
|
||||||
if m.info.Errors == nil {
|
if m.info.Errors == nil {
|
||||||
m.info.Errors = make([]error, 0)
|
m.info.Errors = make([]error, 0)
|
||||||
}
|
}
|
||||||
@@ -183,10 +441,19 @@ func (m *mk2Ser) updateReport() {
|
|||||||
|
|
||||||
// Checks for valid frame and chooses decoding.
|
// Checks for valid frame and chooses decoding.
|
||||||
func (m *mk2Ser) handleFrame(l byte, frame []byte) {
|
func (m *mk2Ser) handleFrame(l byte, frame []byte) {
|
||||||
|
logrus.Debugf("[handleFrame] frame %#v", frame)
|
||||||
if checkChecksum(l, frame[0], frame[1:]) {
|
if checkChecksum(l, frame[0], frame[1:]) {
|
||||||
switch frame[0] {
|
switch frame[0] {
|
||||||
|
case bootupFrameHeader:
|
||||||
|
m.setTarget()
|
||||||
case frameHeader:
|
case frameHeader:
|
||||||
switch frame[1] {
|
switch frame[1] {
|
||||||
|
case interfaceFrame:
|
||||||
|
if len(frame) > 2 {
|
||||||
|
m.pushInterfaceResponse(frame[2])
|
||||||
|
}
|
||||||
|
case stateFrame:
|
||||||
|
m.pushStateResponse()
|
||||||
case vFrame:
|
case vFrame:
|
||||||
m.versionDecode(frame[2:])
|
m.versionDecode(frame[2:])
|
||||||
case winmonFrame:
|
case winmonFrame:
|
||||||
@@ -195,10 +462,16 @@ func (m *mk2Ser) handleFrame(l byte, frame []byte) {
|
|||||||
m.scaleDecode(frame[2:])
|
m.scaleDecode(frame[2:])
|
||||||
case commandReadRAMResponse:
|
case commandReadRAMResponse:
|
||||||
m.stateDecode(frame[2:])
|
m.stateDecode(frame[2:])
|
||||||
|
case commandWriteRAMResponse, commandWriteSettingResponse, commandUnsupportedResponse, commandWriteNotAllowedResponse:
|
||||||
|
m.pushWriteResponse(frame[2])
|
||||||
|
default:
|
||||||
|
logrus.Warnf("[handleFrame] invalid winmonFrame %v", frame[2:])
|
||||||
}
|
}
|
||||||
|
|
||||||
case ledFrame:
|
case ledFrame:
|
||||||
m.ledDecode(frame[2:])
|
m.ledDecode(frame[2:])
|
||||||
|
default:
|
||||||
|
logrus.Warnf("[handleFrame] invalid frameHeader %v", frame[1])
|
||||||
}
|
}
|
||||||
|
|
||||||
case infoFrameHeader:
|
case infoFrameHeader:
|
||||||
@@ -207,10 +480,14 @@ func (m *mk2Ser) handleFrame(l byte, frame []byte) {
|
|||||||
m.dcDecode(frame[1:])
|
m.dcDecode(frame[1:])
|
||||||
case acL1InfoFrame:
|
case acL1InfoFrame:
|
||||||
m.acDecode(frame[1:])
|
m.acDecode(frame[1:])
|
||||||
|
default:
|
||||||
|
logrus.Warnf("[handleFrame] invalid infoFrameHeader %v", frame[5])
|
||||||
}
|
}
|
||||||
|
default:
|
||||||
|
logrus.Warnf("[handleFrame] Invalid frame %v", frame[0])
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
logrus.Errorf("Invalid incoming frame checksum: %x", frame)
|
logrus.Errorf("[handleFrame] Invalid incoming frame checksum: %x", frame)
|
||||||
m.frameLock = false
|
m.frameLock = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -233,24 +510,43 @@ func (m *mk2Ser) reqScaleFactor(in byte) {
|
|||||||
m.sendCommand(cmd)
|
m.sendCommand(cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func int16Abs(in int16) uint16 {
|
||||||
|
if in < 0 {
|
||||||
|
return uint16(-in)
|
||||||
|
}
|
||||||
|
return uint16(in)
|
||||||
|
}
|
||||||
|
|
||||||
// Decode the scale factor frame.
|
// Decode the scale factor frame.
|
||||||
func (m *mk2Ser) scaleDecode(frame []byte) {
|
func (m *mk2Ser) scaleDecode(frame []byte) {
|
||||||
tmp := scaling{}
|
tmp := scaling{}
|
||||||
|
logrus.Debugf("Scale frame(%d): 0x%x", len(frame), frame)
|
||||||
if len(frame) < 6 {
|
if len(frame) < 6 {
|
||||||
tmp.supported = false
|
tmp.supported = false
|
||||||
logrus.Warnf("Skiping scaling factors for: %d", m.scaleCount)
|
logrus.Warnf("Skiping scaling factors for: %d", m.scaleCount)
|
||||||
} else {
|
} else {
|
||||||
tmp.supported = true
|
tmp.supported = true
|
||||||
scl := uint16(frame[2])<<8 + uint16(frame[1])
|
var scl int16
|
||||||
ofs := int16(uint16(frame[5])<<8 + uint16(frame[4]))
|
var ofs int16
|
||||||
|
if len(frame) == 6 {
|
||||||
tmp.offset = float64(ofs)
|
scl = int16(frame[2])<<8 + int16(frame[1])
|
||||||
if scl >= 0x4000 {
|
ofs = int16(uint16(frame[4])<<8 + uint16(frame[3]))
|
||||||
tmp.scale = math.Abs(1 / (0x8000 - float64(scl)))
|
|
||||||
} else {
|
} else {
|
||||||
tmp.scale = math.Abs(float64(scl))
|
scl = int16(frame[2])<<8 + int16(frame[1])
|
||||||
|
ofs = int16(uint16(frame[5])<<8 + uint16(frame[4]))
|
||||||
|
}
|
||||||
|
if scl < 0 {
|
||||||
|
tmp.signed = true
|
||||||
|
}
|
||||||
|
tmp.offset = float64(ofs)
|
||||||
|
scale := int16Abs(scl)
|
||||||
|
if scale >= 0x4000 {
|
||||||
|
tmp.scale = 1 / (0x8000 - float64(scale))
|
||||||
|
} else {
|
||||||
|
tmp.scale = float64(scale)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
logrus.Debugf("scalecount %v: %#v \n", m.scaleCount, tmp)
|
||||||
m.scales = append(m.scales, tmp)
|
m.scales = append(m.scales, tmp)
|
||||||
m.scaleCount++
|
m.scaleCount++
|
||||||
if m.scaleCount < ramVarMaxOffset {
|
if m.scaleCount < ramVarMaxOffset {
|
||||||
@@ -262,6 +558,7 @@ func (m *mk2Ser) scaleDecode(frame []byte) {
|
|||||||
|
|
||||||
// Decode the version number
|
// Decode the version number
|
||||||
func (m *mk2Ser) versionDecode(frame []byte) {
|
func (m *mk2Ser) versionDecode(frame []byte) {
|
||||||
|
logrus.Debugf("versiondecode %v", frame)
|
||||||
m.info.Version = 0
|
m.info.Version = 0
|
||||||
m.info.Valid = true
|
m.info.Valid = true
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
@@ -280,6 +577,20 @@ func (m *mk2Ser) versionDecode(frame []byte) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Decode with correct signedness and apply scale
|
||||||
|
func (m *mk2Ser) applyScaleAndSign(data []byte, scale int) float64 {
|
||||||
|
var value float64
|
||||||
|
if !m.scales[scale].supported {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if m.scales[scale].signed {
|
||||||
|
value = getSigned(data)
|
||||||
|
} else {
|
||||||
|
value = getUnsigned16(data)
|
||||||
|
}
|
||||||
|
return m.applyScale(value, scale)
|
||||||
|
}
|
||||||
|
|
||||||
// Apply scaling to float
|
// Apply scaling to float
|
||||||
func (m *mk2Ser) applyScale(value float64, scale int) float64 {
|
func (m *mk2Ser) applyScale(value float64, scale int) float64 {
|
||||||
if !m.scales[scale].supported {
|
if !m.scales[scale].supported {
|
||||||
@@ -293,6 +604,11 @@ func getSigned(data []byte) float64 {
|
|||||||
return float64(int16(data[0]) + int16(data[1])<<8)
|
return float64(int16(data[0]) + int16(data[1])<<8)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Convert bytes->int16->float
|
||||||
|
func getUnsigned16(data []byte) float64 {
|
||||||
|
return float64(uint16(data[0]) + uint16(data[1])<<8)
|
||||||
|
}
|
||||||
|
|
||||||
// Convert bytes->uint32->float
|
// Convert bytes->uint32->float
|
||||||
func getUnsigned(data []byte) float64 {
|
func getUnsigned(data []byte) float64 {
|
||||||
return float64(uint32(data[0]) + uint32(data[1])<<8 + uint32(data[2])<<16)
|
return float64(uint32(data[0]) + uint32(data[1])<<8 + uint32(data[2])<<16)
|
||||||
@@ -300,13 +616,14 @@ func getUnsigned(data []byte) float64 {
|
|||||||
|
|
||||||
// Decodes DC frame.
|
// Decodes DC frame.
|
||||||
func (m *mk2Ser) dcDecode(frame []byte) {
|
func (m *mk2Ser) dcDecode(frame []byte) {
|
||||||
m.info.BatVoltage = m.applyScale(getSigned(frame[5:7]), ramVarVBat)
|
m.info.BatVoltage = m.applyScaleAndSign(frame[5:7], ramVarVBat)
|
||||||
|
|
||||||
usedC := m.applyScale(getUnsigned(frame[7:10]), ramVarIBat)
|
usedC := m.applyScale(getUnsigned(frame[7:10]), ramVarIBat)
|
||||||
chargeC := m.applyScale(getUnsigned(frame[10:13]), ramVarIBat)
|
chargeC := m.applyScale(getUnsigned(frame[10:13]), ramVarIBat)
|
||||||
m.info.BatCurrent = usedC - chargeC
|
m.info.BatCurrent = usedC - chargeC
|
||||||
|
|
||||||
m.info.OutFrequency = 10 / (m.applyScale(float64(frame[13]), ramVarInverterPeriod))
|
m.info.OutFrequency = m.calcFreq(frame[13], ramVarInverterPeriod)
|
||||||
|
logrus.Debugf("dcDecode %#v", m.info)
|
||||||
|
|
||||||
// Send L1 status request
|
// Send L1 status request
|
||||||
cmd := make([]byte, 2)
|
cmd := make([]byte, 2)
|
||||||
@@ -321,12 +638,9 @@ func (m *mk2Ser) acDecode(frame []byte) {
|
|||||||
m.info.InCurrent = m.applyScale(getSigned(frame[7:9]), ramVarIMains)
|
m.info.InCurrent = m.applyScale(getSigned(frame[7:9]), ramVarIMains)
|
||||||
m.info.OutVoltage = m.applyScale(getSigned(frame[9:11]), ramVarVInverter)
|
m.info.OutVoltage = m.applyScale(getSigned(frame[9:11]), ramVarVInverter)
|
||||||
m.info.OutCurrent = m.applyScale(getSigned(frame[11:13]), ramVarIInverter)
|
m.info.OutCurrent = m.applyScale(getSigned(frame[11:13]), ramVarIInverter)
|
||||||
|
m.info.InFrequency = m.calcFreq(frame[13], ramVarMainPeriod)
|
||||||
|
|
||||||
if frame[13] == 0xff {
|
logrus.Debugf("acDecode %#v", m.info)
|
||||||
m.info.InFrequency = 0
|
|
||||||
} else {
|
|
||||||
m.info.InFrequency = 10 / (m.applyScale(float64(frame[13]), ramVarMainPeriod))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send status request
|
// Send status request
|
||||||
cmd := make([]byte, 1)
|
cmd := make([]byte, 1)
|
||||||
@@ -334,9 +648,17 @@ func (m *mk2Ser) acDecode(frame []byte) {
|
|||||||
m.sendCommand(cmd)
|
m.sendCommand(cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) calcFreq(data byte, scaleIndex int) float64 {
|
||||||
|
if data == 0xff || data == 0x00 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return 10 / (m.applyScale(float64(data), scaleIndex))
|
||||||
|
}
|
||||||
|
|
||||||
// Decode charge state of battery.
|
// Decode charge state of battery.
|
||||||
func (m *mk2Ser) stateDecode(frame []byte) {
|
func (m *mk2Ser) stateDecode(frame []byte) {
|
||||||
m.info.ChargeState = m.applyScale(getSigned(frame[1:3]), ramVarChargeState)
|
m.info.ChargeState = m.applyScaleAndSign(frame[1:3], ramVarChargeState)
|
||||||
|
logrus.Debugf("battery state decode %#v", m.info)
|
||||||
m.updateReport()
|
m.updateReport()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -372,6 +694,12 @@ func getLEDs(ledsOn, ledsBlink byte) map[Led]LEDstate {
|
|||||||
|
|
||||||
// Adds header and trailing crc for frame to send.
|
// Adds header and trailing crc for frame to send.
|
||||||
func (m *mk2Ser) sendCommand(data []byte) {
|
func (m *mk2Ser) sendCommand(data []byte) {
|
||||||
|
m.commandMu.Lock()
|
||||||
|
defer m.commandMu.Unlock()
|
||||||
|
m.sendCommandLocked(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mk2Ser) sendCommandLocked(data []byte) {
|
||||||
l := len(data)
|
l := len(data)
|
||||||
dataOut := make([]byte, l+3)
|
dataOut := make([]byte, l+3)
|
||||||
dataOut[0] = byte(l + 1)
|
dataOut[0] = byte(l + 1)
|
||||||
@@ -383,6 +711,7 @@ func (m *mk2Ser) sendCommand(data []byte) {
|
|||||||
}
|
}
|
||||||
dataOut[l+2] = cr
|
dataOut[l+2] = cr
|
||||||
|
|
||||||
|
logrus.Debugf("sendCommand %#v", dataOut)
|
||||||
_, err := m.p.Write(dataOut)
|
_, err := m.p.Write(dataOut)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
m.addError(fmt.Errorf("Write error: %v", err))
|
m.addError(fmt.Errorf("Write error: %v", err))
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"io"
|
"io"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
@@ -33,7 +34,7 @@ var knownWrites = []byte{
|
|||||||
var writeBuffer = bytes.NewBuffer(nil)
|
var writeBuffer = bytes.NewBuffer(nil)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
testEpsilon = 0.00000001
|
testDelta = 0.00000001
|
||||||
)
|
)
|
||||||
|
|
||||||
type testIo struct {
|
type testIo struct {
|
||||||
@@ -42,6 +43,7 @@ type testIo struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewIOStub(readBuffer []byte) io.ReadWriter {
|
func NewIOStub(readBuffer []byte) io.ReadWriter {
|
||||||
|
writeBuffer = bytes.NewBuffer(nil)
|
||||||
return &testIo{
|
return &testIo{
|
||||||
Reader: bytes.NewBuffer(readBuffer),
|
Reader: bytes.NewBuffer(readBuffer),
|
||||||
Writer: writeBuffer,
|
Writer: writeBuffer,
|
||||||
@@ -50,62 +52,162 @@ func NewIOStub(readBuffer []byte) io.ReadWriter {
|
|||||||
|
|
||||||
// Test a know sequence as reference as extracted from Mk2
|
// Test a know sequence as reference as extracted from Mk2
|
||||||
func TestSync(t *testing.T) {
|
func TestSync(t *testing.T) {
|
||||||
knownReadBuffer := []byte{
|
tests := []struct {
|
||||||
//Len Cmd
|
name string
|
||||||
0x04, 0xff, 0x41, 0x01, 0x00, 0xbb, 0x07, 0xff, 0x56, 0x96, 0x3e, 0x11, 0x00, 0x00, 0xbf,
|
knownReadBuffer []byte
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
knownWrites []byte
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x00, 0x00, 0xa1,
|
result Mk2Info
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
}{
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
{
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
name: "basic",
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x00, 0x00, 0xa1,
|
knownReadBuffer: []byte{
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
//Len Cmd
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x57, 0x78, 0x8f, 0x00, 0x01, 0xb5,
|
0x04, 0xff, 0x41, 0x01, 0x00, 0xbb,
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x2f, 0x7c, 0x8f, 0x00, 0x00, 0xda,
|
0x07, 0xff, 0x56, 0x96, 0x3e, 0x11, 0x00, 0x00, 0xbf,
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x00, 0x00, 0xa1,
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x04, 0x00, 0x8f, 0x00, 0x80, 0x01,
|
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x00, 0x00, 0xa1,
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x01, 0x00, 0x8f, 0x00, 0x80, 0x04,
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x02, 0x00, 0x8f, 0x00, 0x80, 0x03,
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
||||||
0x08, 0xff, 0x57, 0x8e, 0x38, 0x7f, 0x8f, 0x00, 0x00, 0xce,
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
||||||
0x07, 0xff, 0x56, 0x96, 0x3e, 0x11, 0x00, 0x00, 0xbf,
|
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x00, 0x00, 0xa1,
|
||||||
0x0f, 0x20, 0xf3, 0x00, 0xc8, 0x02, 0x0c, 0xa1, 0x05, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x88, 0xb2,
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a,
|
||||||
0x0f, 0x20, 0x01, 0x01, 0xca, 0x09, 0x08, 0xaa, 0x58, 0xab, 0x00, 0xaa, 0x58, 0x9a, 0x00, 0xc3, 0xe8,
|
0x08, 0xff, 0x57, 0x8e, 0x57, 0x78, 0x8f, 0x00, 0x01, 0xb5,
|
||||||
0x06, 0xff, 0x4c, 0x03, 0x00, 0x00, 0x00, 0xac,
|
0x08, 0xff, 0x57, 0x8e, 0x2f, 0x7c, 0x8f, 0x00, 0x00, 0xda,
|
||||||
0x05, 0xff, 0x57, 0x85, 0xc8, 0x00, 0x58,
|
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x00, 0x00, 0xa1,
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x04, 0x00, 0x8f, 0x00, 0x80, 0x01,
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x01, 0x00, 0x8f, 0x00, 0x80, 0x04,
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x02, 0x00, 0x8f, 0x00, 0x80, 0x03,
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x38, 0x7f, 0x8f, 0x00, 0x00, 0xce,
|
||||||
|
0x07, 0xff, 0x56, 0x96, 0x3e, 0x11, 0x00, 0x00, 0xbf,
|
||||||
|
0x0f, 0x20, 0xf3, 0x00, 0xc8, 0x02, 0x0c, 0xa1, 0x05, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x88, 0xb2,
|
||||||
|
0x0f, 0x20, 0x01, 0x01, 0xca, 0x09, 0x08, 0xaa, 0x58, 0xab, 0x00, 0xaa, 0x58, 0x9a, 0x00, 0xc3, 0xe8,
|
||||||
|
0x06, 0xff, 0x4c, 0x03, 0x00, 0x00, 0x00, 0xac,
|
||||||
|
0x05, 0xff, 0x57, 0x85, 0xc8, 0x00, 0x58,
|
||||||
|
},
|
||||||
|
knownWrites: []byte{
|
||||||
|
0x04, 0xff, 0x41, 0x01, 0x00, 0xbb,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x00, 0x00, 0x6f,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x01, 0x00, 0x6e,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x02, 0x00, 0x6d,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x03, 0x00, 0x6c,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x04, 0x00, 0x6b,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x05, 0x00, 0x6a,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x06, 0x00, 0x69,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x07, 0x00, 0x68,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x08, 0x00, 0x67,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x09, 0x00, 0x66,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x0a, 0x00, 0x65,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x0b, 0x00, 0x64,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x0c, 0x00, 0x63,
|
||||||
|
0x05, 0xff, 0x57, 0x36, 0x0d, 0x00, 0x62,
|
||||||
|
0x03, 0xff, 0x46, 0x00, 0xb8,
|
||||||
|
0x03, 0xff, 0x46, 0x01, 0xb7,
|
||||||
|
0x02, 0xff, 0x4c, 0xb3,
|
||||||
|
0x05, 0xff, 0x57, 0x30, 0x0d, 0x00, 0x68,
|
||||||
|
},
|
||||||
|
result: Mk2Info{
|
||||||
|
Version: uint32(2736),
|
||||||
|
BatVoltage: 14.41,
|
||||||
|
BatCurrent: -0.4,
|
||||||
|
InVoltage: 226.98,
|
||||||
|
InCurrent: 1.71,
|
||||||
|
InFrequency: 50.10256410256411,
|
||||||
|
OutVoltage: 226.980,
|
||||||
|
OutCurrent: 1.54,
|
||||||
|
OutFrequency: 50.025510204081634,
|
||||||
|
ChargeState: 1,
|
||||||
|
LEDs: map[Led]LEDstate{
|
||||||
|
LedMain: LedOn,
|
||||||
|
LedAbsorption: LedOn,
|
||||||
|
LedBulk: LedOff,
|
||||||
|
LedFloat: LedOff,
|
||||||
|
LedInverter: LedOff,
|
||||||
|
LedOverload: LedOff,
|
||||||
|
LedLowBattery: LedOff,
|
||||||
|
LedTemperature: LedOff,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "multiplus24/3000",
|
||||||
|
knownReadBuffer: []byte{
|
||||||
|
//Len Cmd
|
||||||
|
0x04, 0xff, 0x41, 0x01, 0x00, 0xbb,
|
||||||
|
0x07, 0xff, 0x56, 0x98, 0x3e, 0x11, 0x00, 0x00, 0xbd, // version
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x0, 0x0, 0x6a, // scale 0
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x0, 0x0, 0x6a, // scale 1
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x0, 0x0, 0x6a, // scale 2
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x0, 0x0, 0x6a, // scale 3
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x0, 0x0, 0x6a, // scale 4
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x0, 0x0, 0xa1, // scale 5
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x0, 0x0, 0x6a, // scale 6
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x57, 0x78, 0x8f, 0x0, 0x1, 0xb5, // scale 7
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x2f, 0x7c, 0x8f, 0x0, 0x0, 0xda, // scale 8
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x64, 0x80, 0x8f, 0x0, 0x0, 0xa1, //scale 9
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x4, 0x0, 0x8f, 0x0, 0x80, 0x1, // scale 10
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x1, 0x0, 0x8f, 0x0, 0x80, 0x4, // scale 11
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x6, 0x0, 0x8f, 0x0, 0x80, 0xff, // scale 12
|
||||||
|
0x08, 0xff, 0x57, 0x8e, 0x38, 0x7f, 0x8f, 0x0, 0x0, 0xce, // scale 13
|
||||||
|
0x07, 0xff, 0x56, 0x98, 0x3e, 0x11, 0x0, 0x0, 0xbd, // version
|
||||||
|
0x0f, 0x20, 0xb6, 0x89, 0x6d, 0xb7, 0xc, 0x4e, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x88, 0x82, // dc info
|
||||||
|
0x0f, 0x20, 0x1, 0x1, 0x6d, 0xb7, 0x8, 0x77, 0x5b, 0x21, 0x0, 0x77, 0x5b, 0xfe, 0xff, 0xc3, 0x1e, // ac info
|
||||||
|
0x08, 0xff, 0x4c, 0x9, 0x0, 0x0, 0x0, 0x3, 0x0, 0xa1,
|
||||||
|
0x05, 0xff, 0x57, 0x85, 0xc8, 0x0, 0x58,
|
||||||
|
},
|
||||||
|
knownWrites: []byte{},
|
||||||
|
result: Mk2Info{
|
||||||
|
Version: 0xac0,
|
||||||
|
BatVoltage: 26.38,
|
||||||
|
BatCurrent: 0,
|
||||||
|
InVoltage: 234.15,
|
||||||
|
InCurrent: 0.33,
|
||||||
|
InFrequency: 50.1025641025641,
|
||||||
|
OutVoltage: 234.15,
|
||||||
|
OutCurrent: -0.02,
|
||||||
|
OutFrequency: 50.025510204081634,
|
||||||
|
ChargeState: 1,
|
||||||
|
LEDs: map[Led]LEDstate{
|
||||||
|
LedMain: LedOn,
|
||||||
|
LedAbsorption: LedOff,
|
||||||
|
LedBulk: LedOff,
|
||||||
|
LedFloat: LedOn,
|
||||||
|
LedInverter: LedOff,
|
||||||
|
LedOverload: LedOff,
|
||||||
|
LedLowBattery: LedOff,
|
||||||
|
LedTemperature: LedOff,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedLEDs := map[Led]LEDstate{
|
for _, tt := range tests {
|
||||||
LedMain: LedOn,
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
LedAbsorption: LedOn,
|
testIO := NewIOStub(tt.knownReadBuffer)
|
||||||
LedBulk: LedOff,
|
mk2, err := NewMk2Connection(testIO)
|
||||||
LedFloat: LedOff,
|
assert.NoError(t, err, "Could not open MK2")
|
||||||
LedInverter: LedOff,
|
|
||||||
LedOverload: LedOff,
|
event := <-mk2.C()
|
||||||
LedLowBattery: LedOff,
|
mk2.Close()
|
||||||
LedTemperature: LedOff,
|
|
||||||
|
if len(tt.knownWrites) > 0 {
|
||||||
|
assert.Equal(t, 0, bytes.Compare(writeBuffer.Bytes(), knownWrites), "Expected writes did not match received writes")
|
||||||
|
}
|
||||||
|
assert.True(t, event.Valid, "data not valid")
|
||||||
|
assert.Equal(t, tt.result.Version, event.Version, "Invalid version decoded")
|
||||||
|
assert.Equal(t, 0, len(event.Errors), "Reported errors not empty")
|
||||||
|
assert.Equal(t, tt.result.LEDs, event.LEDs, "Reported LEDs incorrect")
|
||||||
|
|
||||||
|
assert.InDelta(t, tt.result.BatVoltage, event.BatVoltage, testDelta, "BatVoltage conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.BatCurrent, event.BatCurrent, testDelta, "BatCurrent conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.InVoltage, event.InVoltage, testDelta, "InVoltage conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.InCurrent, event.InCurrent, testDelta, "InCurrent conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.InFrequency, event.InFrequency, testDelta, "InFrequency conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.OutVoltage, event.OutVoltage, testDelta, "OutVoltage conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.OutCurrent, event.OutCurrent, testDelta, "OutCurrent conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.OutFrequency, event.OutFrequency, testDelta, "OutFrequency conversion failed")
|
||||||
|
assert.InDelta(t, tt.result.ChargeState, event.ChargeState, testDelta, "ChargeState conversion failed")
|
||||||
|
})
|
||||||
}
|
}
|
||||||
testIO := NewIOStub(knownReadBuffer)
|
|
||||||
mk2, err := NewMk2Connection(testIO)
|
|
||||||
assert.NoError(t, err, "Could not open MK2")
|
|
||||||
|
|
||||||
event := <-mk2.C()
|
|
||||||
mk2.Close()
|
|
||||||
|
|
||||||
assert.Equal(t, 0, bytes.Compare(writeBuffer.Bytes(), knownWrites), "Expected writes did not match received writes")
|
|
||||||
assert.True(t, event.Valid, "data not valid")
|
|
||||||
assert.Equal(t, uint32(2736), event.Version, "Invalid version decoded")
|
|
||||||
assert.Equal(t, 0, len(event.Errors), "Reported errors not empty")
|
|
||||||
assert.Equal(t, expectedLEDs, event.LEDs, "Reported LEDs incorrect")
|
|
||||||
|
|
||||||
assert.InEpsilon(t, 14.41, event.BatVoltage, testEpsilon, "BatVoltage conversion failed")
|
|
||||||
assert.InEpsilon(t, -0.4, event.BatCurrent, testEpsilon, "BatCurrent conversion failed")
|
|
||||||
assert.InEpsilon(t, 226.98, event.InVoltage, testEpsilon, "InVoltage conversion failed")
|
|
||||||
assert.InEpsilon(t, 1.71, event.InCurrent, testEpsilon, "InCurrent conversion failed")
|
|
||||||
assert.InEpsilon(t, 50.10256410256411, event.InFrequency, testEpsilon, "InFrequency conversion failed")
|
|
||||||
assert.InEpsilon(t, 226.980, event.OutVoltage, testEpsilon, "OutVoltage conversion failed")
|
|
||||||
assert.InEpsilon(t, 1.54, event.OutCurrent, testEpsilon, "OutCurrent conversion failed")
|
|
||||||
assert.InEpsilon(t, 50.025510204081634, event.OutFrequency, testEpsilon, "OutFrequency conversion failed")
|
|
||||||
assert.InEpsilon(t, 1, event.ChargeState, testEpsilon, "ChargeState conversion failed")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_mk2Ser_scaleDecode(t *testing.T) {
|
func Test_mk2Ser_scaleDecode(t *testing.T) {
|
||||||
@@ -116,16 +218,16 @@ func Test_mk2Ser_scaleDecode(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "Valid scale",
|
name: "Valid scale",
|
||||||
frame: []byte{0x57, 0x8e, 0x9c, 0x7f, 0x8f, 0x00, 0x00, 0x6a},
|
frame: []byte{0x8e, 0x9c, 0x7f, 0x8f, 0x01, 0x00, 0x6a},
|
||||||
expectedScaling: scaling{
|
expectedScaling: scaling{
|
||||||
scale: 0.00013679890560875513,
|
scale: 0.01,
|
||||||
offset: 143,
|
offset: 1,
|
||||||
supported: true,
|
supported: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Unsupported frame",
|
name: "Unsupported frame",
|
||||||
frame: []byte{0x57, 0x00},
|
frame: []byte{0x00},
|
||||||
expectedScaling: scaling{
|
expectedScaling: scaling{
|
||||||
supported: false,
|
supported: false,
|
||||||
},
|
},
|
||||||
@@ -141,10 +243,195 @@ func Test_mk2Ser_scaleDecode(t *testing.T) {
|
|||||||
assert.Equal(t, 1, len(m.scales))
|
assert.Equal(t, 1, len(m.scales))
|
||||||
assert.Equal(t, 1, m.scaleCount)
|
assert.Equal(t, 1, m.scaleCount)
|
||||||
assert.Equal(t, tt.expectedScaling.supported, m.scales[0].supported)
|
assert.Equal(t, tt.expectedScaling.supported, m.scales[0].supported)
|
||||||
|
assert.Equal(t, tt.expectedScaling.signed, m.scales[0].signed)
|
||||||
if tt.expectedScaling.supported {
|
if tt.expectedScaling.supported {
|
||||||
assert.InEpsilon(t, tt.expectedScaling.offset, m.scales[0].offset, testEpsilon)
|
assert.InDelta(t, tt.expectedScaling.offset, m.scales[0].offset, testDelta)
|
||||||
assert.InEpsilon(t, tt.expectedScaling.scale, m.scales[0].scale, testEpsilon)
|
assert.InDelta(t, tt.expectedScaling.scale, m.scales[0].scale, testDelta)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_mk2Ser_calcFreq(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
scales []scaling
|
||||||
|
data byte
|
||||||
|
scaleIndex int
|
||||||
|
want float64
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "Calculate working low",
|
||||||
|
scales: []scaling{
|
||||||
|
{supported: false},
|
||||||
|
},
|
||||||
|
data: 0x01,
|
||||||
|
scaleIndex: 0,
|
||||||
|
want: 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Calculate working high",
|
||||||
|
scales: []scaling{
|
||||||
|
{
|
||||||
|
supported: true,
|
||||||
|
offset: 0,
|
||||||
|
scale: 0.01,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
data: 0xFE,
|
||||||
|
scaleIndex: 0,
|
||||||
|
want: 3.937007874015748,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Calculate clip high",
|
||||||
|
scales: []scaling{
|
||||||
|
{supported: false},
|
||||||
|
},
|
||||||
|
data: 0xff,
|
||||||
|
scaleIndex: 0,
|
||||||
|
want: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Calculate clip low",
|
||||||
|
scales: []scaling{
|
||||||
|
{supported: false},
|
||||||
|
},
|
||||||
|
data: 0x00,
|
||||||
|
scaleIndex: 0,
|
||||||
|
want: 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
m := &mk2Ser{
|
||||||
|
scales: tt.scales,
|
||||||
|
}
|
||||||
|
got := m.calcFreq(tt.data, tt.scaleIndex)
|
||||||
|
assert.InDelta(t, tt.want, got, testDelta)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_mk2Ser_WriteSetting(t *testing.T) {
|
||||||
|
testIO := NewIOStub(nil)
|
||||||
|
m := &mk2Ser{
|
||||||
|
p: testIO,
|
||||||
|
writeAck: make(chan byte, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
m.pushWriteResponse(commandWriteSettingResponse)
|
||||||
|
}()
|
||||||
|
|
||||||
|
err := m.WriteSetting(0x1234, 1234)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
expected := []byte{
|
||||||
|
0x05, 0xff, 0x57, 0x33, 0x34, 0x12, 0x2c,
|
||||||
|
0x05, 0xff, 0x57, 0x34, 0xd2, 0x04, 0x9b,
|
||||||
|
}
|
||||||
|
assert.Equal(t, expected, writeBuffer.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_mk2Ser_WriteRAMVarRejected(t *testing.T) {
|
||||||
|
testIO := NewIOStub(nil)
|
||||||
|
m := &mk2Ser{
|
||||||
|
p: testIO,
|
||||||
|
writeAck: make(chan byte, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
m.pushWriteResponse(commandWriteNotAllowedResponse)
|
||||||
|
}()
|
||||||
|
|
||||||
|
err := m.WriteRAMVar(0x000d, 1)
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.ErrorContains(t, err, "rejected")
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_mk2Ser_SetPanelState(t *testing.T) {
|
||||||
|
testIO := NewIOStub(nil)
|
||||||
|
m := &mk2Ser{
|
||||||
|
p: testIO,
|
||||||
|
stateAck: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
m.pushStateResponse()
|
||||||
|
}()
|
||||||
|
|
||||||
|
currentLimit := 16.5
|
||||||
|
err := m.SetPanelState(PanelSwitchOn, ¤tLimit)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
expected := []byte{
|
||||||
|
0x07, 0xff, 0x53, 0x03, 0xa5, 0x00, 0x01, 0x80, 0x7e,
|
||||||
|
}
|
||||||
|
assert.Equal(t, expected, writeBuffer.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_mk2Ser_SetPanelState_SwitchOnly(t *testing.T) {
|
||||||
|
testIO := NewIOStub(nil)
|
||||||
|
m := &mk2Ser{
|
||||||
|
p: testIO,
|
||||||
|
stateAck: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
m.pushStateResponse()
|
||||||
|
}()
|
||||||
|
|
||||||
|
err := m.SetPanelState(PanelSwitchOff, nil)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
expected := []byte{
|
||||||
|
0x07, 0xff, 0x53, 0x04, 0x00, 0x80, 0x01, 0x80, 0xa2,
|
||||||
|
}
|
||||||
|
assert.Equal(t, expected, writeBuffer.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_mk2Ser_SetStandby(t *testing.T) {
|
||||||
|
testIO := NewIOStub(nil)
|
||||||
|
m := &mk2Ser{
|
||||||
|
p: testIO,
|
||||||
|
ifaceAck: make(chan byte, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
m.pushInterfaceResponse(interfacePanelDetectFlag | interfaceStandbyFlag)
|
||||||
|
}()
|
||||||
|
|
||||||
|
err := m.SetStandby(true)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
expected := []byte{
|
||||||
|
0x03, 0xff, 0x48, 0x03, 0xb3,
|
||||||
|
}
|
||||||
|
assert.Equal(t, expected, writeBuffer.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_mk2Ser_SetStandby_Disabled(t *testing.T) {
|
||||||
|
testIO := NewIOStub(nil)
|
||||||
|
m := &mk2Ser{
|
||||||
|
p: testIO,
|
||||||
|
ifaceAck: make(chan byte, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
m.pushInterfaceResponse(interfacePanelDetectFlag)
|
||||||
|
}()
|
||||||
|
|
||||||
|
err := m.SetStandby(false)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
expected := []byte{
|
||||||
|
0x03, 0xff, 0x48, 0x01, 0xb5,
|
||||||
|
}
|
||||||
|
assert.Equal(t, expected, writeBuffer.Bytes())
|
||||||
|
}
|
||||||
|
|||||||
@@ -76,3 +76,29 @@ type Mk2 interface {
|
|||||||
C() chan *Mk2Info
|
C() chan *Mk2Info
|
||||||
Close()
|
Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type PanelSwitchState byte
|
||||||
|
|
||||||
|
const (
|
||||||
|
// PanelSwitchChargerOnly enables charging only.
|
||||||
|
PanelSwitchChargerOnly PanelSwitchState = 0x01
|
||||||
|
// PanelSwitchInverterOnly enables inverter output and disables charging.
|
||||||
|
PanelSwitchInverterOnly PanelSwitchState = 0x02
|
||||||
|
// PanelSwitchOn enables both inverter and charger.
|
||||||
|
PanelSwitchOn PanelSwitchState = 0x03
|
||||||
|
// PanelSwitchOff disables inverter and charger.
|
||||||
|
PanelSwitchOff PanelSwitchState = 0x04
|
||||||
|
)
|
||||||
|
|
||||||
|
type SettingsWriter interface {
|
||||||
|
// WriteRAMVar writes a signed 16-bit value to a RAM variable id.
|
||||||
|
WriteRAMVar(id uint16, value int16) error
|
||||||
|
// WriteSetting writes a signed 16-bit value to a setting id.
|
||||||
|
WriteSetting(id uint16, value int16) error
|
||||||
|
// SetPanelState sends the MK2 "S" command using a virtual panel switch state.
|
||||||
|
// If currentLimitA is nil, the command does not update the AC current limit.
|
||||||
|
SetPanelState(switchState PanelSwitchState, currentLimitA *float64) error
|
||||||
|
// SetStandby configures the remote panel standby line.
|
||||||
|
// When enabled, the inverter is prevented from sleeping while switched off.
|
||||||
|
SetStandby(enabled bool) error
|
||||||
|
}
|
||||||
|
|||||||
@@ -37,6 +37,22 @@ func (m *mock) Close() {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *mock) WriteRAMVar(_ uint16, _ int16) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mock) WriteSetting(_ uint16, _ int16) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mock) SetPanelState(_ PanelSwitchState, _ *float64) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mock) SetStandby(_ bool) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (m *mock) genMockValues() {
|
func (m *mock) genMockValues() {
|
||||||
mult := 1.0
|
mult := 1.0
|
||||||
ledState := LedOff
|
ledState := LedOff
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package cli
|
package cli
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,14 @@ package mqttclient
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
@@ -13,42 +18,758 @@ var log = logrus.WithField("ctx", "inverter-gui-mqtt")
|
|||||||
|
|
||||||
const keepAlive = 5 * time.Second
|
const keepAlive = 5 * time.Second
|
||||||
|
|
||||||
// Config sets MQTT client configuration
|
const (
|
||||||
type Config struct {
|
commandKindSetting = "setting"
|
||||||
Broker string
|
commandKindRAMVar = "ram_var"
|
||||||
ClientID string
|
commandKindPanel = "panel_state"
|
||||||
Topic string
|
commandKindStandby = "standby"
|
||||||
Username string
|
|
||||||
Password string
|
writeStatusOK = "ok"
|
||||||
|
writeStatusError = "error"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HomeAssistantConfig struct {
|
||||||
|
Enabled bool
|
||||||
|
DiscoveryPrefix string
|
||||||
|
NodeID string
|
||||||
|
DeviceName string
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates an MQTT client that starts publishing MK2 data as it is received.
|
// Config sets MQTT client configuration
|
||||||
func New(mk2 mk2driver.Mk2, config Config) error {
|
type Config struct {
|
||||||
|
Broker string
|
||||||
|
ClientID string
|
||||||
|
Topic string
|
||||||
|
CommandTopic string
|
||||||
|
StatusTopic string
|
||||||
|
HomeAssistant HomeAssistantConfig
|
||||||
|
Username string
|
||||||
|
Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
type writeCommand struct {
|
||||||
|
RequestID string
|
||||||
|
Kind string
|
||||||
|
ID uint16
|
||||||
|
Value int16
|
||||||
|
HasSwitch bool
|
||||||
|
SwitchState mk2driver.PanelSwitchState
|
||||||
|
SwitchName string
|
||||||
|
CurrentLimitA *float64
|
||||||
|
Standby *bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type writeCommandPayload struct {
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
ID *uint16 `json:"id"`
|
||||||
|
Value json.RawMessage `json:"value"`
|
||||||
|
Switch string `json:"switch"`
|
||||||
|
SwitchState string `json:"switch_state"`
|
||||||
|
CurrentLimitA *float64 `json:"current_limit"`
|
||||||
|
Standby *bool `json:"standby"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type writeStatus struct {
|
||||||
|
RequestID string `json:"request_id,omitempty"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Kind string `json:"kind,omitempty"`
|
||||||
|
ID uint16 `json:"id"`
|
||||||
|
Value int16 `json:"value"`
|
||||||
|
Switch string `json:"switch,omitempty"`
|
||||||
|
CurrentLimitA *float64 `json:"current_limit,omitempty"`
|
||||||
|
Standby *bool `json:"standby,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type haDiscoveryDefinition struct {
|
||||||
|
Component string
|
||||||
|
ObjectID string
|
||||||
|
Config map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
type panelStateCache struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
hasSwitch bool
|
||||||
|
switchName string
|
||||||
|
switchState mk2driver.PanelSwitchState
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates an MQTT client that publishes MK2 updates and optionally handles setting write commands.
|
||||||
|
func New(mk2 mk2driver.Mk2, writer mk2driver.SettingsWriter, config Config) error {
|
||||||
c := mqtt.NewClient(getOpts(config))
|
c := mqtt.NewClient(getOpts(config))
|
||||||
if token := c.Connect(); token.Wait() && token.Error() != nil {
|
if token := c.Connect(); token.Wait() && token.Error() != nil {
|
||||||
return token.Error()
|
return token.Error()
|
||||||
}
|
}
|
||||||
|
cache := &panelStateCache{}
|
||||||
|
|
||||||
|
if config.HomeAssistant.Enabled {
|
||||||
|
if err := publishHAAvailability(c, config, "online"); err != nil {
|
||||||
|
return fmt.Errorf("could not publish Home Assistant availability: %w", err)
|
||||||
|
}
|
||||||
|
if err := publishHADiscovery(c, config); err != nil {
|
||||||
|
return fmt.Errorf("could not publish Home Assistant discovery payloads: %w", err)
|
||||||
|
}
|
||||||
|
if writer != nil {
|
||||||
|
if err := subscribeHAPanelModeState(c, config, cache); err != nil {
|
||||||
|
log.Warnf("Could not subscribe to Home Assistant panel mode state topic: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if config.CommandTopic != "" {
|
||||||
|
if writer == nil {
|
||||||
|
log.Warnf("MQTT command topic %q configured, but no settings writer is available", config.CommandTopic)
|
||||||
|
} else {
|
||||||
|
t := c.Subscribe(config.CommandTopic, 1, commandHandler(c, writer, config, cache))
|
||||||
|
t.Wait()
|
||||||
|
if t.Error() != nil {
|
||||||
|
return fmt.Errorf("could not subscribe to MQTT command topic %q: %w", config.CommandTopic, t.Error())
|
||||||
|
}
|
||||||
|
log.Infof("Subscribed to MQTT command topic: %s", config.CommandTopic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
for e := range mk2.C() {
|
for e := range mk2.C() {
|
||||||
if e.Valid {
|
if e == nil || !e.Valid {
|
||||||
data, err := json.Marshal(e)
|
continue
|
||||||
if err != nil {
|
}
|
||||||
log.Errorf("Could not parse data source: %v", err)
|
if err := publishJSON(c, config.Topic, e, 0, false); err != nil {
|
||||||
continue
|
log.Errorf("Could not publish update to MQTT topic %q: %v", config.Topic, err)
|
||||||
}
|
|
||||||
|
|
||||||
t := c.Publish(config.Topic, 0, false, data)
|
|
||||||
t.Wait()
|
|
||||||
if t.Error() != nil {
|
|
||||||
log.Errorf("Could not publish data: %v", t.Error())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func subscribeHAPanelModeState(client mqtt.Client, config Config, cache *panelStateCache) error {
|
||||||
|
if cache == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
stateTopic := haPanelSwitchStateTopic(config)
|
||||||
|
t := client.Subscribe(stateTopic, 1, func(_ mqtt.Client, msg mqtt.Message) {
|
||||||
|
switchState, switchName, err := normalizePanelSwitch(string(msg.Payload()))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cache.remember(writeCommand{
|
||||||
|
Kind: commandKindPanel,
|
||||||
|
HasSwitch: true,
|
||||||
|
SwitchState: switchState,
|
||||||
|
SwitchName: switchName,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
t.Wait()
|
||||||
|
return t.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
func commandHandler(client mqtt.Client, writer mk2driver.SettingsWriter, config Config, cache *panelStateCache) mqtt.MessageHandler {
|
||||||
|
if cache == nil {
|
||||||
|
cache = &panelStateCache{}
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(_ mqtt.Client, msg mqtt.Message) {
|
||||||
|
cmd, err := decodeWriteCommand(msg.Payload())
|
||||||
|
if err != nil {
|
||||||
|
log.Errorf("Invalid MQTT write command payload from topic %q: %v", msg.Topic(), err)
|
||||||
|
publishWriteStatus(client, config.StatusTopic, writeStatus{
|
||||||
|
Status: writeStatusError,
|
||||||
|
Error: err.Error(),
|
||||||
|
Timestamp: time.Now().UTC(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
execCmd := cmd
|
||||||
|
status := writeStatus{
|
||||||
|
RequestID: cmd.RequestID,
|
||||||
|
Status: writeStatusOK,
|
||||||
|
Kind: cmd.Kind,
|
||||||
|
Timestamp: time.Now().UTC(),
|
||||||
|
}
|
||||||
|
switch cmd.Kind {
|
||||||
|
case commandKindPanel:
|
||||||
|
execCmd, err = cache.resolvePanelCommand(cmd)
|
||||||
|
if err != nil {
|
||||||
|
status.Status = writeStatusError
|
||||||
|
status.Error = err.Error()
|
||||||
|
log.Errorf("Invalid MQTT write command %s: %v", formatWriteCommandLog(cmd), err)
|
||||||
|
publishWriteStatus(client, config.StatusTopic, status)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
status.Switch = execCmd.SwitchName
|
||||||
|
status.CurrentLimitA = execCmd.CurrentLimitA
|
||||||
|
case commandKindStandby:
|
||||||
|
status.Standby = copyBoolPtr(execCmd.Standby)
|
||||||
|
default:
|
||||||
|
status.ID = cmd.ID
|
||||||
|
status.Value = cmd.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := executeWriteCommand(writer, execCmd); err != nil {
|
||||||
|
status.Status = writeStatusError
|
||||||
|
status.Error = err.Error()
|
||||||
|
log.Errorf("Failed MQTT write command %s: %v", formatWriteCommandLog(execCmd), err)
|
||||||
|
} else {
|
||||||
|
log.Infof("Applied MQTT write command %s", formatWriteCommandLog(execCmd))
|
||||||
|
cache.remember(execCmd)
|
||||||
|
if config.HomeAssistant.Enabled {
|
||||||
|
if err := publishHAControlState(client, config, execCmd); err != nil {
|
||||||
|
log.Errorf("Could not publish Home Assistant control state update: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
publishWriteStatus(client, config.StatusTopic, status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *panelStateCache) resolvePanelCommand(cmd writeCommand) (writeCommand, error) {
|
||||||
|
if cmd.Kind != commandKindPanel {
|
||||||
|
return cmd, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if cmd.HasSwitch {
|
||||||
|
return cmd, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if !c.hasSwitch {
|
||||||
|
return writeCommand{}, errors.New("panel_state command missing switch and no prior mode is known; set mode once first")
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd.HasSwitch = true
|
||||||
|
cmd.SwitchName = c.switchName
|
||||||
|
cmd.SwitchState = c.switchState
|
||||||
|
return cmd, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *panelStateCache) remember(cmd writeCommand) {
|
||||||
|
if cmd.Kind != commandKindPanel || !cmd.HasSwitch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.mu.Lock()
|
||||||
|
c.hasSwitch = true
|
||||||
|
c.switchName = cmd.SwitchName
|
||||||
|
c.switchState = cmd.SwitchState
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeWriteCommand(payload []byte) (writeCommand, error) {
|
||||||
|
msg := writeCommandPayload{}
|
||||||
|
if err := json.Unmarshal(payload, &msg); err != nil {
|
||||||
|
return writeCommand{}, fmt.Errorf("invalid JSON payload: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
kind := msg.Kind
|
||||||
|
if kind == "" {
|
||||||
|
kind = msg.Type
|
||||||
|
}
|
||||||
|
normalizedKind, err := normalizeWriteKind(kind)
|
||||||
|
if err != nil {
|
||||||
|
return writeCommand{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if normalizedKind == commandKindPanel {
|
||||||
|
switchName := msg.Switch
|
||||||
|
if switchName == "" {
|
||||||
|
switchName = msg.SwitchState
|
||||||
|
}
|
||||||
|
|
||||||
|
hasSwitch := false
|
||||||
|
switchState := mk2driver.PanelSwitchState(0)
|
||||||
|
normalizedSwitchName := ""
|
||||||
|
if switchName != "" {
|
||||||
|
var err error
|
||||||
|
switchState, normalizedSwitchName, err = normalizePanelSwitch(switchName)
|
||||||
|
if err != nil {
|
||||||
|
return writeCommand{}, err
|
||||||
|
}
|
||||||
|
hasSwitch = true
|
||||||
|
}
|
||||||
|
if msg.CurrentLimitA != nil && *msg.CurrentLimitA < 0 {
|
||||||
|
return writeCommand{}, fmt.Errorf("current_limit must be >= 0, got %.3f", *msg.CurrentLimitA)
|
||||||
|
}
|
||||||
|
if !hasSwitch && msg.CurrentLimitA == nil {
|
||||||
|
return writeCommand{}, errors.New(`missing required field "switch" (or "switch_state"), or "current_limit"`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return writeCommand{
|
||||||
|
RequestID: msg.RequestID,
|
||||||
|
Kind: normalizedKind,
|
||||||
|
HasSwitch: hasSwitch,
|
||||||
|
SwitchState: switchState,
|
||||||
|
SwitchName: normalizedSwitchName,
|
||||||
|
CurrentLimitA: msg.CurrentLimitA,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if normalizedKind == commandKindStandby {
|
||||||
|
standby, err := decodeStandbyValue(msg)
|
||||||
|
if err != nil {
|
||||||
|
return writeCommand{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return writeCommand{
|
||||||
|
RequestID: msg.RequestID,
|
||||||
|
Kind: normalizedKind,
|
||||||
|
Standby: &standby,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if msg.ID == nil {
|
||||||
|
return writeCommand{}, errors.New(`missing required field "id"`)
|
||||||
|
}
|
||||||
|
value, err := decodeInt16Value(msg.Value)
|
||||||
|
if err != nil {
|
||||||
|
return writeCommand{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return writeCommand{
|
||||||
|
RequestID: msg.RequestID,
|
||||||
|
Kind: normalizedKind,
|
||||||
|
ID: *msg.ID,
|
||||||
|
Value: value,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeWriteKind(raw string) (string, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||||
|
case "setting", "settings":
|
||||||
|
return commandKindSetting, nil
|
||||||
|
case "ram", "ramvar", "ram_var", "ram-variable", "ramvariable":
|
||||||
|
return commandKindRAMVar, nil
|
||||||
|
case "panel", "panel_state", "switch", "remote_panel":
|
||||||
|
return commandKindPanel, nil
|
||||||
|
case "standby", "panel_standby", "remote_panel_standby":
|
||||||
|
return commandKindStandby, nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("unsupported write command kind %q", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizePanelSwitch(raw string) (mk2driver.PanelSwitchState, string, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||||
|
case "1", "charger_only", "charger-only", "charger":
|
||||||
|
return mk2driver.PanelSwitchChargerOnly, "charger_only", nil
|
||||||
|
case "2", "inverter_only", "inverter-only", "inverter":
|
||||||
|
return mk2driver.PanelSwitchInverterOnly, "inverter_only", nil
|
||||||
|
case "3", "on":
|
||||||
|
return mk2driver.PanelSwitchOn, "on", nil
|
||||||
|
case "4", "off":
|
||||||
|
return mk2driver.PanelSwitchOff, "off", nil
|
||||||
|
default:
|
||||||
|
return 0, "", fmt.Errorf("unsupported panel switch %q", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func executeWriteCommand(writer mk2driver.SettingsWriter, cmd writeCommand) error {
|
||||||
|
if writer == nil {
|
||||||
|
return errors.New("settings writer is not available")
|
||||||
|
}
|
||||||
|
switch cmd.Kind {
|
||||||
|
case commandKindPanel:
|
||||||
|
if !cmd.HasSwitch {
|
||||||
|
return errors.New("panel_state command requires a switch state")
|
||||||
|
}
|
||||||
|
return writer.SetPanelState(cmd.SwitchState, cmd.CurrentLimitA)
|
||||||
|
case commandKindStandby:
|
||||||
|
if cmd.Standby == nil {
|
||||||
|
return errors.New("standby command missing standby value")
|
||||||
|
}
|
||||||
|
return writer.SetStandby(*cmd.Standby)
|
||||||
|
case commandKindRAMVar:
|
||||||
|
return writer.WriteRAMVar(cmd.ID, cmd.Value)
|
||||||
|
case commandKindSetting:
|
||||||
|
return writer.WriteSetting(cmd.ID, cmd.Value)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported write command kind %q", cmd.Kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatWriteCommandLog(cmd writeCommand) string {
|
||||||
|
switch cmd.Kind {
|
||||||
|
case commandKindPanel:
|
||||||
|
switchName := cmd.SwitchName
|
||||||
|
if switchName == "" {
|
||||||
|
switchName = "<cached>"
|
||||||
|
}
|
||||||
|
if cmd.CurrentLimitA == nil {
|
||||||
|
return fmt.Sprintf("kind=%s switch=%s", cmd.Kind, switchName)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("kind=%s switch=%s current_limit=%.3f", cmd.Kind, switchName, *cmd.CurrentLimitA)
|
||||||
|
case commandKindStandby:
|
||||||
|
if cmd.Standby == nil {
|
||||||
|
return fmt.Sprintf("kind=%s standby=<unset>", cmd.Kind)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("kind=%s standby=%t", cmd.Kind, *cmd.Standby)
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("kind=%s id=%d value=%d", cmd.Kind, cmd.ID, cmd.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeInt16Value(raw json.RawMessage) (int16, error) {
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return 0, errors.New(`missing required field "value"`)
|
||||||
|
}
|
||||||
|
|
||||||
|
var value int16
|
||||||
|
if err := json.Unmarshal(raw, &value); err != nil {
|
||||||
|
return 0, fmt.Errorf(`field "value" must be a signed integer: %w`, err)
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeStandbyValue(msg writeCommandPayload) (bool, error) {
|
||||||
|
if msg.Standby != nil {
|
||||||
|
return *msg.Standby, nil
|
||||||
|
}
|
||||||
|
if len(msg.Value) == 0 {
|
||||||
|
return false, errors.New(`missing required field "standby" (or boolean "value")`)
|
||||||
|
}
|
||||||
|
|
||||||
|
var boolValue bool
|
||||||
|
if err := json.Unmarshal(msg.Value, &boolValue); err == nil {
|
||||||
|
return boolValue, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var stringValue string
|
||||||
|
if err := json.Unmarshal(msg.Value, &stringValue); err == nil {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(stringValue)) {
|
||||||
|
case "1", "true", "on", "enable", "enabled":
|
||||||
|
return true, nil
|
||||||
|
case "0", "false", "off", "disable", "disabled":
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var intValue int
|
||||||
|
if err := json.Unmarshal(msg.Value, &intValue); err == nil {
|
||||||
|
switch intValue {
|
||||||
|
case 1:
|
||||||
|
return true, nil
|
||||||
|
case 0:
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false, errors.New(`field "standby" must be true/false`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func publishWriteStatus(client mqtt.Client, topic string, status writeStatus) {
|
||||||
|
if topic == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := publishJSON(client, topic, status, 1, false); err != nil {
|
||||||
|
log.Errorf("Could not publish command status to MQTT topic %q: %v", topic, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func publishHADiscovery(client mqtt.Client, config Config) error {
|
||||||
|
definitions := buildHADiscoveryDefinitions(config)
|
||||||
|
prefix := haDiscoveryPrefix(config)
|
||||||
|
nodeID := haNodeID(config)
|
||||||
|
|
||||||
|
for _, def := range definitions {
|
||||||
|
topic := fmt.Sprintf("%s/%s/%s/%s/config", prefix, def.Component, nodeID, def.ObjectID)
|
||||||
|
if err := publishJSON(client, topic, def.Config, 1, true); err != nil {
|
||||||
|
return fmt.Errorf("could not publish discovery for %s/%s: %w", def.Component, def.ObjectID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildHADiscoveryDefinitions(config Config) []haDiscoveryDefinition {
|
||||||
|
if !config.HomeAssistant.Enabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
nodeID := haNodeID(config)
|
||||||
|
device := map[string]any{
|
||||||
|
"identifiers": []string{fmt.Sprintf("invertergui_%s", nodeID)},
|
||||||
|
"name": haDeviceName(config),
|
||||||
|
"manufacturer": "Victron Energy",
|
||||||
|
"model": "MultiPlus",
|
||||||
|
"sw_version": "invertergui",
|
||||||
|
}
|
||||||
|
availabilityTopic := haAvailabilityTopic(config)
|
||||||
|
stateTopic := config.Topic
|
||||||
|
|
||||||
|
sensors := []haDiscoveryDefinition{
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "battery_voltage", "Battery Voltage", "{{ value_json.BatVoltage }}", "V", "voltage", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "battery_current", "Battery Current", "{{ value_json.BatCurrent }}", "A", "current", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "battery_charge", "Battery Charge", "{{ ((value_json.ChargeState | float(0)) * 100) | round(1) }}", "%", "battery", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "input_voltage", "Input Voltage", "{{ value_json.InVoltage }}", "V", "voltage", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "input_current", "Input Current", "{{ value_json.InCurrent }}", "A", "current", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "input_frequency", "Input Frequency", "{{ value_json.InFrequency }}", "Hz", "frequency", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "output_voltage", "Output Voltage", "{{ value_json.OutVoltage }}", "V", "voltage", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "output_current", "Output Current", "{{ value_json.OutCurrent }}", "A", "current", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "output_frequency", "Output Frequency", "{{ value_json.OutFrequency }}", "Hz", "frequency", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "input_power", "Input Power", "{{ ((value_json.InVoltage | float(0)) * (value_json.InCurrent | float(0))) | round(1) }}", "VA", "", "measurement"),
|
||||||
|
buildHASensor(device, availabilityTopic, stateTopic, nodeID, "output_power", "Output Power", "{{ ((value_json.OutVoltage | float(0)) * (value_json.OutCurrent | float(0))) | round(1) }}", "VA", "", "measurement"),
|
||||||
|
{
|
||||||
|
Component: "binary_sensor",
|
||||||
|
ObjectID: "data_valid",
|
||||||
|
Config: map[string]any{
|
||||||
|
"name": "Data Valid",
|
||||||
|
"unique_id": fmt.Sprintf("%s_data_valid", nodeID),
|
||||||
|
"state_topic": stateTopic,
|
||||||
|
"value_template": "{{ value_json.Valid }}",
|
||||||
|
"payload_on": "true",
|
||||||
|
"payload_off": "false",
|
||||||
|
"availability_topic": availabilityTopic,
|
||||||
|
"device": device,
|
||||||
|
"entity_category": "diagnostic",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if config.CommandTopic != "" {
|
||||||
|
sensors = append(sensors,
|
||||||
|
haDiscoveryDefinition{
|
||||||
|
Component: "select",
|
||||||
|
ObjectID: "remote_panel_mode",
|
||||||
|
Config: map[string]any{
|
||||||
|
"name": "Remote Panel Mode",
|
||||||
|
"unique_id": fmt.Sprintf("%s_remote_panel_mode", nodeID),
|
||||||
|
"state_topic": haPanelSwitchStateTopic(config),
|
||||||
|
"command_topic": config.CommandTopic,
|
||||||
|
"command_template": "{\"kind\":\"panel_state\",\"switch\":\"{{ value }}\"}",
|
||||||
|
"options": []string{"charger_only", "inverter_only", "on", "off"},
|
||||||
|
"availability_topic": availabilityTopic,
|
||||||
|
"device": device,
|
||||||
|
"icon": "mdi:transmission-tower-export",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
haDiscoveryDefinition{
|
||||||
|
Component: "number",
|
||||||
|
ObjectID: "remote_panel_current_limit",
|
||||||
|
Config: map[string]any{
|
||||||
|
"name": "Remote Panel Current Limit",
|
||||||
|
"unique_id": fmt.Sprintf("%s_remote_panel_current_limit", nodeID),
|
||||||
|
"state_topic": haCurrentLimitStateTopic(config),
|
||||||
|
"command_topic": config.CommandTopic,
|
||||||
|
"command_template": "{\"kind\":\"panel_state\",\"current_limit\":{{ value | float(0) }}}",
|
||||||
|
"unit_of_measurement": "A",
|
||||||
|
"device_class": "current",
|
||||||
|
"mode": "box",
|
||||||
|
"min": 0,
|
||||||
|
"max": 100,
|
||||||
|
"step": 0.1,
|
||||||
|
"availability_topic": availabilityTopic,
|
||||||
|
"device": device,
|
||||||
|
"icon": "mdi:current-ac",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
haDiscoveryDefinition{
|
||||||
|
Component: "switch",
|
||||||
|
ObjectID: "remote_panel_standby",
|
||||||
|
Config: map[string]any{
|
||||||
|
"name": "Remote Panel Standby",
|
||||||
|
"unique_id": fmt.Sprintf("%s_remote_panel_standby", nodeID),
|
||||||
|
"state_topic": haStandbyStateTopic(config),
|
||||||
|
"command_topic": config.CommandTopic,
|
||||||
|
"payload_on": "{\"kind\":\"standby\",\"standby\":true}",
|
||||||
|
"payload_off": "{\"kind\":\"standby\",\"standby\":false}",
|
||||||
|
"state_on": "ON",
|
||||||
|
"state_off": "OFF",
|
||||||
|
"availability_topic": availabilityTopic,
|
||||||
|
"device": device,
|
||||||
|
"icon": "mdi:power-sleep",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return sensors
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildHASensor(device map[string]any, availabilityTopic, stateTopic, nodeID, objectID, name, valueTemplate, unit, deviceClass, stateClass string) haDiscoveryDefinition {
|
||||||
|
config := map[string]any{
|
||||||
|
"name": name,
|
||||||
|
"unique_id": fmt.Sprintf("%s_%s", nodeID, objectID),
|
||||||
|
"state_topic": stateTopic,
|
||||||
|
"value_template": valueTemplate,
|
||||||
|
"availability_topic": availabilityTopic,
|
||||||
|
"device": device,
|
||||||
|
}
|
||||||
|
if unit != "" {
|
||||||
|
config["unit_of_measurement"] = unit
|
||||||
|
}
|
||||||
|
if deviceClass != "" {
|
||||||
|
config["device_class"] = deviceClass
|
||||||
|
}
|
||||||
|
if stateClass != "" {
|
||||||
|
config["state_class"] = stateClass
|
||||||
|
}
|
||||||
|
|
||||||
|
return haDiscoveryDefinition{
|
||||||
|
Component: "sensor",
|
||||||
|
ObjectID: objectID,
|
||||||
|
Config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func publishHAAvailability(client mqtt.Client, config Config, status string) error {
|
||||||
|
return publishString(client, haAvailabilityTopic(config), status, 1, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func publishHAControlState(client mqtt.Client, config Config, cmd writeCommand) error {
|
||||||
|
switch cmd.Kind {
|
||||||
|
case commandKindPanel:
|
||||||
|
if err := publishString(client, haPanelSwitchStateTopic(config), cmd.SwitchName, 1, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if cmd.CurrentLimitA != nil {
|
||||||
|
limit := strconv.FormatFloat(*cmd.CurrentLimitA, 'f', 1, 64)
|
||||||
|
if err := publishString(client, haCurrentLimitStateTopic(config), limit, 1, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case commandKindStandby:
|
||||||
|
if cmd.Standby == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
state := "OFF"
|
||||||
|
if *cmd.Standby {
|
||||||
|
state = "ON"
|
||||||
|
}
|
||||||
|
if err := publishString(client, haStandbyStateTopic(config), state, 1, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func publishJSON(client mqtt.Client, topic string, payload any, qos byte, retained bool) error {
|
||||||
|
if topic == "" {
|
||||||
|
return errors.New("topic is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("could not marshal payload: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t := client.Publish(topic, qos, retained, data)
|
||||||
|
t.Wait()
|
||||||
|
if t.Error() != nil {
|
||||||
|
return t.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func publishString(client mqtt.Client, topic, payload string, qos byte, retained bool) error {
|
||||||
|
if topic == "" {
|
||||||
|
return errors.New("topic is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
t := client.Publish(topic, qos, retained, payload)
|
||||||
|
t.Wait()
|
||||||
|
if t.Error() != nil {
|
||||||
|
return t.Error()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mqttTopicRoot(topic string) string {
|
||||||
|
t := strings.Trim(strings.TrimSpace(topic), "/")
|
||||||
|
if t == "" {
|
||||||
|
return "invertergui"
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(t, "/updates") {
|
||||||
|
root := strings.TrimSuffix(t, "/updates")
|
||||||
|
if root != "" {
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
func haAvailabilityTopic(config Config) string {
|
||||||
|
return fmt.Sprintf("%s/homeassistant/availability", mqttTopicRoot(config.Topic))
|
||||||
|
}
|
||||||
|
|
||||||
|
func haPanelSwitchStateTopic(config Config) string {
|
||||||
|
return fmt.Sprintf("%s/homeassistant/remote_panel_mode/state", mqttTopicRoot(config.Topic))
|
||||||
|
}
|
||||||
|
|
||||||
|
func haCurrentLimitStateTopic(config Config) string {
|
||||||
|
return fmt.Sprintf("%s/homeassistant/remote_panel_current_limit/state", mqttTopicRoot(config.Topic))
|
||||||
|
}
|
||||||
|
|
||||||
|
func haStandbyStateTopic(config Config) string {
|
||||||
|
return fmt.Sprintf("%s/homeassistant/remote_panel_standby/state", mqttTopicRoot(config.Topic))
|
||||||
|
}
|
||||||
|
|
||||||
|
func haDiscoveryPrefix(config Config) string {
|
||||||
|
prefix := strings.Trim(strings.TrimSpace(config.HomeAssistant.DiscoveryPrefix), "/")
|
||||||
|
if prefix == "" {
|
||||||
|
return "homeassistant"
|
||||||
|
}
|
||||||
|
return prefix
|
||||||
|
}
|
||||||
|
|
||||||
|
func haNodeID(config Config) string {
|
||||||
|
nodeID := normalizeID(config.HomeAssistant.NodeID)
|
||||||
|
if nodeID == "" {
|
||||||
|
nodeID = normalizeID(config.ClientID)
|
||||||
|
}
|
||||||
|
if nodeID == "" {
|
||||||
|
return "invertergui"
|
||||||
|
}
|
||||||
|
return nodeID
|
||||||
|
}
|
||||||
|
|
||||||
|
func haDeviceName(config Config) string {
|
||||||
|
name := strings.TrimSpace(config.HomeAssistant.DeviceName)
|
||||||
|
if name == "" {
|
||||||
|
return "Victron Inverter"
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeID(in string) string {
|
||||||
|
trimmed := strings.TrimSpace(strings.ToLower(in))
|
||||||
|
if trimmed == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
lastUnderscore := false
|
||||||
|
for _, r := range trimmed {
|
||||||
|
valid := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_'
|
||||||
|
if valid {
|
||||||
|
b.WriteRune(r)
|
||||||
|
lastUnderscore = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !lastUnderscore {
|
||||||
|
b.WriteRune('_')
|
||||||
|
lastUnderscore = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Trim(b.String(), "_")
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyBoolPtr(in *bool) *bool {
|
||||||
|
if in == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
value := *in
|
||||||
|
return &value
|
||||||
|
}
|
||||||
|
|
||||||
func getOpts(config Config) *mqtt.ClientOptions {
|
func getOpts(config Config) *mqtt.ClientOptions {
|
||||||
opts := mqtt.NewClientOptions()
|
opts := mqtt.NewClientOptions()
|
||||||
opts.AddBroker(config.Broker)
|
opts.AddBroker(config.Broker)
|
||||||
@@ -60,14 +781,16 @@ func getOpts(config Config) *mqtt.ClientOptions {
|
|||||||
if config.Password != "" {
|
if config.Password != "" {
|
||||||
opts.SetPassword(config.Password)
|
opts.SetPassword(config.Password)
|
||||||
}
|
}
|
||||||
|
if config.HomeAssistant.Enabled {
|
||||||
|
opts.SetWill(haAvailabilityTopic(config), "offline", 1, true)
|
||||||
|
}
|
||||||
opts.SetKeepAlive(keepAlive)
|
opts.SetKeepAlive(keepAlive)
|
||||||
|
|
||||||
opts.SetOnConnectHandler(func(mqtt.Client) {
|
opts.SetOnConnectHandler(func(mqtt.Client) {
|
||||||
log.Info("Client connected to broker")
|
log.Info("Client connected to broker")
|
||||||
})
|
})
|
||||||
opts.SetConnectionLostHandler(func(cli mqtt.Client, err error) {
|
opts.SetConnectionLostHandler(func(_ mqtt.Client, err error) {
|
||||||
log.Errorf("Client connection to broker lost: %v", err)
|
log.Errorf("Client connection to broker lost: %v", err)
|
||||||
|
|
||||||
})
|
})
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|||||||
316
plugins/mqttclient/mqtt_test.go
Normal file
316
plugins/mqttclient/mqtt_test.go
Normal file
@@ -0,0 +1,316 @@
|
|||||||
|
package mqttclient
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"invertergui/mk2driver"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeWriter struct {
|
||||||
|
lastKind string
|
||||||
|
lastID uint16
|
||||||
|
lastValue int16
|
||||||
|
lastSwitchState mk2driver.PanelSwitchState
|
||||||
|
lastCurrentLimit *float64
|
||||||
|
lastStandby *bool
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeWriter) WriteRAMVar(id uint16, value int16) error {
|
||||||
|
f.lastKind = commandKindRAMVar
|
||||||
|
f.lastID = id
|
||||||
|
f.lastValue = value
|
||||||
|
return f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeWriter) WriteSetting(id uint16, value int16) error {
|
||||||
|
f.lastKind = commandKindSetting
|
||||||
|
f.lastID = id
|
||||||
|
f.lastValue = value
|
||||||
|
return f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeWriter) SetPanelState(switchState mk2driver.PanelSwitchState, currentLimitA *float64) error {
|
||||||
|
f.lastKind = commandKindPanel
|
||||||
|
f.lastSwitchState = switchState
|
||||||
|
f.lastCurrentLimit = currentLimitA
|
||||||
|
return f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeWriter) SetStandby(standby bool) error {
|
||||||
|
f.lastKind = commandKindStandby
|
||||||
|
f.lastStandby = &standby
|
||||||
|
return f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decodeWriteCommand(t *testing.T) {
|
||||||
|
currentLimit := 16.5
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
payload string
|
||||||
|
check func(*testing.T, writeCommand)
|
||||||
|
wantErr string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "setting",
|
||||||
|
payload: `{"request_id":"abc","kind":"setting","id":15,"value":-5}`,
|
||||||
|
check: func(t *testing.T, got writeCommand) {
|
||||||
|
assert.Equal(t, writeCommand{
|
||||||
|
RequestID: "abc",
|
||||||
|
Kind: commandKindSetting,
|
||||||
|
ID: 15,
|
||||||
|
Value: -5,
|
||||||
|
}, got)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "ram_var alias from type",
|
||||||
|
payload: `{"type":"ramvar","id":2,"value":7}`,
|
||||||
|
check: func(t *testing.T, got writeCommand) {
|
||||||
|
assert.Equal(t, writeCommand{
|
||||||
|
Kind: commandKindRAMVar,
|
||||||
|
ID: 2,
|
||||||
|
Value: 7,
|
||||||
|
}, got)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "panel state",
|
||||||
|
payload: `{"kind":"panel_state","switch":"on","current_limit":16.5}`,
|
||||||
|
check: func(t *testing.T, got writeCommand) {
|
||||||
|
assert.Equal(t, commandKindPanel, got.Kind)
|
||||||
|
assert.True(t, got.HasSwitch)
|
||||||
|
assert.Equal(t, mk2driver.PanelSwitchOn, got.SwitchState)
|
||||||
|
assert.Equal(t, "on", got.SwitchName)
|
||||||
|
if assert.NotNil(t, got.CurrentLimitA) {
|
||||||
|
assert.Equal(t, currentLimit, *got.CurrentLimitA)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "panel current limit only",
|
||||||
|
payload: `{"kind":"panel_state","current_limit":12.0}`,
|
||||||
|
check: func(t *testing.T, got writeCommand) {
|
||||||
|
assert.Equal(t, commandKindPanel, got.Kind)
|
||||||
|
assert.False(t, got.HasSwitch)
|
||||||
|
assert.Nil(t, got.Standby)
|
||||||
|
if assert.NotNil(t, got.CurrentLimitA) {
|
||||||
|
assert.Equal(t, 12.0, *got.CurrentLimitA)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "standby bool",
|
||||||
|
payload: `{"kind":"standby","standby":true}`,
|
||||||
|
check: func(t *testing.T, got writeCommand) {
|
||||||
|
assert.Equal(t, commandKindStandby, got.Kind)
|
||||||
|
if assert.NotNil(t, got.Standby) {
|
||||||
|
assert.True(t, *got.Standby)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "standby using value string",
|
||||||
|
payload: `{"kind":"standby","value":"OFF"}`,
|
||||||
|
check: func(t *testing.T, got writeCommand) {
|
||||||
|
assert.Equal(t, commandKindStandby, got.Kind)
|
||||||
|
if assert.NotNil(t, got.Standby) {
|
||||||
|
assert.False(t, *got.Standby)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing id",
|
||||||
|
payload: `{"kind":"setting","value":1}`,
|
||||||
|
wantErr: `missing required field "id"`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing panel switch and current limit",
|
||||||
|
payload: `{"kind":"panel_state"}`,
|
||||||
|
wantErr: `missing required field "switch"`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid standby",
|
||||||
|
payload: `{"kind":"standby","value":"banana"}`,
|
||||||
|
wantErr: `field "standby" must be true/false`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid kind",
|
||||||
|
payload: `{"kind":"unknown","id":1,"value":1}`,
|
||||||
|
wantErr: `unsupported write command kind "unknown"`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := decodeWriteCommand([]byte(tt.payload))
|
||||||
|
if tt.wantErr != "" {
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.ErrorContains(t, err, tt.wantErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.NoError(t, err)
|
||||||
|
tt.check(t, got)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_executeWriteCommand(t *testing.T) {
|
||||||
|
limit := 8.0
|
||||||
|
standby := true
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
cmd writeCommand
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "setting",
|
||||||
|
cmd: writeCommand{
|
||||||
|
Kind: commandKindSetting,
|
||||||
|
ID: 9,
|
||||||
|
Value: 2,
|
||||||
|
},
|
||||||
|
want: commandKindSetting,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "ram_var",
|
||||||
|
cmd: writeCommand{
|
||||||
|
Kind: commandKindRAMVar,
|
||||||
|
ID: 3,
|
||||||
|
Value: -1,
|
||||||
|
},
|
||||||
|
want: commandKindRAMVar,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "panel_state",
|
||||||
|
cmd: writeCommand{
|
||||||
|
Kind: commandKindPanel,
|
||||||
|
HasSwitch: true,
|
||||||
|
SwitchState: mk2driver.PanelSwitchInverterOnly,
|
||||||
|
CurrentLimitA: &limit,
|
||||||
|
},
|
||||||
|
want: commandKindPanel,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "standby",
|
||||||
|
cmd: writeCommand{
|
||||||
|
Kind: commandKindStandby,
|
||||||
|
Standby: &standby,
|
||||||
|
},
|
||||||
|
want: commandKindStandby,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
writer := &fakeWriter{}
|
||||||
|
err := executeWriteCommand(writer, tt.cmd)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, tt.want, writer.lastKind)
|
||||||
|
switch tt.want {
|
||||||
|
case commandKindPanel:
|
||||||
|
assert.Equal(t, tt.cmd.SwitchState, writer.lastSwitchState)
|
||||||
|
if assert.NotNil(t, writer.lastCurrentLimit) {
|
||||||
|
assert.Equal(t, *tt.cmd.CurrentLimitA, *writer.lastCurrentLimit)
|
||||||
|
}
|
||||||
|
case commandKindStandby:
|
||||||
|
if assert.NotNil(t, writer.lastStandby) {
|
||||||
|
assert.Equal(t, *tt.cmd.Standby, *writer.lastStandby)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
assert.Equal(t, tt.cmd.ID, writer.lastID)
|
||||||
|
assert.Equal(t, tt.cmd.Value, writer.lastValue)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_buildHADiscoveryDefinitions(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Topic: "invertergui/updates",
|
||||||
|
CommandTopic: "invertergui/settings/set",
|
||||||
|
HomeAssistant: HomeAssistantConfig{
|
||||||
|
Enabled: true,
|
||||||
|
DiscoveryPrefix: "homeassistant",
|
||||||
|
NodeID: "victron_main",
|
||||||
|
DeviceName: "Shed Victron",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
definitions := buildHADiscoveryDefinitions(cfg)
|
||||||
|
assert.NotEmpty(t, definitions)
|
||||||
|
|
||||||
|
var panelMode *haDiscoveryDefinition
|
||||||
|
var panelCurrentLimit *haDiscoveryDefinition
|
||||||
|
var panelStandby *haDiscoveryDefinition
|
||||||
|
var batteryVoltage *haDiscoveryDefinition
|
||||||
|
for i := range definitions {
|
||||||
|
def := &definitions[i]
|
||||||
|
if def.Component == "select" && def.ObjectID == "remote_panel_mode" {
|
||||||
|
panelMode = def
|
||||||
|
}
|
||||||
|
if def.Component == "number" && def.ObjectID == "remote_panel_current_limit" {
|
||||||
|
panelCurrentLimit = def
|
||||||
|
}
|
||||||
|
if def.Component == "switch" && def.ObjectID == "remote_panel_standby" {
|
||||||
|
panelStandby = def
|
||||||
|
}
|
||||||
|
if def.Component == "sensor" && def.ObjectID == "battery_voltage" {
|
||||||
|
batteryVoltage = def
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if assert.NotNil(t, panelMode) {
|
||||||
|
assert.Equal(t, cfg.CommandTopic, panelMode.Config["command_topic"])
|
||||||
|
assert.Equal(t, haPanelSwitchStateTopic(cfg), panelMode.Config["state_topic"])
|
||||||
|
}
|
||||||
|
if assert.NotNil(t, panelCurrentLimit) {
|
||||||
|
assert.Equal(t, cfg.CommandTopic, panelCurrentLimit.Config["command_topic"])
|
||||||
|
assert.Equal(t, haCurrentLimitStateTopic(cfg), panelCurrentLimit.Config["state_topic"])
|
||||||
|
}
|
||||||
|
if assert.NotNil(t, panelStandby) {
|
||||||
|
assert.Equal(t, cfg.CommandTopic, panelStandby.Config["command_topic"])
|
||||||
|
assert.Equal(t, haStandbyStateTopic(cfg), panelStandby.Config["state_topic"])
|
||||||
|
}
|
||||||
|
if assert.NotNil(t, batteryVoltage) {
|
||||||
|
assert.Equal(t, cfg.Topic, batteryVoltage.Config["state_topic"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_panelStateCacheResolvePanelCommand(t *testing.T) {
|
||||||
|
cache := &panelStateCache{}
|
||||||
|
|
||||||
|
_, err := cache.resolvePanelCommand(writeCommand{
|
||||||
|
Kind: commandKindPanel,
|
||||||
|
CurrentLimitA: float64Ptr(12),
|
||||||
|
})
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
cache.remember(writeCommand{
|
||||||
|
Kind: commandKindPanel,
|
||||||
|
HasSwitch: true,
|
||||||
|
SwitchState: mk2driver.PanelSwitchOn,
|
||||||
|
SwitchName: "on",
|
||||||
|
})
|
||||||
|
|
||||||
|
resolved, err := cache.resolvePanelCommand(writeCommand{
|
||||||
|
Kind: commandKindPanel,
|
||||||
|
CurrentLimitA: float64Ptr(10),
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.True(t, resolved.HasSwitch)
|
||||||
|
assert.Equal(t, mk2driver.PanelSwitchOn, resolved.SwitchState)
|
||||||
|
assert.Equal(t, "on", resolved.SwitchName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func float64Ptr(in float64) *float64 {
|
||||||
|
return &in
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_normalizeID(t *testing.T) {
|
||||||
|
assert.Equal(t, "victron_main_01", normalizeID("Victron Main #01"))
|
||||||
|
assert.Equal(t, "inverter-gui", normalizeID(" inverter-gui "))
|
||||||
|
assert.Equal(t, "", normalizeID(" "))
|
||||||
|
}
|
||||||
@@ -36,7 +36,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -44,18 +44,18 @@ var log = logrus.WithField("ctx", "inverter-gui-munin")
|
|||||||
|
|
||||||
type Munin struct {
|
type Munin struct {
|
||||||
mk2driver.Mk2
|
mk2driver.Mk2
|
||||||
muninResponse chan *muninData
|
muninResponse chan muninData
|
||||||
}
|
}
|
||||||
|
|
||||||
type muninData struct {
|
type muninData struct {
|
||||||
status *mk2driver.Mk2Info
|
status mk2driver.Mk2Info
|
||||||
timesUpdated int
|
timesUpdated int
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMunin(mk2 mk2driver.Mk2) *Munin {
|
func NewMunin(mk2 mk2driver.Mk2) *Munin {
|
||||||
m := &Munin{
|
m := &Munin{
|
||||||
Mk2: mk2,
|
Mk2: mk2,
|
||||||
muninResponse: make(chan *muninData),
|
muninResponse: make(chan muninData),
|
||||||
}
|
}
|
||||||
|
|
||||||
go m.run()
|
go m.run()
|
||||||
@@ -63,7 +63,7 @@ func NewMunin(mk2 mk2driver.Mk2) *Munin {
|
|||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Munin) ServeMuninHTTP(rw http.ResponseWriter, r *http.Request) {
|
func (m *Munin) ServeMuninHTTP(rw http.ResponseWriter, _ *http.Request) {
|
||||||
muninDat := <-m.muninResponse
|
muninDat := <-m.muninResponse
|
||||||
if muninDat.timesUpdated == 0 {
|
if muninDat.timesUpdated == 0 {
|
||||||
log.Error("No data returned")
|
log.Error("No data returned")
|
||||||
@@ -71,10 +71,10 @@ func (m *Munin) ServeMuninHTTP(rw http.ResponseWriter, r *http.Request) {
|
|||||||
_, _ = rw.Write([]byte("No data to return.\n"))
|
_, _ = rw.Write([]byte("No data to return.\n"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
calcMuninAverages(muninDat)
|
calcMuninAverages(&muninDat)
|
||||||
|
|
||||||
status := muninDat.status
|
status := muninDat.status
|
||||||
tmpInput := buildTemplateInput(status)
|
tmpInput := buildTemplateInput(&status)
|
||||||
outputBuf := &bytes.Buffer{}
|
outputBuf := &bytes.Buffer{}
|
||||||
fmt.Fprintf(outputBuf, "multigraph in_batvolt\n")
|
fmt.Fprintf(outputBuf, "multigraph in_batvolt\n")
|
||||||
fmt.Fprintf(outputBuf, "volt.value %s\n", tmpInput.BatVoltage)
|
fmt.Fprintf(outputBuf, "volt.value %s\n", tmpInput.BatVoltage)
|
||||||
@@ -103,7 +103,7 @@ func (m *Munin) ServeMuninHTTP(rw http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Munin) ServeMuninConfigHTTP(rw http.ResponseWriter, r *http.Request) {
|
func (m *Munin) ServeMuninConfigHTTP(rw http.ResponseWriter, _ *http.Request) {
|
||||||
output := muninConfig
|
output := muninConfig
|
||||||
_, err := rw.Write([]byte(output))
|
_, err := rw.Write([]byte(output))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -113,65 +113,61 @@ func (m *Munin) ServeMuninConfigHTTP(rw http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (m *Munin) run() {
|
func (m *Munin) run() {
|
||||||
muninValues := &muninData{
|
muninValues := &muninData{
|
||||||
status: &mk2driver.Mk2Info{},
|
status: mk2driver.Mk2Info{},
|
||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case e := <-m.C():
|
case e := <-m.C():
|
||||||
if e.Valid {
|
if e.Valid {
|
||||||
calcMuninValues(muninValues, e)
|
calcMuninValues(muninValues, e)
|
||||||
|
|
||||||
}
|
}
|
||||||
case m.muninResponse <- muninValues:
|
case m.muninResponse <- *muninValues:
|
||||||
zeroMuninValues(muninValues)
|
zeroMuninValues(muninValues)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Munin only samples once every 5 minutes so averages have to be calculated for some values.
|
// Munin only samples once every 5 minutes so averages have to be calculated for some values.
|
||||||
func calcMuninValues(muninDat *muninData, newStatus *mk2driver.Mk2Info) {
|
func calcMuninValues(m *muninData, newStatus *mk2driver.Mk2Info) {
|
||||||
muninDat.timesUpdated++
|
m.timesUpdated++
|
||||||
muninVal := muninDat.status
|
m.status.OutCurrent += newStatus.OutCurrent
|
||||||
muninVal.OutCurrent += newStatus.OutCurrent
|
m.status.InCurrent += newStatus.InCurrent
|
||||||
muninVal.InCurrent += newStatus.InCurrent
|
m.status.BatCurrent += newStatus.BatCurrent
|
||||||
muninVal.BatCurrent += newStatus.BatCurrent
|
|
||||||
|
|
||||||
muninVal.OutVoltage += newStatus.OutVoltage
|
m.status.OutVoltage += newStatus.OutVoltage
|
||||||
muninVal.InVoltage += newStatus.InVoltage
|
m.status.InVoltage += newStatus.InVoltage
|
||||||
muninVal.BatVoltage += newStatus.BatVoltage
|
m.status.BatVoltage += newStatus.BatVoltage
|
||||||
|
|
||||||
muninVal.InFrequency = newStatus.InFrequency
|
m.status.InFrequency = newStatus.InFrequency
|
||||||
muninVal.OutFrequency = newStatus.OutFrequency
|
m.status.OutFrequency = newStatus.OutFrequency
|
||||||
|
|
||||||
muninVal.ChargeState = newStatus.ChargeState
|
m.status.ChargeState = newStatus.ChargeState
|
||||||
}
|
}
|
||||||
|
|
||||||
func calcMuninAverages(muninDat *muninData) {
|
func calcMuninAverages(m *muninData) {
|
||||||
muninVal := muninDat.status
|
m.status.OutCurrent /= float64(m.timesUpdated)
|
||||||
muninVal.OutCurrent /= float64(muninDat.timesUpdated)
|
m.status.InCurrent /= float64(m.timesUpdated)
|
||||||
muninVal.InCurrent /= float64(muninDat.timesUpdated)
|
m.status.BatCurrent /= float64(m.timesUpdated)
|
||||||
muninVal.BatCurrent /= float64(muninDat.timesUpdated)
|
|
||||||
|
|
||||||
muninVal.OutVoltage /= float64(muninDat.timesUpdated)
|
m.status.OutVoltage /= float64(m.timesUpdated)
|
||||||
muninVal.InVoltage /= float64(muninDat.timesUpdated)
|
m.status.InVoltage /= float64(m.timesUpdated)
|
||||||
muninVal.BatVoltage /= float64(muninDat.timesUpdated)
|
m.status.BatVoltage /= float64(m.timesUpdated)
|
||||||
}
|
}
|
||||||
|
|
||||||
func zeroMuninValues(muninDat *muninData) {
|
func zeroMuninValues(m *muninData) {
|
||||||
muninDat.timesUpdated = 0
|
m.timesUpdated = 0
|
||||||
muninVal := muninDat.status
|
m.status.OutCurrent = 0
|
||||||
muninVal.OutCurrent = 0
|
m.status.InCurrent = 0
|
||||||
muninVal.InCurrent = 0
|
m.status.BatCurrent = 0
|
||||||
muninVal.BatCurrent = 0
|
|
||||||
|
|
||||||
muninVal.OutVoltage = 0
|
m.status.OutVoltage = 0
|
||||||
muninVal.InVoltage = 0
|
m.status.InVoltage = 0
|
||||||
muninVal.BatVoltage = 0
|
m.status.BatVoltage = 0
|
||||||
|
|
||||||
muninVal.InFrequency = 0
|
m.status.InFrequency = 0
|
||||||
muninVal.OutFrequency = 0
|
m.status.OutFrequency = 0
|
||||||
|
|
||||||
muninVal.ChargeState = 0
|
m.status.ChargeState = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
type templateInput struct {
|
type templateInput struct {
|
||||||
|
|||||||
29
plugins/munin/munin_test.go
Normal file
29
plugins/munin/munin_test.go
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
package munin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"invertergui/mk2driver"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestServer(_ *testing.T) {
|
||||||
|
|
||||||
|
mockMk2 := mk2driver.NewMk2Mock()
|
||||||
|
muninServer := NewMunin(mockMk2)
|
||||||
|
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(muninServer.ServeMuninHTTP))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
res, err := http.Get(ts.URL)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = io.ReadAll(res.Body)
|
||||||
|
res.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,7 +31,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||||||
package prometheus
|
package prometheus
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,14 @@
|
|||||||
package static
|
package static
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/rakyll/statik/fs"
|
"embed"
|
||||||
|
|
||||||
"log"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// New exports the static part of the webgui that is served via statik
|
//go:embed css js index.html favicon.ico
|
||||||
|
var content embed.FS
|
||||||
|
|
||||||
|
// New exports the static part of the webgui that is served via embed
|
||||||
func New() http.Handler {
|
func New() http.Handler {
|
||||||
statikFs, err := fs.New()
|
return http.FileServer(http.FS(content))
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
return http.FileServer(statikFs)
|
|
||||||
}
|
}
|
||||||
|
|||||||
12
plugins/webui/static/css/bootstrap.min.css
vendored
Normal file
12
plugins/webui/static/css/bootstrap.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 31 KiB After Width: | Height: | Size: 31 KiB |
@@ -98,6 +98,117 @@
|
|||||||
<div class="alert alert-danger" role="alert" v-if="error.has_error">
|
<div class="alert alert-danger" role="alert" v-if="error.has_error">
|
||||||
{{ error.error_message }}
|
{{ error.error_message }}
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
class="alert"
|
||||||
|
v-if="control.message !== ''"
|
||||||
|
v-bind:class="[control.has_error ? 'alert-danger' : 'alert-success']"
|
||||||
|
>
|
||||||
|
{{ control.message }}
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<div class="col">
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<h4 class="card-title">Remote Panel Control</h4>
|
||||||
|
<p class="text-muted mb-2">
|
||||||
|
Mode and current limit are applied together, equivalent to
|
||||||
|
<code>set_remote_panel_state</code>.
|
||||||
|
</p>
|
||||||
|
<p class="mb-1">
|
||||||
|
<strong>Current Mode:</strong>
|
||||||
|
{{ remoteModeLabel(state.remote_panel) }}
|
||||||
|
</p>
|
||||||
|
<p class="mb-1">
|
||||||
|
<strong>Current Limit:</strong>
|
||||||
|
{{ state.remote_panel.current_limit === null || state.remote_panel.current_limit === undefined ? 'Unknown' : state.remote_panel.current_limit + ' A' }}
|
||||||
|
</p>
|
||||||
|
<p class="mb-3">
|
||||||
|
<strong>Standby:</strong>
|
||||||
|
{{ remoteStandbyLabel(state.remote_panel) }}
|
||||||
|
</p>
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-8">
|
||||||
|
<form v-on:submit.prevent="applyRemotePanelState">
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group col-md-6">
|
||||||
|
<label for="modeSelect">Remote Panel Mode</label>
|
||||||
|
<select
|
||||||
|
class="form-control"
|
||||||
|
id="modeSelect"
|
||||||
|
v-model="remote_form.mode"
|
||||||
|
v-bind:disabled="!state.remote_panel.writable || control.busy"
|
||||||
|
>
|
||||||
|
<option value="on">on</option>
|
||||||
|
<option value="off">off</option>
|
||||||
|
<option value="charger_only">charger_only</option>
|
||||||
|
<option value="inverter_only">inverter_only</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="form-group col-md-6">
|
||||||
|
<label for="currentLimitInput">AC Input Current Limit (A)</label>
|
||||||
|
<input
|
||||||
|
id="currentLimitInput"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.1"
|
||||||
|
class="form-control"
|
||||||
|
v-model="remote_form.current_limit"
|
||||||
|
placeholder="leave blank to keep current"
|
||||||
|
v-bind:disabled="!state.remote_panel.writable || control.busy"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="btn btn-primary"
|
||||||
|
v-bind:disabled="!state.remote_panel.writable || control.busy"
|
||||||
|
>
|
||||||
|
Apply Mode + Current Limit
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-4">
|
||||||
|
<form v-on:submit.prevent="applyStandby">
|
||||||
|
<div class="form-group">
|
||||||
|
<div class="form-check mt-4">
|
||||||
|
<input
|
||||||
|
id="standbySwitch"
|
||||||
|
type="checkbox"
|
||||||
|
class="form-check-input"
|
||||||
|
v-model="remote_form.standby"
|
||||||
|
v-bind:disabled="!state.remote_panel.writable || control.busy"
|
||||||
|
/>
|
||||||
|
<label class="form-check-label" for="standbySwitch">
|
||||||
|
Prevent sleep while off
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="btn btn-secondary"
|
||||||
|
v-bind:disabled="!state.remote_panel.writable || control.busy"
|
||||||
|
>
|
||||||
|
Apply Standby
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mt-3 text-muted" v-if="state.remote_panel.last_updated">
|
||||||
|
Last update {{ state.remote_panel.last_updated }}
|
||||||
|
<span v-if="state.remote_panel.last_command">
|
||||||
|
({{ state.remote_panel.last_command }})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 text-danger" v-if="state.remote_panel.last_error">
|
||||||
|
{{ state.remote_panel.last_error }}
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 text-warning" v-if="!state.remote_panel.writable">
|
||||||
|
Remote control is unavailable for this data source.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col">
|
<div class="col">
|
||||||
<hr />
|
<hr />
|
||||||
280
plugins/webui/static/js/controller.js
Normal file
280
plugins/webui/static/js/controller.js
Normal file
@@ -0,0 +1,280 @@
|
|||||||
|
var app;
|
||||||
|
const timeoutMax = 30000;
|
||||||
|
const timeoutMin = 1000;
|
||||||
|
var timeout = timeoutMin;
|
||||||
|
|
||||||
|
function defaultRemotePanelState() {
|
||||||
|
return {
|
||||||
|
writable: false,
|
||||||
|
mode: "unknown",
|
||||||
|
current_limit: null,
|
||||||
|
standby: null,
|
||||||
|
last_command: "",
|
||||||
|
last_error: "",
|
||||||
|
last_updated: ""
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultState() {
|
||||||
|
return {
|
||||||
|
output_current: null,
|
||||||
|
output_voltage: 0,
|
||||||
|
output_frequency: 0,
|
||||||
|
output_power: 0,
|
||||||
|
input_current: 0,
|
||||||
|
input_voltage: 0,
|
||||||
|
input_frequency: 0,
|
||||||
|
input_power: 0,
|
||||||
|
battery_current: 0,
|
||||||
|
battery_voltage: 0,
|
||||||
|
battery_charge: 0,
|
||||||
|
battery_power: 0,
|
||||||
|
led_map: {
|
||||||
|
led_mains: "dot-off",
|
||||||
|
led_absorb: "dot-off",
|
||||||
|
led_bulk: "dot-off",
|
||||||
|
led_float: "dot-off",
|
||||||
|
led_inverter: "dot-off",
|
||||||
|
led_overload: "dot-off",
|
||||||
|
led_bat_low: "dot-off",
|
||||||
|
led_over_temp: "dot-off"
|
||||||
|
},
|
||||||
|
remote_panel: defaultRemotePanelState()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadContent() {
|
||||||
|
app = new Vue({
|
||||||
|
el: "#app",
|
||||||
|
data: {
|
||||||
|
error: {
|
||||||
|
has_error: false,
|
||||||
|
error_message: ""
|
||||||
|
},
|
||||||
|
control: {
|
||||||
|
busy: false,
|
||||||
|
has_error: false,
|
||||||
|
message: ""
|
||||||
|
},
|
||||||
|
remote_form: {
|
||||||
|
mode: "on",
|
||||||
|
current_limit: "",
|
||||||
|
standby: false
|
||||||
|
},
|
||||||
|
state: defaultState()
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
syncRemoteFormFromState: function(remoteState) {
|
||||||
|
if (!remoteState) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (remoteState.mode && remoteState.mode !== "unknown") {
|
||||||
|
this.remote_form.mode = remoteState.mode;
|
||||||
|
}
|
||||||
|
if (remoteState.current_limit === null || remoteState.current_limit === undefined) {
|
||||||
|
this.remote_form.current_limit = "";
|
||||||
|
} else {
|
||||||
|
this.remote_form.current_limit = String(remoteState.current_limit);
|
||||||
|
}
|
||||||
|
if (remoteState.standby === null || remoteState.standby === undefined) {
|
||||||
|
this.remote_form.standby = false;
|
||||||
|
} else {
|
||||||
|
this.remote_form.standby = !!remoteState.standby;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
remoteModeLabel: function(remoteState) {
|
||||||
|
var mode = (remoteState && remoteState.mode) || "unknown";
|
||||||
|
if (mode === "charger_only") {
|
||||||
|
return "Charger Only";
|
||||||
|
}
|
||||||
|
if (mode === "inverter_only") {
|
||||||
|
return "Inverter Only";
|
||||||
|
}
|
||||||
|
if (mode === "on") {
|
||||||
|
return "On";
|
||||||
|
}
|
||||||
|
if (mode === "off") {
|
||||||
|
return "Off";
|
||||||
|
}
|
||||||
|
return "Unknown";
|
||||||
|
},
|
||||||
|
remoteStandbyLabel: function(remoteState) {
|
||||||
|
if (!remoteState || remoteState.standby === null || remoteState.standby === undefined) {
|
||||||
|
return "Unknown";
|
||||||
|
}
|
||||||
|
return remoteState.standby ? "Enabled" : "Disabled";
|
||||||
|
},
|
||||||
|
refreshRemoteState: function() {
|
||||||
|
var self = this;
|
||||||
|
fetch(getAPIURI("api/remote-panel/state"))
|
||||||
|
.then(function(resp) {
|
||||||
|
if (!resp.ok) {
|
||||||
|
throw new Error("Could not load remote panel state.");
|
||||||
|
}
|
||||||
|
return resp.json();
|
||||||
|
})
|
||||||
|
.then(function(payload) {
|
||||||
|
self.state.remote_panel = payload;
|
||||||
|
self.syncRemoteFormFromState(payload);
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
self.control.has_error = true;
|
||||||
|
self.control.message = err.message;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
applyRemotePanelState: function() {
|
||||||
|
var self = this;
|
||||||
|
if (!self.state.remote_panel.writable) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var body = {
|
||||||
|
mode: self.remote_form.mode
|
||||||
|
};
|
||||||
|
if (self.remote_form.current_limit !== "") {
|
||||||
|
var parsed = parseFloat(self.remote_form.current_limit);
|
||||||
|
if (isNaN(parsed)) {
|
||||||
|
self.control.has_error = true;
|
||||||
|
self.control.message = "Current limit must be numeric.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
body.current_limit = parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.control.busy = true;
|
||||||
|
self.control.has_error = false;
|
||||||
|
self.control.message = "";
|
||||||
|
fetch(getAPIURI("api/remote-panel/state"), {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
})
|
||||||
|
.then(function(resp) {
|
||||||
|
if (!resp.ok) {
|
||||||
|
return resp.text().then(function(text) {
|
||||||
|
throw new Error(text || "Failed to set remote panel mode/current limit.");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return resp.json();
|
||||||
|
})
|
||||||
|
.then(function(payload) {
|
||||||
|
self.state.remote_panel = payload;
|
||||||
|
self.syncRemoteFormFromState(payload);
|
||||||
|
self.control.has_error = false;
|
||||||
|
self.control.message = "Remote panel state updated.";
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
self.control.has_error = true;
|
||||||
|
self.control.message = err.message;
|
||||||
|
})
|
||||||
|
.finally(function() {
|
||||||
|
self.control.busy = false;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
applyStandby: function() {
|
||||||
|
var self = this;
|
||||||
|
if (!self.state.remote_panel.writable) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.control.busy = true;
|
||||||
|
self.control.has_error = false;
|
||||||
|
self.control.message = "";
|
||||||
|
fetch(getAPIURI("api/remote-panel/standby"), {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
standby: !!self.remote_form.standby
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.then(function(resp) {
|
||||||
|
if (!resp.ok) {
|
||||||
|
return resp.text().then(function(text) {
|
||||||
|
throw new Error(text || "Failed to set standby mode.");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return resp.json();
|
||||||
|
})
|
||||||
|
.then(function(payload) {
|
||||||
|
self.state.remote_panel = payload;
|
||||||
|
self.syncRemoteFormFromState(payload);
|
||||||
|
self.control.has_error = false;
|
||||||
|
self.control.message = "Standby mode updated.";
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
self.control.has_error = true;
|
||||||
|
self.control.message = err.message;
|
||||||
|
})
|
||||||
|
.finally(function() {
|
||||||
|
self.control.busy = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.refreshRemoteState();
|
||||||
|
connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
if (window["WebSocket"]) {
|
||||||
|
var conn = new WebSocket(getURI());
|
||||||
|
conn.onclose = function(evt) {
|
||||||
|
app.error.has_error = true;
|
||||||
|
app.error.error_message =
|
||||||
|
"Server not reachable. Trying to reconnect in " +
|
||||||
|
timeout / 1000 +
|
||||||
|
" second(s).";
|
||||||
|
|
||||||
|
console.log(app.error.error_message, evt.reason);
|
||||||
|
setTimeout(function() {
|
||||||
|
connect();
|
||||||
|
}, timeout);
|
||||||
|
timeout = timeout * 2;
|
||||||
|
if (timeout > timeoutMax) {
|
||||||
|
timeout = timeoutMax;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
conn.onopen = function() {
|
||||||
|
timeout = timeoutMin;
|
||||||
|
app.error.has_error = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
conn.onmessage = function(evt) {
|
||||||
|
var update = JSON.parse(evt.data);
|
||||||
|
app.state = update;
|
||||||
|
if (!app.control.busy) {
|
||||||
|
app.syncRemoteFormFromState(update.remote_panel);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
app.error.has_error = true;
|
||||||
|
app.error.error_message = "Our browser does not support WebSockets.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getURI() {
|
||||||
|
var loc = window.location,
|
||||||
|
new_uri;
|
||||||
|
if (loc.protocol === "https:") {
|
||||||
|
new_uri = "wss:";
|
||||||
|
} else {
|
||||||
|
new_uri = "ws:";
|
||||||
|
}
|
||||||
|
new_uri += "//" + loc.host;
|
||||||
|
new_uri += loc.pathname + "ws";
|
||||||
|
return new_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAPIURI(path) {
|
||||||
|
var base = window.location.pathname;
|
||||||
|
if (base.slice(-1) !== "/") {
|
||||||
|
base += "/";
|
||||||
|
}
|
||||||
|
return base + path.replace(/^\/+/, "");
|
||||||
|
}
|
||||||
6
plugins/webui/static/js/vue.js
Normal file
6
plugins/webui/static/js/vue.js
Normal file
File diff suppressed because one or more lines are too long
12
plugins/webui/static/root/css/bootstrap.min.css
vendored
12
plugins/webui/static/root/css/bootstrap.min.css
vendored
File diff suppressed because one or more lines are too long
@@ -1,88 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
|
|
||||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'">
|
|
||||||
<title>Page not found · GitHub Pages</title>
|
|
||||||
<style type="text/css" media="screen">
|
|
||||||
body {
|
|
||||||
background-color: #f1f1f1;
|
|
||||||
margin: 0;
|
|
||||||
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
|
|
||||||
}
|
|
||||||
|
|
||||||
.container { margin: 50px auto 40px auto; width: 600px; text-align: center; }
|
|
||||||
|
|
||||||
a { color: #4183c4; text-decoration: none; }
|
|
||||||
a:hover { text-decoration: underline; }
|
|
||||||
|
|
||||||
h1 { width: 800px; position:relative; left: -100px; letter-spacing: -1px; line-height: 60px; font-size: 60px; font-weight: 100; margin: 0px 0 50px 0; text-shadow: 0 1px 0 #fff; }
|
|
||||||
p { color: rgba(0, 0, 0, 0.5); margin: 20px 0; line-height: 1.6; }
|
|
||||||
|
|
||||||
ul { list-style: none; margin: 25px 0; padding: 0; }
|
|
||||||
li { display: table-cell; font-weight: bold; width: 1%; }
|
|
||||||
|
|
||||||
.logo { display: inline-block; margin-top: 35px; }
|
|
||||||
.logo-img-2x { display: none; }
|
|
||||||
@media
|
|
||||||
only screen and (-webkit-min-device-pixel-ratio: 2),
|
|
||||||
only screen and ( min--moz-device-pixel-ratio: 2),
|
|
||||||
only screen and ( -o-min-device-pixel-ratio: 2/1),
|
|
||||||
only screen and ( min-device-pixel-ratio: 2),
|
|
||||||
only screen and ( min-resolution: 192dpi),
|
|
||||||
only screen and ( min-resolution: 2dppx) {
|
|
||||||
.logo-img-1x { display: none; }
|
|
||||||
.logo-img-2x { display: inline-block; }
|
|
||||||
}
|
|
||||||
|
|
||||||
#suggestions {
|
|
||||||
margin-top: 35px;
|
|
||||||
color: #ccc;
|
|
||||||
}
|
|
||||||
#suggestions a {
|
|
||||||
color: #666666;
|
|
||||||
font-weight: 200;
|
|
||||||
font-size: 14px;
|
|
||||||
margin: 0 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
|
|
||||||
<div class="container">
|
|
||||||
|
|
||||||
<h1>404</h1>
|
|
||||||
<p><strong>File not found</strong></p>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
The site configured at this address does not
|
|
||||||
contain the requested file.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
If this is your site, make sure that the filename case matches the URL.<br>
|
|
||||||
For root URLs (like <code>http://example.com/</code>) you must provide an
|
|
||||||
<code>index.html</code> file.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
<a href="https://help.github.com/pages/">Read the full documentation</a>
|
|
||||||
for more information about using <strong>GitHub Pages</strong>.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div id="suggestions">
|
|
||||||
<a href="https://githubstatus.com">GitHub Status</a> —
|
|
||||||
<a href="https://twitter.com/githubstatus">@githubstatus</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<a href="/" class="logo logo-img-1x">
|
|
||||||
<img width="32" height="32" title="" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpFMTZCRDY3REIzRjAxMUUyQUQzREIxQzRENUFFNUM5NiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpFMTZCRDY3RUIzRjAxMUUyQUQzREIxQzRENUFFNUM5NiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkUxNkJENjdCQjNGMDExRTJBRDNEQjFDNEQ1QUU1Qzk2IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkUxNkJENjdDQjNGMDExRTJBRDNEQjFDNEQ1QUU1Qzk2Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+SM9MCAAAA+5JREFUeNrEV11Ik1EY3s4+ddOp29Q5b0opCgKFsoKoi5Kg6CIhuwi6zLJLoYLopq4qsKKgi4i6CYIoU/q5iDAKs6syoS76IRWtyJ+p7cdt7sf1PGOD+e0c3dygAx/67ZzzPM95/877GYdHRg3ZjMXFxepQKNS6sLCwJxqNNuFpiMfjVs4ZjUa/pmmjeD6VlJS8NpvNT4QQ7mxwjSsJiEQim/1+/9lgMHgIr5ohuxG1WCw9Vqv1clFR0dCqBODElV6v90ogEDjGdYbVjXhpaendioqK07CIR7ZAqE49PT09BPL2PMgTByQGsYiZlQD4uMXtdr+JxWINhgINYhGT2MsKgMrm2dnZXgRXhaHAg5jEJodUAHxux4LudHJE9RdEdA+i3Juz7bGHe4mhE9FNrgwBCLirMFV9Okh5eflFh8PR5nK5nDabrR2BNJlKO0T35+Li4n4+/J+/JQCxhmu5h3uJoXNHPbmWZAHMshWB8l5/ipqammaAf0zPDDx1ONV3vurdidqwAQL+pEc8sLcAe1CCvQ3YHxIW8Pl85xSWNC1hADDIv0rIE/o4J0k3kww4xSlwIhcq3EFFOm7KN/hUGOQkt0CFa5WpNJlMvxBEz/IVQAxg/ZRZl9wiHA63yDYieM7DnLP5CiAGsC7I5sgtYKJGWe2A8seFqgFJrJjEPY1Cn3pJ8/9W1e5VWsFDTEmFrBcoDhZJEQkXuhICMyKpjhahqN21hRYATKfUOlDmkygrR4o4C0VOLGJKrOITKB4jijzdXygBKixyC5TDQdnk/Pz8qRw6oOWGlsTKGOQW6OH6FBWsyePxdOXLTgxiyebILZCjz+GLgMIKnXNzc49YMlcRdHXcSwxFVgTInQhC9G33UhNoJLuqq6t345p9y3eUy8OTk5PjAHuI9uo4b07FBaOhsu0A4Unc+T1TU1Nj3KsSSE5yJ65jqF2DDd8QqWYmAZrIM2VlZTdnZmb6AbpdV9V6ec9znf5Q7HjYumdRE0JOp3MjitO4SFa+cZz8Umqe3TCbSLvdfkR/kWDdNQl5InuTcysOcpFT35ZrbBxx4p3JAHlZVVW1D/634VRt+FvLBgK/v5LV9WS+10xMTEwtRw7XvqOL+e2Q8V3AYIOIAXQ26/heWVnZCVfcyKHg2CBgTpmPmjYM8l24GyaUHyaIh7XwfR9ErE8qHoDfn2LTNAVC0HX6MFcBIP8Bi+6F6cdW/DICkANRfx99fEYFQ7Nph5i/uQiA214gno7K+guhaiKg9gC62+M8eR7XsBsYJ4ilam60Fb7r7uAj8wFyuwM1oIOWgfmDy6RXEEQzJMPe23DXrVS7rtyD3Df8z/FPgAEAzWU5Ku59ZAUAAAAASUVORK5CYII=">
|
|
||||||
</a>
|
|
||||||
|
|
||||||
<a href="/" class="logo logo-img-2x">
|
|
||||||
<img width="32" height="32" title="" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpEQUM1QkUxRUI0MUMxMUUyQUQzREIxQzRENUFFNUM5NiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpEQUM1QkUxRkI0MUMxMUUyQUQzREIxQzRENUFFNUM5NiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkUxNkJENjdGQjNGMDExRTJBRDNEQjFDNEQ1QUU1Qzk2IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkUxNkJENjgwQjNGMDExRTJBRDNEQjFDNEQ1QUU1Qzk2Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+hfPRaQAAB6lJREFUeNrsW2mME2UYbodtt+2222u35QheoCCYGBQligIJgkZJNPzgigoaTEj8AdFEMfADfyABkgWiiWcieK4S+QOiHAYUj2hMNKgYlEujpNttu9vttbvdw+chU1K6M535pt3ubHCSyezR+b73eb73+t7vrfXsufOW4bz6+vom9/b23ovnNNw34b5xYGAgODg46Mbt4mesVmsWd1qSpHhdXd2fuP/Afcput5/A88xwymcdBgLqenp6FuRyuWV4zu/v759QyWBjxoz5t76+/gun09mK5xFyakoCAPSaTCazNpvNPoYVbh6O1YKGRF0u13sNDQ27QMzfpiAAKj0lnU6/gBVfAZW2WWpwwVzy0IgP3G73FpjI6REhAGA9qVRqA1b9mVoBVyIC2tDi8Xg24+dUzQiAbS/s7Ox8G2o/3mKCC+Zw0efzPQEfcVjYrARX3dbV1bUtHo8fMgt42f+Mp0yUTVQbdWsAHVsikdiHkHaPxcQXQufXgUBgMRxme9U0AAxfH4vFvjM7eF6UkbJS5qoQwEQGA57Ac5JllFyUVZZ5ckUEgMVxsK2jlSYzI+QXJsiyjzNEAJyJAzb/KQa41jJKL8pODMQiTEAymXw5n8/P0IjD3bh7Rgog59aanxiIRTVvV/oj0tnHca/WMrVwODwB3raTGxzkBg/gnZVapFV62Wy2n5AO70HM/5wbJ0QnXyQSaVPDIuNZzY0V3ntHMwxiwHA0Gj2Np7ecIBDgaDAYXKCQJM1DhrgJ3nhulcPbl8j4NmHe46X/g60fwbz3aewjkqFQaAqebWU1AOqyQwt8Id6qEHMc97zu7u7FGGsn7HAiVuosVw7P35C1nccdgSCxop1dHeZswmfHMnxBo6ZTk+jN8dl/vF7vWofDsa+MLN9oEUBMxOb3+1eoEsBVw6Zmua49r8YmhAKDiEPcMwBsxMiqQ+ixzPFxZyqRpXARG/YOr1ObFJ0gUskXBbamcR1OKmMUvDxHRAu8/LmY3jFLMUpFqz9HxG65smYJdyKyECOxDiEAe/p1gjF2oonivZAsxVgl2daa4EQWCW6J55qFAFFZiJWYLxNQy2qOSUzGRsyXCUDIeliwAHEO4WSlWQBRFoZakXcKmCXmyXAKs0Ve9vl8q42WoIYpJU4hV3hKcNs8m9gl7p/xQ73eF5kB4j5mNrWmTJRNwAzqiV1CxjVTZCIkEq+Z1bZFZSN2CenmVAFVy4Plz8xKAGWjjAKFk6lCBMDR/MJjLLMSQNm43xAiQKTaA+9/wewhDjL+JVI1kkTSSOTcKbMTwPqESAot6dn6Fr1gHwVJju6IRuyiByPuUUBAg5DGkAgBmxlvdgIEK9gDkohdY/BJo4CAG0R8miRSsGABkgVQs4KXu098IgUXSSRsFAoKZiVAVDY2WUiiPTjYRi41KwGisrGsLtlsth8Fiwnz2fBkQvWfRtlE3iF2yW63/yCacXZ1dW02GwGyTFaRd4idJnCKHRaCxYRHoG5LTKT6SyiToP1fJHbmAYPYRR0UnZQtMnA6s0zg+GZBlt0Gdo7EPHgpE3Q6nZ8YyLhc8Xj8MJh/aKTAY+5FPAKHLE7RdwuYJZmNwzyCMkBCYyKROJBMJl9B/PXXCjjmCmDOVzH3fiPpObEWGqoKe4EBl8v1hlqsdLvd23mkxHM9pc9kMpmno9HoeTii7ewbHEZPPx1ztLS1tV3AnGuMjiNjvbQFuHw6zDo5By7dTPAQNBgMLrRarTkSls1mnwT7uwp9virx9QzbW/HuV/j5d/b+6jniKlllP8lkeONJDk+dq9GsQTnC4fB1heO0K47Hwe7WdDr9nAKgXwOBwHI+C45Htj1d6sd429TUNEcmUdc+PRaLHcvn87dXW4ugzdsaGxufL94NFv9zi1J7GVbhlvb2dnaJ3SVrxfc+n2+NTsZ7/H7/Mr3g5XdSIHyJSH1PZ+7fToyl2+ErqilgZ4NaLYB9goVGaHjR93Hv1ZrU4XDsFT20kH3PObzbWk0CgG1jacVIUnAQb9F+VexyLMzkpcLv0IJV7AHQIOCAUYHx7v5qgScmYHtTqSAyZLEJTK22Bie4iq3xsqpm4SAf9Hq9a2DnJ4uLK3SEULcdRvp3i3zHySqpficxEdsQc1NrlYXXvR+O7qASSezXB+h1SuUomgg9LL8BUoV4749EIolKh+EiqWmqVEZlDgHks2pxHw7xTqUQw9J5NcAXOK10AGIoZ6Zli6JY6Z1Q461KoZ4NiKLHarW+KDsxlDUPHZ5zPQZqUVDPJsTqb5n9malbpAh8C2XXDLl62+WZIDFRUlNVOiwencnNU3aQEkL+cDMSoLvZo2fQB7AJssNAuFuvorlDVVkkg2I87+jo2K2QAVphDrfyViK5VqtO34OkaxXCp+7drdDBCAdubm6eidX+2WwqT5komwh4YQLk+H4aE93h8Xg2gvHekQZOGSgLZTLyDTLJ4Lx9/KZWKBSainT4Iy3FqQBfnUZR42PKQFksBr9QKVXCPusD3OiA/RkQ5kP8qV/Jl1WywAp/6+dcmPM2zL1UrUahe4JqfnWWKXIul3uUbfP8njAFLW1OFr3gdFtZ72cNH+PtQT7/brW+NXqJAHh0y9V8/U/A1U7AfwIMAD7mS3pCbuWJAAAAAElFTkSuQmCC">
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
var app;
|
|
||||||
const timeoutMax = 30000;
|
|
||||||
const timeoutMin = 1000;
|
|
||||||
var timeout = timeoutMin;
|
|
||||||
|
|
||||||
function loadContent() {
|
|
||||||
app = new Vue({
|
|
||||||
el: "#app",
|
|
||||||
data: {
|
|
||||||
error: {
|
|
||||||
has_error: false,
|
|
||||||
error_message: ""
|
|
||||||
},
|
|
||||||
state: {
|
|
||||||
output_current: null,
|
|
||||||
output_voltage: 0,
|
|
||||||
output_frequency: 0,
|
|
||||||
output_power: 0,
|
|
||||||
input_current: 0,
|
|
||||||
input_voltage: 0,
|
|
||||||
input_frequency: 0,
|
|
||||||
input_power: 0,
|
|
||||||
battery_current: 0,
|
|
||||||
battery_voltage: 0,
|
|
||||||
battery_charge: 0,
|
|
||||||
battery_power: 0,
|
|
||||||
led_map: [
|
|
||||||
{ led_mains: "dot-off" },
|
|
||||||
{ led_absorb: "dot-off" },
|
|
||||||
{ led_bulk: "dot-off" },
|
|
||||||
{ led_float: "dot-off" },
|
|
||||||
{ led_inverter: "dot-off" },
|
|
||||||
{ led_overload: "dot-off" },
|
|
||||||
{ led_bat_low: "dot-off" },
|
|
||||||
{ led_over_temp: "dot-off" }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
connect();
|
|
||||||
}
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
if (window["WebSocket"]) {
|
|
||||||
var conn = new WebSocket(getURI());
|
|
||||||
conn.onclose = function(evt) {
|
|
||||||
app.error.has_error = true;
|
|
||||||
app.error.error_message =
|
|
||||||
"Server not reachable. Trying to reconnect in " +
|
|
||||||
timeout / 1000 +
|
|
||||||
" second(s).";
|
|
||||||
|
|
||||||
console.log(app.error.error_message, evt.reason);
|
|
||||||
setTimeout(function() {
|
|
||||||
connect();
|
|
||||||
}, timeout);
|
|
||||||
timeout = timeout * 2;
|
|
||||||
if (timeout > timeoutMax) {
|
|
||||||
timeout = timeoutMax;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
conn.onopen = function(evt) {
|
|
||||||
timeout = timeoutMin;
|
|
||||||
app.error.has_error = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
conn.onmessage = function(evt) {
|
|
||||||
var update = JSON.parse(evt.data);
|
|
||||||
app.state = update;
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
app.error.has_error = true;
|
|
||||||
app.error.error_message = "Our browser does not support WebSockets.";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getURI() {
|
|
||||||
var loc = window.location,
|
|
||||||
new_uri;
|
|
||||||
if (loc.protocol === "https:") {
|
|
||||||
new_uri = "wss:";
|
|
||||||
} else {
|
|
||||||
new_uri = "ws:";
|
|
||||||
}
|
|
||||||
new_uri += "//" + loc.host;
|
|
||||||
new_uri += loc.pathname + "ws";
|
|
||||||
return new_uri;
|
|
||||||
}
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -31,13 +31,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||||||
package webui
|
package webui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
"github.com/diebietse/invertergui/websocket"
|
"invertergui/websocket"
|
||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -51,25 +53,53 @@ const (
|
|||||||
BlinkGreen = "blink-green"
|
BlinkGreen = "blink-green"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
modeChargerOnly = "charger_only"
|
||||||
|
modeInverterOnly = "inverter_only"
|
||||||
|
modeOn = "on"
|
||||||
|
modeOff = "off"
|
||||||
|
modeUnknown = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
type WebGui struct {
|
type WebGui struct {
|
||||||
mk2driver.Mk2
|
mk2driver.Mk2
|
||||||
|
writer mk2driver.SettingsWriter
|
||||||
stopChan chan struct{}
|
stopChan chan struct{}
|
||||||
|
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
hub *websocket.Hub
|
hub *websocket.Hub
|
||||||
|
|
||||||
|
stateMu sync.RWMutex
|
||||||
|
latest *templateInput
|
||||||
|
remote remotePanelState
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWebGui(source mk2driver.Mk2) *WebGui {
|
func NewWebGui(source mk2driver.Mk2, writer mk2driver.SettingsWriter) *WebGui {
|
||||||
w := &WebGui{
|
w := &WebGui{
|
||||||
stopChan: make(chan struct{}),
|
stopChan: make(chan struct{}),
|
||||||
Mk2: source,
|
Mk2: source,
|
||||||
|
writer: writer,
|
||||||
hub: websocket.NewHub(),
|
hub: websocket.NewHub(),
|
||||||
|
remote: remotePanelState{
|
||||||
|
Writable: writer != nil,
|
||||||
|
Mode: modeUnknown,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
w.wg.Add(1)
|
w.wg.Add(1)
|
||||||
go w.dataPoll()
|
go w.dataPoll()
|
||||||
return w
|
return w
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type remotePanelState struct {
|
||||||
|
Writable bool `json:"writable"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
CurrentLimit *float64 `json:"current_limit,omitempty"`
|
||||||
|
Standby *bool `json:"standby,omitempty"`
|
||||||
|
LastCommand string `json:"last_command,omitempty"`
|
||||||
|
LastError string `json:"last_error,omitempty"`
|
||||||
|
LastUpdated string `json:"last_updated,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
type templateInput struct {
|
type templateInput struct {
|
||||||
Error []error `json:"errors"`
|
Error []error `json:"errors"`
|
||||||
|
|
||||||
@@ -94,12 +124,125 @@ type templateInput struct {
|
|||||||
OutFreq string `json:"output_frequency"`
|
OutFreq string `json:"output_frequency"`
|
||||||
|
|
||||||
LedMap map[string]string `json:"led_map"`
|
LedMap map[string]string `json:"led_map"`
|
||||||
|
|
||||||
|
RemotePanel remotePanelState `json:"remote_panel"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type setRemotePanelStateRequest struct {
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
CurrentLimit *float64 `json:"current_limit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type setRemotePanelStandbyRequest struct {
|
||||||
|
Standby bool `json:"standby"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WebGui) ServeHub(rw http.ResponseWriter, r *http.Request) {
|
func (w *WebGui) ServeHub(rw http.ResponseWriter, r *http.Request) {
|
||||||
w.hub.ServeHTTP(rw, r)
|
w.hub.ServeHTTP(rw, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *WebGui) ServeRemotePanelState(rw http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method {
|
||||||
|
case http.MethodGet:
|
||||||
|
writeJSON(rw, http.StatusOK, w.getRemotePanelState())
|
||||||
|
case http.MethodPost:
|
||||||
|
w.handleSetRemotePanelState(rw, r)
|
||||||
|
default:
|
||||||
|
http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WebGui) ServeRemotePanelStandby(rw http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method {
|
||||||
|
case http.MethodGet:
|
||||||
|
writeJSON(rw, http.StatusOK, w.getRemotePanelState())
|
||||||
|
case http.MethodPost:
|
||||||
|
w.handleSetRemotePanelStandby(rw, r)
|
||||||
|
default:
|
||||||
|
http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WebGui) handleSetRemotePanelState(rw http.ResponseWriter, r *http.Request) {
|
||||||
|
if w.writer == nil {
|
||||||
|
http.Error(rw, "remote control is not supported by this data source", http.StatusNotImplemented)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
req := setRemotePanelStateRequest{}
|
||||||
|
if err := decodeJSONBody(r, &req); err != nil {
|
||||||
|
http.Error(rw, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switchState, normalizedMode, err := parsePanelMode(req.Mode)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(rw, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := w.writer.SetPanelState(switchState, req.CurrentLimit); err != nil {
|
||||||
|
w.updateRemotePanelState(func(state *remotePanelState) {
|
||||||
|
state.LastCommand = "set_remote_panel_state"
|
||||||
|
state.LastError = err.Error()
|
||||||
|
})
|
||||||
|
http.Error(rw, err.Error(), http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.updateRemotePanelState(func(state *remotePanelState) {
|
||||||
|
state.Mode = normalizedMode
|
||||||
|
state.CurrentLimit = copyFloat64Ptr(req.CurrentLimit)
|
||||||
|
state.LastCommand = "set_remote_panel_state"
|
||||||
|
state.LastError = ""
|
||||||
|
})
|
||||||
|
writeJSON(rw, http.StatusOK, w.getRemotePanelState())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WebGui) handleSetRemotePanelStandby(rw http.ResponseWriter, r *http.Request) {
|
||||||
|
if w.writer == nil {
|
||||||
|
http.Error(rw, "remote control is not supported by this data source", http.StatusNotImplemented)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
req := setRemotePanelStandbyRequest{}
|
||||||
|
if err := decodeJSONBody(r, &req); err != nil {
|
||||||
|
http.Error(rw, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := w.writer.SetStandby(req.Standby); err != nil {
|
||||||
|
w.updateRemotePanelState(func(state *remotePanelState) {
|
||||||
|
state.LastCommand = "set_remote_panel_standby"
|
||||||
|
state.LastError = err.Error()
|
||||||
|
})
|
||||||
|
http.Error(rw, err.Error(), http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.updateRemotePanelState(func(state *remotePanelState) {
|
||||||
|
state.Standby = copyBoolPtr(&req.Standby)
|
||||||
|
state.LastCommand = "set_remote_panel_standby"
|
||||||
|
state.LastError = ""
|
||||||
|
})
|
||||||
|
writeJSON(rw, http.StatusOK, w.getRemotePanelState())
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePanelMode(raw string) (mk2driver.PanelSwitchState, string, error) {
|
||||||
|
switch strings.TrimSpace(strings.ToLower(raw)) {
|
||||||
|
case modeChargerOnly:
|
||||||
|
return mk2driver.PanelSwitchChargerOnly, modeChargerOnly, nil
|
||||||
|
case modeInverterOnly:
|
||||||
|
return mk2driver.PanelSwitchInverterOnly, modeInverterOnly, nil
|
||||||
|
case modeOn:
|
||||||
|
return mk2driver.PanelSwitchOn, modeOn, nil
|
||||||
|
case modeOff:
|
||||||
|
return mk2driver.PanelSwitchOff, modeOff, nil
|
||||||
|
default:
|
||||||
|
return 0, "", fmt.Errorf("unsupported panel mode %q", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func ledName(led mk2driver.Led) string {
|
func ledName(led mk2driver.Led) string {
|
||||||
name, ok := mk2driver.LedNames[led]
|
name, ok := mk2driver.LedNames[led]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -162,15 +305,17 @@ func (w *WebGui) Stop() {
|
|||||||
w.wg.Wait()
|
w.wg.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
// dataPoll waits for data from the w.poller channel. It will send its currently stored status
|
|
||||||
// to respChan if anything reads from it.
|
|
||||||
func (w *WebGui) dataPoll() {
|
func (w *WebGui) dataPoll() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case s := <-w.C():
|
case s := <-w.C():
|
||||||
if s.Valid {
|
if s.Valid {
|
||||||
err := w.hub.Broadcast(buildTemplateInput(s))
|
payload := buildTemplateInput(s)
|
||||||
if err != nil {
|
w.stateMu.Lock()
|
||||||
|
payload.RemotePanel = w.remote
|
||||||
|
w.latest = payload
|
||||||
|
w.stateMu.Unlock()
|
||||||
|
if err := w.hub.Broadcast(payload); err != nil {
|
||||||
log.Errorf("Could not send update to clients: %v", err)
|
log.Errorf("Could not send update to clients: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -180,3 +325,93 @@ func (w *WebGui) dataPoll() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *WebGui) getRemotePanelState() remotePanelState {
|
||||||
|
w.stateMu.RLock()
|
||||||
|
defer w.stateMu.RUnlock()
|
||||||
|
return copyRemotePanelState(w.remote)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WebGui) updateRemotePanelState(update func(state *remotePanelState)) {
|
||||||
|
w.stateMu.Lock()
|
||||||
|
update(&w.remote)
|
||||||
|
w.remote.LastUpdated = time.Now().UTC().Format(time.RFC3339)
|
||||||
|
snapshot := w.snapshotLocked()
|
||||||
|
w.stateMu.Unlock()
|
||||||
|
|
||||||
|
if snapshot != nil {
|
||||||
|
if err := w.hub.Broadcast(snapshot); err != nil {
|
||||||
|
log.Errorf("Could not send control update to clients: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WebGui) snapshotLocked() *templateInput {
|
||||||
|
if w.latest == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot := cloneTemplateInput(w.latest)
|
||||||
|
snapshot.RemotePanel = copyRemotePanelState(w.remote)
|
||||||
|
return snapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneTemplateInput(in *templateInput) *templateInput {
|
||||||
|
if in == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := *in
|
||||||
|
|
||||||
|
if in.Error != nil {
|
||||||
|
out.Error = append([]error(nil), in.Error...)
|
||||||
|
}
|
||||||
|
if in.LedMap != nil {
|
||||||
|
out.LedMap = make(map[string]string, len(in.LedMap))
|
||||||
|
for k, v := range in.LedMap {
|
||||||
|
out.LedMap[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.RemotePanel = copyRemotePanelState(in.RemotePanel)
|
||||||
|
return &out
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyRemotePanelState(in remotePanelState) remotePanelState {
|
||||||
|
in.CurrentLimit = copyFloat64Ptr(in.CurrentLimit)
|
||||||
|
in.Standby = copyBoolPtr(in.Standby)
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyFloat64Ptr(in *float64) *float64 {
|
||||||
|
if in == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
value := *in
|
||||||
|
return &value
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyBoolPtr(in *bool) *bool {
|
||||||
|
if in == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
value := *in
|
||||||
|
return &value
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeJSONBody(r *http.Request, destination any) error {
|
||||||
|
defer r.Body.Close()
|
||||||
|
decoder := json.NewDecoder(r.Body)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(destination); err != nil {
|
||||||
|
return fmt.Errorf("invalid request body: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(rw http.ResponseWriter, statusCode int, payload any) {
|
||||||
|
rw.Header().Set("Content-Type", "application/json")
|
||||||
|
rw.WriteHeader(statusCode)
|
||||||
|
if err := json.NewEncoder(rw).Encode(payload); err != nil {
|
||||||
|
log.Errorf("Could not encode webui API response: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/diebietse/invertergui/mk2driver"
|
"invertergui/mk2driver"
|
||||||
)
|
)
|
||||||
|
|
||||||
type templateTest struct {
|
type templateTest struct {
|
||||||
@@ -91,3 +91,53 @@ func TestTemplateInput(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParsePanelMode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
want mk2driver.PanelSwitchState
|
||||||
|
wantRaw string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "on",
|
||||||
|
input: "on",
|
||||||
|
want: mk2driver.PanelSwitchOn,
|
||||||
|
wantRaw: "on",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "charger_only",
|
||||||
|
input: "charger_only",
|
||||||
|
want: mk2driver.PanelSwitchChargerOnly,
|
||||||
|
wantRaw: "charger_only",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid",
|
||||||
|
input: "banana",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, gotRaw, err := parsePanelMode(tt.input)
|
||||||
|
if tt.wantErr {
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error, got nil")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Fatalf("got switch %d, want %d", got, tt.want)
|
||||||
|
}
|
||||||
|
if gotRaw != tt.wantRaw {
|
||||||
|
t.Fatalf("got mode %q, want %q", gotRaw, tt.wantRaw)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
22
vendor/github.com/cespare/xxhash/v2/LICENSE.txt
generated
vendored
Normal file
22
vendor/github.com/cespare/xxhash/v2/LICENSE.txt
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
Copyright (c) 2016 Caleb Spare
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of this software and associated documentation files (the
|
||||||
|
"Software"), to deal in the Software without restriction, including
|
||||||
|
without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be
|
||||||
|
included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
74
vendor/github.com/cespare/xxhash/v2/README.md
generated
vendored
Normal file
74
vendor/github.com/cespare/xxhash/v2/README.md
generated
vendored
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
# xxhash
|
||||||
|
|
||||||
|
[](https://pkg.go.dev/github.com/cespare/xxhash/v2)
|
||||||
|
[](https://github.com/cespare/xxhash/actions/workflows/test.yml)
|
||||||
|
|
||||||
|
xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a
|
||||||
|
high-quality hashing algorithm that is much faster than anything in the Go
|
||||||
|
standard library.
|
||||||
|
|
||||||
|
This package provides a straightforward API:
|
||||||
|
|
||||||
|
```
|
||||||
|
func Sum64(b []byte) uint64
|
||||||
|
func Sum64String(s string) uint64
|
||||||
|
type Digest struct{ ... }
|
||||||
|
func New() *Digest
|
||||||
|
```
|
||||||
|
|
||||||
|
The `Digest` type implements hash.Hash64. Its key methods are:
|
||||||
|
|
||||||
|
```
|
||||||
|
func (*Digest) Write([]byte) (int, error)
|
||||||
|
func (*Digest) WriteString(string) (int, error)
|
||||||
|
func (*Digest) Sum64() uint64
|
||||||
|
```
|
||||||
|
|
||||||
|
The package is written with optimized pure Go and also contains even faster
|
||||||
|
assembly implementations for amd64 and arm64. If desired, the `purego` build tag
|
||||||
|
opts into using the Go code even on those architectures.
|
||||||
|
|
||||||
|
[xxHash]: http://cyan4973.github.io/xxHash/
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
This package is in a module and the latest code is in version 2 of the module.
|
||||||
|
You need a version of Go with at least "minimal module compatibility" to use
|
||||||
|
github.com/cespare/xxhash/v2:
|
||||||
|
|
||||||
|
* 1.9.7+ for Go 1.9
|
||||||
|
* 1.10.3+ for Go 1.10
|
||||||
|
* Go 1.11 or later
|
||||||
|
|
||||||
|
I recommend using the latest release of Go.
|
||||||
|
|
||||||
|
## Benchmarks
|
||||||
|
|
||||||
|
Here are some quick benchmarks comparing the pure-Go and assembly
|
||||||
|
implementations of Sum64.
|
||||||
|
|
||||||
|
| input size | purego | asm |
|
||||||
|
| ---------- | --------- | --------- |
|
||||||
|
| 4 B | 1.3 GB/s | 1.2 GB/s |
|
||||||
|
| 16 B | 2.9 GB/s | 3.5 GB/s |
|
||||||
|
| 100 B | 6.9 GB/s | 8.1 GB/s |
|
||||||
|
| 4 KB | 11.7 GB/s | 16.7 GB/s |
|
||||||
|
| 10 MB | 12.0 GB/s | 17.3 GB/s |
|
||||||
|
|
||||||
|
These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C
|
||||||
|
CPU using the following commands under Go 1.19.2:
|
||||||
|
|
||||||
|
```
|
||||||
|
benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$')
|
||||||
|
benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Projects using this package
|
||||||
|
|
||||||
|
- [InfluxDB](https://github.com/influxdata/influxdb)
|
||||||
|
- [Prometheus](https://github.com/prometheus/prometheus)
|
||||||
|
- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics)
|
||||||
|
- [FreeCache](https://github.com/coocood/freecache)
|
||||||
|
- [FastCache](https://github.com/VictoriaMetrics/fastcache)
|
||||||
|
- [Ristretto](https://github.com/dgraph-io/ristretto)
|
||||||
|
- [Badger](https://github.com/dgraph-io/badger)
|
||||||
10
vendor/github.com/cespare/xxhash/v2/testall.sh
generated
vendored
Normal file
10
vendor/github.com/cespare/xxhash/v2/testall.sh
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -eu -o pipefail
|
||||||
|
|
||||||
|
# Small convenience script for running the tests with various combinations of
|
||||||
|
# arch/tags. This assumes we're running on amd64 and have qemu available.
|
||||||
|
|
||||||
|
go test ./...
|
||||||
|
go test -tags purego ./...
|
||||||
|
GOARCH=arm64 go test
|
||||||
|
GOARCH=arm64 go test -tags purego
|
||||||
243
vendor/github.com/cespare/xxhash/v2/xxhash.go
generated
vendored
Normal file
243
vendor/github.com/cespare/xxhash/v2/xxhash.go
generated
vendored
Normal file
@@ -0,0 +1,243 @@
|
|||||||
|
// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described
|
||||||
|
// at http://cyan4973.github.io/xxHash/.
|
||||||
|
package xxhash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"math/bits"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
prime1 uint64 = 11400714785074694791
|
||||||
|
prime2 uint64 = 14029467366897019727
|
||||||
|
prime3 uint64 = 1609587929392839161
|
||||||
|
prime4 uint64 = 9650029242287828579
|
||||||
|
prime5 uint64 = 2870177450012600261
|
||||||
|
)
|
||||||
|
|
||||||
|
// Store the primes in an array as well.
|
||||||
|
//
|
||||||
|
// The consts are used when possible in Go code to avoid MOVs but we need a
|
||||||
|
// contiguous array for the assembly code.
|
||||||
|
var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5}
|
||||||
|
|
||||||
|
// Digest implements hash.Hash64.
|
||||||
|
//
|
||||||
|
// Note that a zero-valued Digest is not ready to receive writes.
|
||||||
|
// Call Reset or create a Digest using New before calling other methods.
|
||||||
|
type Digest struct {
|
||||||
|
v1 uint64
|
||||||
|
v2 uint64
|
||||||
|
v3 uint64
|
||||||
|
v4 uint64
|
||||||
|
total uint64
|
||||||
|
mem [32]byte
|
||||||
|
n int // how much of mem is used
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a new Digest with a zero seed.
|
||||||
|
func New() *Digest {
|
||||||
|
return NewWithSeed(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewWithSeed creates a new Digest with the given seed.
|
||||||
|
func NewWithSeed(seed uint64) *Digest {
|
||||||
|
var d Digest
|
||||||
|
d.ResetWithSeed(seed)
|
||||||
|
return &d
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset clears the Digest's state so that it can be reused.
|
||||||
|
// It uses a seed value of zero.
|
||||||
|
func (d *Digest) Reset() {
|
||||||
|
d.ResetWithSeed(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetWithSeed clears the Digest's state so that it can be reused.
|
||||||
|
// It uses the given seed to initialize the state.
|
||||||
|
func (d *Digest) ResetWithSeed(seed uint64) {
|
||||||
|
d.v1 = seed + prime1 + prime2
|
||||||
|
d.v2 = seed + prime2
|
||||||
|
d.v3 = seed
|
||||||
|
d.v4 = seed - prime1
|
||||||
|
d.total = 0
|
||||||
|
d.n = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size always returns 8 bytes.
|
||||||
|
func (d *Digest) Size() int { return 8 }
|
||||||
|
|
||||||
|
// BlockSize always returns 32 bytes.
|
||||||
|
func (d *Digest) BlockSize() int { return 32 }
|
||||||
|
|
||||||
|
// Write adds more data to d. It always returns len(b), nil.
|
||||||
|
func (d *Digest) Write(b []byte) (n int, err error) {
|
||||||
|
n = len(b)
|
||||||
|
d.total += uint64(n)
|
||||||
|
|
||||||
|
memleft := d.mem[d.n&(len(d.mem)-1):]
|
||||||
|
|
||||||
|
if d.n+n < 32 {
|
||||||
|
// This new data doesn't even fill the current block.
|
||||||
|
copy(memleft, b)
|
||||||
|
d.n += n
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.n > 0 {
|
||||||
|
// Finish off the partial block.
|
||||||
|
c := copy(memleft, b)
|
||||||
|
d.v1 = round(d.v1, u64(d.mem[0:8]))
|
||||||
|
d.v2 = round(d.v2, u64(d.mem[8:16]))
|
||||||
|
d.v3 = round(d.v3, u64(d.mem[16:24]))
|
||||||
|
d.v4 = round(d.v4, u64(d.mem[24:32]))
|
||||||
|
b = b[c:]
|
||||||
|
d.n = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(b) >= 32 {
|
||||||
|
// One or more full blocks left.
|
||||||
|
nw := writeBlocks(d, b)
|
||||||
|
b = b[nw:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store any remaining partial block.
|
||||||
|
copy(d.mem[:], b)
|
||||||
|
d.n = len(b)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sum appends the current hash to b and returns the resulting slice.
|
||||||
|
func (d *Digest) Sum(b []byte) []byte {
|
||||||
|
s := d.Sum64()
|
||||||
|
return append(
|
||||||
|
b,
|
||||||
|
byte(s>>56),
|
||||||
|
byte(s>>48),
|
||||||
|
byte(s>>40),
|
||||||
|
byte(s>>32),
|
||||||
|
byte(s>>24),
|
||||||
|
byte(s>>16),
|
||||||
|
byte(s>>8),
|
||||||
|
byte(s),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sum64 returns the current hash.
|
||||||
|
func (d *Digest) Sum64() uint64 {
|
||||||
|
var h uint64
|
||||||
|
|
||||||
|
if d.total >= 32 {
|
||||||
|
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
|
||||||
|
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
|
||||||
|
h = mergeRound(h, v1)
|
||||||
|
h = mergeRound(h, v2)
|
||||||
|
h = mergeRound(h, v3)
|
||||||
|
h = mergeRound(h, v4)
|
||||||
|
} else {
|
||||||
|
h = d.v3 + prime5
|
||||||
|
}
|
||||||
|
|
||||||
|
h += d.total
|
||||||
|
|
||||||
|
b := d.mem[:d.n&(len(d.mem)-1)]
|
||||||
|
for ; len(b) >= 8; b = b[8:] {
|
||||||
|
k1 := round(0, u64(b[:8]))
|
||||||
|
h ^= k1
|
||||||
|
h = rol27(h)*prime1 + prime4
|
||||||
|
}
|
||||||
|
if len(b) >= 4 {
|
||||||
|
h ^= uint64(u32(b[:4])) * prime1
|
||||||
|
h = rol23(h)*prime2 + prime3
|
||||||
|
b = b[4:]
|
||||||
|
}
|
||||||
|
for ; len(b) > 0; b = b[1:] {
|
||||||
|
h ^= uint64(b[0]) * prime5
|
||||||
|
h = rol11(h) * prime1
|
||||||
|
}
|
||||||
|
|
||||||
|
h ^= h >> 33
|
||||||
|
h *= prime2
|
||||||
|
h ^= h >> 29
|
||||||
|
h *= prime3
|
||||||
|
h ^= h >> 32
|
||||||
|
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
magic = "xxh\x06"
|
||||||
|
marshaledSize = len(magic) + 8*5 + 32
|
||||||
|
)
|
||||||
|
|
||||||
|
// MarshalBinary implements the encoding.BinaryMarshaler interface.
|
||||||
|
func (d *Digest) MarshalBinary() ([]byte, error) {
|
||||||
|
b := make([]byte, 0, marshaledSize)
|
||||||
|
b = append(b, magic...)
|
||||||
|
b = appendUint64(b, d.v1)
|
||||||
|
b = appendUint64(b, d.v2)
|
||||||
|
b = appendUint64(b, d.v3)
|
||||||
|
b = appendUint64(b, d.v4)
|
||||||
|
b = appendUint64(b, d.total)
|
||||||
|
b = append(b, d.mem[:d.n]...)
|
||||||
|
b = b[:len(b)+len(d.mem)-d.n]
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
|
||||||
|
func (d *Digest) UnmarshalBinary(b []byte) error {
|
||||||
|
if len(b) < len(magic) || string(b[:len(magic)]) != magic {
|
||||||
|
return errors.New("xxhash: invalid hash state identifier")
|
||||||
|
}
|
||||||
|
if len(b) != marshaledSize {
|
||||||
|
return errors.New("xxhash: invalid hash state size")
|
||||||
|
}
|
||||||
|
b = b[len(magic):]
|
||||||
|
b, d.v1 = consumeUint64(b)
|
||||||
|
b, d.v2 = consumeUint64(b)
|
||||||
|
b, d.v3 = consumeUint64(b)
|
||||||
|
b, d.v4 = consumeUint64(b)
|
||||||
|
b, d.total = consumeUint64(b)
|
||||||
|
copy(d.mem[:], b)
|
||||||
|
d.n = int(d.total % uint64(len(d.mem)))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendUint64(b []byte, x uint64) []byte {
|
||||||
|
var a [8]byte
|
||||||
|
binary.LittleEndian.PutUint64(a[:], x)
|
||||||
|
return append(b, a[:]...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func consumeUint64(b []byte) ([]byte, uint64) {
|
||||||
|
x := u64(b)
|
||||||
|
return b[8:], x
|
||||||
|
}
|
||||||
|
|
||||||
|
func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) }
|
||||||
|
func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) }
|
||||||
|
|
||||||
|
func round(acc, input uint64) uint64 {
|
||||||
|
acc += input * prime2
|
||||||
|
acc = rol31(acc)
|
||||||
|
acc *= prime1
|
||||||
|
return acc
|
||||||
|
}
|
||||||
|
|
||||||
|
func mergeRound(acc, val uint64) uint64 {
|
||||||
|
val = round(0, val)
|
||||||
|
acc ^= val
|
||||||
|
acc = acc*prime1 + prime4
|
||||||
|
return acc
|
||||||
|
}
|
||||||
|
|
||||||
|
func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) }
|
||||||
|
func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) }
|
||||||
|
func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) }
|
||||||
|
func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) }
|
||||||
|
func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) }
|
||||||
|
func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) }
|
||||||
|
func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) }
|
||||||
|
func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) }
|
||||||
209
vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s
generated
vendored
Normal file
209
vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s
generated
vendored
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
//go:build !appengine && gc && !purego
|
||||||
|
// +build !appengine
|
||||||
|
// +build gc
|
||||||
|
// +build !purego
|
||||||
|
|
||||||
|
#include "textflag.h"
|
||||||
|
|
||||||
|
// Registers:
|
||||||
|
#define h AX
|
||||||
|
#define d AX
|
||||||
|
#define p SI // pointer to advance through b
|
||||||
|
#define n DX
|
||||||
|
#define end BX // loop end
|
||||||
|
#define v1 R8
|
||||||
|
#define v2 R9
|
||||||
|
#define v3 R10
|
||||||
|
#define v4 R11
|
||||||
|
#define x R12
|
||||||
|
#define prime1 R13
|
||||||
|
#define prime2 R14
|
||||||
|
#define prime4 DI
|
||||||
|
|
||||||
|
#define round(acc, x) \
|
||||||
|
IMULQ prime2, x \
|
||||||
|
ADDQ x, acc \
|
||||||
|
ROLQ $31, acc \
|
||||||
|
IMULQ prime1, acc
|
||||||
|
|
||||||
|
// round0 performs the operation x = round(0, x).
|
||||||
|
#define round0(x) \
|
||||||
|
IMULQ prime2, x \
|
||||||
|
ROLQ $31, x \
|
||||||
|
IMULQ prime1, x
|
||||||
|
|
||||||
|
// mergeRound applies a merge round on the two registers acc and x.
|
||||||
|
// It assumes that prime1, prime2, and prime4 have been loaded.
|
||||||
|
#define mergeRound(acc, x) \
|
||||||
|
round0(x) \
|
||||||
|
XORQ x, acc \
|
||||||
|
IMULQ prime1, acc \
|
||||||
|
ADDQ prime4, acc
|
||||||
|
|
||||||
|
// blockLoop processes as many 32-byte blocks as possible,
|
||||||
|
// updating v1, v2, v3, and v4. It assumes that there is at least one block
|
||||||
|
// to process.
|
||||||
|
#define blockLoop() \
|
||||||
|
loop: \
|
||||||
|
MOVQ +0(p), x \
|
||||||
|
round(v1, x) \
|
||||||
|
MOVQ +8(p), x \
|
||||||
|
round(v2, x) \
|
||||||
|
MOVQ +16(p), x \
|
||||||
|
round(v3, x) \
|
||||||
|
MOVQ +24(p), x \
|
||||||
|
round(v4, x) \
|
||||||
|
ADDQ $32, p \
|
||||||
|
CMPQ p, end \
|
||||||
|
JLE loop
|
||||||
|
|
||||||
|
// func Sum64(b []byte) uint64
|
||||||
|
TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32
|
||||||
|
// Load fixed primes.
|
||||||
|
MOVQ ·primes+0(SB), prime1
|
||||||
|
MOVQ ·primes+8(SB), prime2
|
||||||
|
MOVQ ·primes+24(SB), prime4
|
||||||
|
|
||||||
|
// Load slice.
|
||||||
|
MOVQ b_base+0(FP), p
|
||||||
|
MOVQ b_len+8(FP), n
|
||||||
|
LEAQ (p)(n*1), end
|
||||||
|
|
||||||
|
// The first loop limit will be len(b)-32.
|
||||||
|
SUBQ $32, end
|
||||||
|
|
||||||
|
// Check whether we have at least one block.
|
||||||
|
CMPQ n, $32
|
||||||
|
JLT noBlocks
|
||||||
|
|
||||||
|
// Set up initial state (v1, v2, v3, v4).
|
||||||
|
MOVQ prime1, v1
|
||||||
|
ADDQ prime2, v1
|
||||||
|
MOVQ prime2, v2
|
||||||
|
XORQ v3, v3
|
||||||
|
XORQ v4, v4
|
||||||
|
SUBQ prime1, v4
|
||||||
|
|
||||||
|
blockLoop()
|
||||||
|
|
||||||
|
MOVQ v1, h
|
||||||
|
ROLQ $1, h
|
||||||
|
MOVQ v2, x
|
||||||
|
ROLQ $7, x
|
||||||
|
ADDQ x, h
|
||||||
|
MOVQ v3, x
|
||||||
|
ROLQ $12, x
|
||||||
|
ADDQ x, h
|
||||||
|
MOVQ v4, x
|
||||||
|
ROLQ $18, x
|
||||||
|
ADDQ x, h
|
||||||
|
|
||||||
|
mergeRound(h, v1)
|
||||||
|
mergeRound(h, v2)
|
||||||
|
mergeRound(h, v3)
|
||||||
|
mergeRound(h, v4)
|
||||||
|
|
||||||
|
JMP afterBlocks
|
||||||
|
|
||||||
|
noBlocks:
|
||||||
|
MOVQ ·primes+32(SB), h
|
||||||
|
|
||||||
|
afterBlocks:
|
||||||
|
ADDQ n, h
|
||||||
|
|
||||||
|
ADDQ $24, end
|
||||||
|
CMPQ p, end
|
||||||
|
JG try4
|
||||||
|
|
||||||
|
loop8:
|
||||||
|
MOVQ (p), x
|
||||||
|
ADDQ $8, p
|
||||||
|
round0(x)
|
||||||
|
XORQ x, h
|
||||||
|
ROLQ $27, h
|
||||||
|
IMULQ prime1, h
|
||||||
|
ADDQ prime4, h
|
||||||
|
|
||||||
|
CMPQ p, end
|
||||||
|
JLE loop8
|
||||||
|
|
||||||
|
try4:
|
||||||
|
ADDQ $4, end
|
||||||
|
CMPQ p, end
|
||||||
|
JG try1
|
||||||
|
|
||||||
|
MOVL (p), x
|
||||||
|
ADDQ $4, p
|
||||||
|
IMULQ prime1, x
|
||||||
|
XORQ x, h
|
||||||
|
|
||||||
|
ROLQ $23, h
|
||||||
|
IMULQ prime2, h
|
||||||
|
ADDQ ·primes+16(SB), h
|
||||||
|
|
||||||
|
try1:
|
||||||
|
ADDQ $4, end
|
||||||
|
CMPQ p, end
|
||||||
|
JGE finalize
|
||||||
|
|
||||||
|
loop1:
|
||||||
|
MOVBQZX (p), x
|
||||||
|
ADDQ $1, p
|
||||||
|
IMULQ ·primes+32(SB), x
|
||||||
|
XORQ x, h
|
||||||
|
ROLQ $11, h
|
||||||
|
IMULQ prime1, h
|
||||||
|
|
||||||
|
CMPQ p, end
|
||||||
|
JL loop1
|
||||||
|
|
||||||
|
finalize:
|
||||||
|
MOVQ h, x
|
||||||
|
SHRQ $33, x
|
||||||
|
XORQ x, h
|
||||||
|
IMULQ prime2, h
|
||||||
|
MOVQ h, x
|
||||||
|
SHRQ $29, x
|
||||||
|
XORQ x, h
|
||||||
|
IMULQ ·primes+16(SB), h
|
||||||
|
MOVQ h, x
|
||||||
|
SHRQ $32, x
|
||||||
|
XORQ x, h
|
||||||
|
|
||||||
|
MOVQ h, ret+24(FP)
|
||||||
|
RET
|
||||||
|
|
||||||
|
// func writeBlocks(d *Digest, b []byte) int
|
||||||
|
TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40
|
||||||
|
// Load fixed primes needed for round.
|
||||||
|
MOVQ ·primes+0(SB), prime1
|
||||||
|
MOVQ ·primes+8(SB), prime2
|
||||||
|
|
||||||
|
// Load slice.
|
||||||
|
MOVQ b_base+8(FP), p
|
||||||
|
MOVQ b_len+16(FP), n
|
||||||
|
LEAQ (p)(n*1), end
|
||||||
|
SUBQ $32, end
|
||||||
|
|
||||||
|
// Load vN from d.
|
||||||
|
MOVQ s+0(FP), d
|
||||||
|
MOVQ 0(d), v1
|
||||||
|
MOVQ 8(d), v2
|
||||||
|
MOVQ 16(d), v3
|
||||||
|
MOVQ 24(d), v4
|
||||||
|
|
||||||
|
// We don't need to check the loop condition here; this function is
|
||||||
|
// always called with at least one block of data to process.
|
||||||
|
blockLoop()
|
||||||
|
|
||||||
|
// Copy vN back to d.
|
||||||
|
MOVQ v1, 0(d)
|
||||||
|
MOVQ v2, 8(d)
|
||||||
|
MOVQ v3, 16(d)
|
||||||
|
MOVQ v4, 24(d)
|
||||||
|
|
||||||
|
// The number of bytes written is p minus the old base pointer.
|
||||||
|
SUBQ b_base+8(FP), p
|
||||||
|
MOVQ p, ret+32(FP)
|
||||||
|
|
||||||
|
RET
|
||||||
183
vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s
generated
vendored
Normal file
183
vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s
generated
vendored
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
//go:build !appengine && gc && !purego
|
||||||
|
// +build !appengine
|
||||||
|
// +build gc
|
||||||
|
// +build !purego
|
||||||
|
|
||||||
|
#include "textflag.h"
|
||||||
|
|
||||||
|
// Registers:
|
||||||
|
#define digest R1
|
||||||
|
#define h R2 // return value
|
||||||
|
#define p R3 // input pointer
|
||||||
|
#define n R4 // input length
|
||||||
|
#define nblocks R5 // n / 32
|
||||||
|
#define prime1 R7
|
||||||
|
#define prime2 R8
|
||||||
|
#define prime3 R9
|
||||||
|
#define prime4 R10
|
||||||
|
#define prime5 R11
|
||||||
|
#define v1 R12
|
||||||
|
#define v2 R13
|
||||||
|
#define v3 R14
|
||||||
|
#define v4 R15
|
||||||
|
#define x1 R20
|
||||||
|
#define x2 R21
|
||||||
|
#define x3 R22
|
||||||
|
#define x4 R23
|
||||||
|
|
||||||
|
#define round(acc, x) \
|
||||||
|
MADD prime2, acc, x, acc \
|
||||||
|
ROR $64-31, acc \
|
||||||
|
MUL prime1, acc
|
||||||
|
|
||||||
|
// round0 performs the operation x = round(0, x).
|
||||||
|
#define round0(x) \
|
||||||
|
MUL prime2, x \
|
||||||
|
ROR $64-31, x \
|
||||||
|
MUL prime1, x
|
||||||
|
|
||||||
|
#define mergeRound(acc, x) \
|
||||||
|
round0(x) \
|
||||||
|
EOR x, acc \
|
||||||
|
MADD acc, prime4, prime1, acc
|
||||||
|
|
||||||
|
// blockLoop processes as many 32-byte blocks as possible,
|
||||||
|
// updating v1, v2, v3, and v4. It assumes that n >= 32.
|
||||||
|
#define blockLoop() \
|
||||||
|
LSR $5, n, nblocks \
|
||||||
|
PCALIGN $16 \
|
||||||
|
loop: \
|
||||||
|
LDP.P 16(p), (x1, x2) \
|
||||||
|
LDP.P 16(p), (x3, x4) \
|
||||||
|
round(v1, x1) \
|
||||||
|
round(v2, x2) \
|
||||||
|
round(v3, x3) \
|
||||||
|
round(v4, x4) \
|
||||||
|
SUB $1, nblocks \
|
||||||
|
CBNZ nblocks, loop
|
||||||
|
|
||||||
|
// func Sum64(b []byte) uint64
|
||||||
|
TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32
|
||||||
|
LDP b_base+0(FP), (p, n)
|
||||||
|
|
||||||
|
LDP ·primes+0(SB), (prime1, prime2)
|
||||||
|
LDP ·primes+16(SB), (prime3, prime4)
|
||||||
|
MOVD ·primes+32(SB), prime5
|
||||||
|
|
||||||
|
CMP $32, n
|
||||||
|
CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 }
|
||||||
|
BLT afterLoop
|
||||||
|
|
||||||
|
ADD prime1, prime2, v1
|
||||||
|
MOVD prime2, v2
|
||||||
|
MOVD $0, v3
|
||||||
|
NEG prime1, v4
|
||||||
|
|
||||||
|
blockLoop()
|
||||||
|
|
||||||
|
ROR $64-1, v1, x1
|
||||||
|
ROR $64-7, v2, x2
|
||||||
|
ADD x1, x2
|
||||||
|
ROR $64-12, v3, x3
|
||||||
|
ROR $64-18, v4, x4
|
||||||
|
ADD x3, x4
|
||||||
|
ADD x2, x4, h
|
||||||
|
|
||||||
|
mergeRound(h, v1)
|
||||||
|
mergeRound(h, v2)
|
||||||
|
mergeRound(h, v3)
|
||||||
|
mergeRound(h, v4)
|
||||||
|
|
||||||
|
afterLoop:
|
||||||
|
ADD n, h
|
||||||
|
|
||||||
|
TBZ $4, n, try8
|
||||||
|
LDP.P 16(p), (x1, x2)
|
||||||
|
|
||||||
|
round0(x1)
|
||||||
|
|
||||||
|
// NOTE: here and below, sequencing the EOR after the ROR (using a
|
||||||
|
// rotated register) is worth a small but measurable speedup for small
|
||||||
|
// inputs.
|
||||||
|
ROR $64-27, h
|
||||||
|
EOR x1 @> 64-27, h, h
|
||||||
|
MADD h, prime4, prime1, h
|
||||||
|
|
||||||
|
round0(x2)
|
||||||
|
ROR $64-27, h
|
||||||
|
EOR x2 @> 64-27, h, h
|
||||||
|
MADD h, prime4, prime1, h
|
||||||
|
|
||||||
|
try8:
|
||||||
|
TBZ $3, n, try4
|
||||||
|
MOVD.P 8(p), x1
|
||||||
|
|
||||||
|
round0(x1)
|
||||||
|
ROR $64-27, h
|
||||||
|
EOR x1 @> 64-27, h, h
|
||||||
|
MADD h, prime4, prime1, h
|
||||||
|
|
||||||
|
try4:
|
||||||
|
TBZ $2, n, try2
|
||||||
|
MOVWU.P 4(p), x2
|
||||||
|
|
||||||
|
MUL prime1, x2
|
||||||
|
ROR $64-23, h
|
||||||
|
EOR x2 @> 64-23, h, h
|
||||||
|
MADD h, prime3, prime2, h
|
||||||
|
|
||||||
|
try2:
|
||||||
|
TBZ $1, n, try1
|
||||||
|
MOVHU.P 2(p), x3
|
||||||
|
AND $255, x3, x1
|
||||||
|
LSR $8, x3, x2
|
||||||
|
|
||||||
|
MUL prime5, x1
|
||||||
|
ROR $64-11, h
|
||||||
|
EOR x1 @> 64-11, h, h
|
||||||
|
MUL prime1, h
|
||||||
|
|
||||||
|
MUL prime5, x2
|
||||||
|
ROR $64-11, h
|
||||||
|
EOR x2 @> 64-11, h, h
|
||||||
|
MUL prime1, h
|
||||||
|
|
||||||
|
try1:
|
||||||
|
TBZ $0, n, finalize
|
||||||
|
MOVBU (p), x4
|
||||||
|
|
||||||
|
MUL prime5, x4
|
||||||
|
ROR $64-11, h
|
||||||
|
EOR x4 @> 64-11, h, h
|
||||||
|
MUL prime1, h
|
||||||
|
|
||||||
|
finalize:
|
||||||
|
EOR h >> 33, h
|
||||||
|
MUL prime2, h
|
||||||
|
EOR h >> 29, h
|
||||||
|
MUL prime3, h
|
||||||
|
EOR h >> 32, h
|
||||||
|
|
||||||
|
MOVD h, ret+24(FP)
|
||||||
|
RET
|
||||||
|
|
||||||
|
// func writeBlocks(d *Digest, b []byte) int
|
||||||
|
TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40
|
||||||
|
LDP ·primes+0(SB), (prime1, prime2)
|
||||||
|
|
||||||
|
// Load state. Assume v[1-4] are stored contiguously.
|
||||||
|
MOVD d+0(FP), digest
|
||||||
|
LDP 0(digest), (v1, v2)
|
||||||
|
LDP 16(digest), (v3, v4)
|
||||||
|
|
||||||
|
LDP b_base+8(FP), (p, n)
|
||||||
|
|
||||||
|
blockLoop()
|
||||||
|
|
||||||
|
// Store updated state.
|
||||||
|
STP (v1, v2), 0(digest)
|
||||||
|
STP (v3, v4), 16(digest)
|
||||||
|
|
||||||
|
BIC $31, n
|
||||||
|
MOVD n, ret+32(FP)
|
||||||
|
RET
|
||||||
15
vendor/github.com/cespare/xxhash/v2/xxhash_asm.go
generated
vendored
Normal file
15
vendor/github.com/cespare/xxhash/v2/xxhash_asm.go
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
//go:build (amd64 || arm64) && !appengine && gc && !purego
|
||||||
|
// +build amd64 arm64
|
||||||
|
// +build !appengine
|
||||||
|
// +build gc
|
||||||
|
// +build !purego
|
||||||
|
|
||||||
|
package xxhash
|
||||||
|
|
||||||
|
// Sum64 computes the 64-bit xxHash digest of b with a zero seed.
|
||||||
|
//
|
||||||
|
//go:noescape
|
||||||
|
func Sum64(b []byte) uint64
|
||||||
|
|
||||||
|
//go:noescape
|
||||||
|
func writeBlocks(d *Digest, b []byte) int
|
||||||
76
vendor/github.com/cespare/xxhash/v2/xxhash_other.go
generated
vendored
Normal file
76
vendor/github.com/cespare/xxhash/v2/xxhash_other.go
generated
vendored
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
//go:build (!amd64 && !arm64) || appengine || !gc || purego
|
||||||
|
// +build !amd64,!arm64 appengine !gc purego
|
||||||
|
|
||||||
|
package xxhash
|
||||||
|
|
||||||
|
// Sum64 computes the 64-bit xxHash digest of b with a zero seed.
|
||||||
|
func Sum64(b []byte) uint64 {
|
||||||
|
// A simpler version would be
|
||||||
|
// d := New()
|
||||||
|
// d.Write(b)
|
||||||
|
// return d.Sum64()
|
||||||
|
// but this is faster, particularly for small inputs.
|
||||||
|
|
||||||
|
n := len(b)
|
||||||
|
var h uint64
|
||||||
|
|
||||||
|
if n >= 32 {
|
||||||
|
v1 := primes[0] + prime2
|
||||||
|
v2 := prime2
|
||||||
|
v3 := uint64(0)
|
||||||
|
v4 := -primes[0]
|
||||||
|
for len(b) >= 32 {
|
||||||
|
v1 = round(v1, u64(b[0:8:len(b)]))
|
||||||
|
v2 = round(v2, u64(b[8:16:len(b)]))
|
||||||
|
v3 = round(v3, u64(b[16:24:len(b)]))
|
||||||
|
v4 = round(v4, u64(b[24:32:len(b)]))
|
||||||
|
b = b[32:len(b):len(b)]
|
||||||
|
}
|
||||||
|
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
|
||||||
|
h = mergeRound(h, v1)
|
||||||
|
h = mergeRound(h, v2)
|
||||||
|
h = mergeRound(h, v3)
|
||||||
|
h = mergeRound(h, v4)
|
||||||
|
} else {
|
||||||
|
h = prime5
|
||||||
|
}
|
||||||
|
|
||||||
|
h += uint64(n)
|
||||||
|
|
||||||
|
for ; len(b) >= 8; b = b[8:] {
|
||||||
|
k1 := round(0, u64(b[:8]))
|
||||||
|
h ^= k1
|
||||||
|
h = rol27(h)*prime1 + prime4
|
||||||
|
}
|
||||||
|
if len(b) >= 4 {
|
||||||
|
h ^= uint64(u32(b[:4])) * prime1
|
||||||
|
h = rol23(h)*prime2 + prime3
|
||||||
|
b = b[4:]
|
||||||
|
}
|
||||||
|
for ; len(b) > 0; b = b[1:] {
|
||||||
|
h ^= uint64(b[0]) * prime5
|
||||||
|
h = rol11(h) * prime1
|
||||||
|
}
|
||||||
|
|
||||||
|
h ^= h >> 33
|
||||||
|
h *= prime2
|
||||||
|
h ^= h >> 29
|
||||||
|
h *= prime3
|
||||||
|
h ^= h >> 32
|
||||||
|
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeBlocks(d *Digest, b []byte) int {
|
||||||
|
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
|
||||||
|
n := len(b)
|
||||||
|
for len(b) >= 32 {
|
||||||
|
v1 = round(v1, u64(b[0:8:len(b)]))
|
||||||
|
v2 = round(v2, u64(b[8:16:len(b)]))
|
||||||
|
v3 = round(v3, u64(b[16:24:len(b)]))
|
||||||
|
v4 = round(v4, u64(b[24:32:len(b)]))
|
||||||
|
b = b[32:len(b):len(b)]
|
||||||
|
}
|
||||||
|
d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4
|
||||||
|
return n - len(b)
|
||||||
|
}
|
||||||
16
vendor/github.com/cespare/xxhash/v2/xxhash_safe.go
generated
vendored
Normal file
16
vendor/github.com/cespare/xxhash/v2/xxhash_safe.go
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
//go:build appengine
|
||||||
|
// +build appengine
|
||||||
|
|
||||||
|
// This file contains the safe implementations of otherwise unsafe-using code.
|
||||||
|
|
||||||
|
package xxhash
|
||||||
|
|
||||||
|
// Sum64String computes the 64-bit xxHash digest of s with a zero seed.
|
||||||
|
func Sum64String(s string) uint64 {
|
||||||
|
return Sum64([]byte(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteString adds more data to d. It always returns len(s), nil.
|
||||||
|
func (d *Digest) WriteString(s string) (n int, err error) {
|
||||||
|
return d.Write([]byte(s))
|
||||||
|
}
|
||||||
58
vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go
generated
vendored
Normal file
58
vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
//go:build !appengine
|
||||||
|
// +build !appengine
|
||||||
|
|
||||||
|
// This file encapsulates usage of unsafe.
|
||||||
|
// xxhash_safe.go contains the safe implementations.
|
||||||
|
|
||||||
|
package xxhash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// In the future it's possible that compiler optimizations will make these
|
||||||
|
// XxxString functions unnecessary by realizing that calls such as
|
||||||
|
// Sum64([]byte(s)) don't need to copy s. See https://go.dev/issue/2205.
|
||||||
|
// If that happens, even if we keep these functions they can be replaced with
|
||||||
|
// the trivial safe code.
|
||||||
|
|
||||||
|
// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is:
|
||||||
|
//
|
||||||
|
// var b []byte
|
||||||
|
// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||||
|
// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
|
||||||
|
// bh.Len = len(s)
|
||||||
|
// bh.Cap = len(s)
|
||||||
|
//
|
||||||
|
// Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough
|
||||||
|
// weight to this sequence of expressions that any function that uses it will
|
||||||
|
// not be inlined. Instead, the functions below use a different unsafe
|
||||||
|
// conversion designed to minimize the inliner weight and allow both to be
|
||||||
|
// inlined. There is also a test (TestInlining) which verifies that these are
|
||||||
|
// inlined.
|
||||||
|
//
|
||||||
|
// See https://github.com/golang/go/issues/42739 for discussion.
|
||||||
|
|
||||||
|
// Sum64String computes the 64-bit xxHash digest of s with a zero seed.
|
||||||
|
// It may be faster than Sum64([]byte(s)) by avoiding a copy.
|
||||||
|
func Sum64String(s string) uint64 {
|
||||||
|
b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))
|
||||||
|
return Sum64(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteString adds more data to d. It always returns len(s), nil.
|
||||||
|
// It may be faster than Write([]byte(s)) by avoiding a copy.
|
||||||
|
func (d *Digest) WriteString(s string) (n int, err error) {
|
||||||
|
d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})))
|
||||||
|
// d.Write always returns len(s), nil.
|
||||||
|
// Ignoring the return output and returning these fixed values buys a
|
||||||
|
// savings of 6 in the inliner's cost model.
|
||||||
|
return len(s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout
|
||||||
|
// of the first two words is the same as the layout of a string.
|
||||||
|
type sliceHeader struct {
|
||||||
|
s string
|
||||||
|
cap int
|
||||||
|
}
|
||||||
15
vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION
generated
vendored
15
vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION
generated
vendored
@@ -1,15 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
Eclipse Distribution License - v 1.0
|
|
||||||
|
|
||||||
Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors.
|
|
||||||
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
||||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
||||||
Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
283
vendor/github.com/eclipse/paho.mqtt.golang/LICENSE
generated
vendored
283
vendor/github.com/eclipse/paho.mqtt.golang/LICENSE
generated
vendored
@@ -1,87 +1,294 @@
|
|||||||
Eclipse Public License - v 1.0
|
Eclipse Public License - v 2.0 (EPL-2.0)
|
||||||
|
|
||||||
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
|
This program and the accompanying materials
|
||||||
|
are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
|
||||||
|
The Eclipse Public License is available at
|
||||||
|
https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
and the Eclipse Distribution License is available at
|
||||||
|
http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
|
||||||
|
For an explanation of what dual-licensing means to you, see:
|
||||||
|
https://www.eclipse.org/legal/eplfaq.php#DUALLIC
|
||||||
|
|
||||||
|
****
|
||||||
|
The epl-2.0 is copied below in order to pass the pkg.go.dev license check (https://pkg.go.dev/license-policy).
|
||||||
|
****
|
||||||
|
Eclipse Public License - v 2.0
|
||||||
|
|
||||||
|
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
|
||||||
|
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
|
||||||
|
OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
|
||||||
|
|
||||||
1. DEFINITIONS
|
1. DEFINITIONS
|
||||||
|
|
||||||
"Contribution" means:
|
"Contribution" means:
|
||||||
|
|
||||||
a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
|
a) in the case of the initial Contributor, the initial content
|
||||||
|
Distributed under this Agreement, and
|
||||||
|
|
||||||
b) in the case of each subsequent Contributor:
|
b) in the case of each subsequent Contributor:
|
||||||
|
i) changes to the Program, and
|
||||||
|
ii) additions to the Program;
|
||||||
|
where such changes and/or additions to the Program originate from
|
||||||
|
and are Distributed by that particular Contributor. A Contribution
|
||||||
|
"originates" from a Contributor if it was added to the Program by
|
||||||
|
such Contributor itself or anyone acting on such Contributor's behalf.
|
||||||
|
Contributions do not include changes or additions to the Program that
|
||||||
|
are not Modified Works.
|
||||||
|
|
||||||
i) changes to the Program, and
|
"Contributor" means any person or entity that Distributes the Program.
|
||||||
|
|
||||||
ii) additions to the Program;
|
"Licensed Patents" mean patent claims licensable by a Contributor which
|
||||||
|
are necessarily infringed by the use or sale of its Contribution alone
|
||||||
|
or when combined with the Program.
|
||||||
|
|
||||||
where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
|
"Program" means the Contributions Distributed in accordance with this
|
||||||
|
Agreement.
|
||||||
|
|
||||||
"Contributor" means any person or entity that distributes the Program.
|
"Recipient" means anyone who receives the Program under this Agreement
|
||||||
|
or any Secondary License (as applicable), including Contributors.
|
||||||
|
|
||||||
"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
|
"Derivative Works" shall mean any work, whether in Source Code or other
|
||||||
|
form, that is based on (or derived from) the Program and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship.
|
||||||
|
|
||||||
"Program" means the Contributions distributed in accordance with this Agreement.
|
"Modified Works" shall mean any work in Source Code or other form that
|
||||||
|
results from an addition to, deletion from, or modification of the
|
||||||
|
contents of the Program, including, for purposes of clarity any new file
|
||||||
|
in Source Code form that contains any contents of the Program. Modified
|
||||||
|
Works shall not include works that contain only declarations,
|
||||||
|
interfaces, types, classes, structures, or files of the Program solely
|
||||||
|
in each case in order to link to, bind by name, or subclass the Program
|
||||||
|
or Modified Works thereof.
|
||||||
|
|
||||||
"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
|
"Distribute" means the acts of a) distributing or b) making available
|
||||||
|
in any manner that enables the transfer of a copy.
|
||||||
|
|
||||||
|
"Source Code" means the form of a Program preferred for making
|
||||||
|
modifications, including but not limited to software source code,
|
||||||
|
documentation source, and configuration files.
|
||||||
|
|
||||||
|
"Secondary License" means either the GNU General Public License,
|
||||||
|
Version 2.0, or any later versions of that license, including any
|
||||||
|
exceptions or additional permissions as identified by the initial
|
||||||
|
Contributor.
|
||||||
|
|
||||||
2. GRANT OF RIGHTS
|
2. GRANT OF RIGHTS
|
||||||
|
|
||||||
a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
|
a) Subject to the terms of this Agreement, each Contributor hereby
|
||||||
|
grants Recipient a non-exclusive, worldwide, royalty-free copyright
|
||||||
|
license to reproduce, prepare Derivative Works of, publicly display,
|
||||||
|
publicly perform, Distribute and sublicense the Contribution of such
|
||||||
|
Contributor, if any, and such Derivative Works.
|
||||||
|
|
||||||
b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
|
b) Subject to the terms of this Agreement, each Contributor hereby
|
||||||
|
grants Recipient a non-exclusive, worldwide, royalty-free patent
|
||||||
|
license under Licensed Patents to make, use, sell, offer to sell,
|
||||||
|
import and otherwise transfer the Contribution of such Contributor,
|
||||||
|
if any, in Source Code or other form. This patent license shall
|
||||||
|
apply to the combination of the Contribution and the Program if, at
|
||||||
|
the time the Contribution is added by the Contributor, such addition
|
||||||
|
of the Contribution causes such combination to be covered by the
|
||||||
|
Licensed Patents. The patent license shall not apply to any other
|
||||||
|
combinations which include the Contribution. No hardware per se is
|
||||||
|
licensed hereunder.
|
||||||
|
|
||||||
c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
|
c) Recipient understands that although each Contributor grants the
|
||||||
|
licenses to its Contributions set forth herein, no assurances are
|
||||||
|
provided by any Contributor that the Program does not infringe the
|
||||||
|
patent or other intellectual property rights of any other entity.
|
||||||
|
Each Contributor disclaims any liability to Recipient for claims
|
||||||
|
brought by any other entity based on infringement of intellectual
|
||||||
|
property rights or otherwise. As a condition to exercising the
|
||||||
|
rights and licenses granted hereunder, each Recipient hereby
|
||||||
|
assumes sole responsibility to secure any other intellectual
|
||||||
|
property rights needed, if any. For example, if a third party
|
||||||
|
patent license is required to allow Recipient to Distribute the
|
||||||
|
Program, it is Recipient's responsibility to acquire that license
|
||||||
|
before distributing the Program.
|
||||||
|
|
||||||
d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
|
d) Each Contributor represents that to its knowledge it has
|
||||||
|
sufficient copyright rights in its Contribution, if any, to grant
|
||||||
|
the copyright license set forth in this Agreement.
|
||||||
|
|
||||||
|
e) Notwithstanding the terms of any Secondary License, no
|
||||||
|
Contributor makes additional grants to any Recipient (other than
|
||||||
|
those set forth in this Agreement) as a result of such Recipient's
|
||||||
|
receipt of the Program under the terms of a Secondary License
|
||||||
|
(if permitted under the terms of Section 3).
|
||||||
|
|
||||||
3. REQUIREMENTS
|
3. REQUIREMENTS
|
||||||
|
|
||||||
A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
|
3.1 If a Contributor Distributes the Program in any form, then:
|
||||||
|
|
||||||
a) it complies with the terms and conditions of this Agreement; and
|
a) the Program must also be made available as Source Code, in
|
||||||
|
accordance with section 3.2, and the Contributor must accompany
|
||||||
|
the Program with a statement that the Source Code for the Program
|
||||||
|
is available under this Agreement, and informs Recipients how to
|
||||||
|
obtain it in a reasonable manner on or through a medium customarily
|
||||||
|
used for software exchange; and
|
||||||
|
|
||||||
b) its license agreement:
|
b) the Contributor may Distribute the Program under a license
|
||||||
|
different than this Agreement, provided that such license:
|
||||||
|
i) effectively disclaims on behalf of all other Contributors all
|
||||||
|
warranties and conditions, express and implied, including
|
||||||
|
warranties or conditions of title and non-infringement, and
|
||||||
|
implied warranties or conditions of merchantability and fitness
|
||||||
|
for a particular purpose;
|
||||||
|
|
||||||
i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
|
ii) effectively excludes on behalf of all other Contributors all
|
||||||
|
liability for damages, including direct, indirect, special,
|
||||||
|
incidental and consequential damages, such as lost profits;
|
||||||
|
|
||||||
ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
|
iii) does not attempt to limit or alter the recipients' rights
|
||||||
|
in the Source Code under section 3.2; and
|
||||||
|
|
||||||
iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
|
iv) requires any subsequent distribution of the Program by any
|
||||||
|
party to be under a license that satisfies the requirements
|
||||||
|
of this section 3.
|
||||||
|
|
||||||
iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
|
3.2 When the Program is Distributed as Source Code:
|
||||||
|
|
||||||
When the Program is made available in source code form:
|
a) it must be made available under this Agreement, or if the
|
||||||
|
Program (i) is combined with other material in a separate file or
|
||||||
|
files made available under a Secondary License, and (ii) the initial
|
||||||
|
Contributor attached to the Source Code the notice described in
|
||||||
|
Exhibit A of this Agreement, then the Program may be made available
|
||||||
|
under the terms of such Secondary Licenses, and
|
||||||
|
|
||||||
a) it must be made available under this Agreement; and
|
b) a copy of this Agreement must be included with each copy of
|
||||||
|
the Program.
|
||||||
|
|
||||||
b) a copy of this Agreement must be included with each copy of the Program.
|
3.3 Contributors may not remove or alter any copyright, patent,
|
||||||
|
trademark, attribution notices, disclaimers of warranty, or limitations
|
||||||
Contributors may not remove or alter any copyright notices contained within the Program.
|
of liability ("notices") contained within the Program from any copy of
|
||||||
|
the Program which they Distribute, provided that Contributors may add
|
||||||
Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
|
their own appropriate notices.
|
||||||
|
|
||||||
4. COMMERCIAL DISTRIBUTION
|
4. COMMERCIAL DISTRIBUTION
|
||||||
|
|
||||||
Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
|
Commercial distributors of software may accept certain responsibilities
|
||||||
|
with respect to end users, business partners and the like. While this
|
||||||
|
license is intended to facilitate the commercial use of the Program,
|
||||||
|
the Contributor who includes the Program in a commercial product
|
||||||
|
offering should do so in a manner which does not create potential
|
||||||
|
liability for other Contributors. Therefore, if a Contributor includes
|
||||||
|
the Program in a commercial product offering, such Contributor
|
||||||
|
("Commercial Contributor") hereby agrees to defend and indemnify every
|
||||||
|
other Contributor ("Indemnified Contributor") against any losses,
|
||||||
|
damages and costs (collectively "Losses") arising from claims, lawsuits
|
||||||
|
and other legal actions brought by a third party against the Indemnified
|
||||||
|
Contributor to the extent caused by the acts or omissions of such
|
||||||
|
Commercial Contributor in connection with its distribution of the Program
|
||||||
|
in a commercial product offering. The obligations in this section do not
|
||||||
|
apply to any claims or Losses relating to any actual or alleged
|
||||||
|
intellectual property infringement. In order to qualify, an Indemnified
|
||||||
|
Contributor must: a) promptly notify the Commercial Contributor in
|
||||||
|
writing of such claim, and b) allow the Commercial Contributor to control,
|
||||||
|
and cooperate with the Commercial Contributor in, the defense and any
|
||||||
|
related settlement negotiations. The Indemnified Contributor may
|
||||||
|
participate in any such claim at its own expense.
|
||||||
|
|
||||||
For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
|
For example, a Contributor might include the Program in a commercial
|
||||||
|
product offering, Product X. That Contributor is then a Commercial
|
||||||
|
Contributor. If that Commercial Contributor then makes performance
|
||||||
|
claims, or offers warranties related to Product X, those performance
|
||||||
|
claims and warranties are such Commercial Contributor's responsibility
|
||||||
|
alone. Under this section, the Commercial Contributor would have to
|
||||||
|
defend claims against the other Contributors related to those performance
|
||||||
|
claims and warranties, and if a court requires any other Contributor to
|
||||||
|
pay any damages as a result, the Commercial Contributor must pay
|
||||||
|
those damages.
|
||||||
|
|
||||||
5. NO WARRANTY
|
5. NO WARRANTY
|
||||||
|
|
||||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
|
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
|
||||||
|
PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS"
|
||||||
|
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
|
||||||
|
IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
|
||||||
|
TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. Each Recipient is solely responsible for determining the
|
||||||
|
appropriateness of using and distributing the Program and assumes all
|
||||||
|
risks associated with its exercise of rights under this Agreement,
|
||||||
|
including but not limited to the risks and costs of program errors,
|
||||||
|
compliance with applicable laws, damage to or loss of data, programs
|
||||||
|
or equipment, and unavailability or interruption of operations.
|
||||||
|
|
||||||
6. DISCLAIMER OF LIABILITY
|
6. DISCLAIMER OF LIABILITY
|
||||||
|
|
||||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
|
||||||
|
PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS
|
||||||
|
SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||||
|
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
|
||||||
|
PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||||
|
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||||
|
ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
|
||||||
|
EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
|
||||||
|
POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
7. GENERAL
|
7. GENERAL
|
||||||
|
|
||||||
If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
|
If any provision of this Agreement is invalid or unenforceable under
|
||||||
|
applicable law, it shall not affect the validity or enforceability of
|
||||||
|
the remainder of the terms of this Agreement, and without further
|
||||||
|
action by the parties hereto, such provision shall be reformed to the
|
||||||
|
minimum extent necessary to make such provision valid and enforceable.
|
||||||
|
|
||||||
If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
|
If Recipient institutes patent litigation against any entity
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that the
|
||||||
|
Program itself (excluding combinations of the Program with other software
|
||||||
|
or hardware) infringes such Recipient's patent(s), then such Recipient's
|
||||||
|
rights granted under Section 2(b) shall terminate as of the date such
|
||||||
|
litigation is filed.
|
||||||
|
|
||||||
All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
|
All Recipient's rights under this Agreement shall terminate if it
|
||||||
|
fails to comply with any of the material terms or conditions of this
|
||||||
|
Agreement and does not cure such failure in a reasonable period of
|
||||||
|
time after becoming aware of such noncompliance. If all Recipient's
|
||||||
|
rights under this Agreement terminate, Recipient agrees to cease use
|
||||||
|
and distribution of the Program as soon as reasonably practicable.
|
||||||
|
However, Recipient's obligations under this Agreement and any licenses
|
||||||
|
granted by Recipient relating to the Program shall continue and survive.
|
||||||
|
|
||||||
Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
|
Everyone is permitted to copy and distribute copies of this Agreement,
|
||||||
|
but in order to avoid inconsistency the Agreement is copyrighted and
|
||||||
|
may only be modified in the following manner. The Agreement Steward
|
||||||
|
reserves the right to publish new versions (including revisions) of
|
||||||
|
this Agreement from time to time. No one other than the Agreement
|
||||||
|
Steward has the right to modify this Agreement. The Eclipse Foundation
|
||||||
|
is the initial Agreement Steward. The Eclipse Foundation may assign the
|
||||||
|
responsibility to serve as the Agreement Steward to a suitable separate
|
||||||
|
entity. Each new version of the Agreement will be given a distinguishing
|
||||||
|
version number. The Program (including Contributions) may always be
|
||||||
|
Distributed subject to the version of the Agreement under which it was
|
||||||
|
received. In addition, after a new version of the Agreement is published,
|
||||||
|
Contributor may elect to Distribute the Program (including its
|
||||||
|
Contributions) under the new version.
|
||||||
|
|
||||||
This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
|
Except as expressly stated in Sections 2(a) and 2(b) above, Recipient
|
||||||
|
receives no rights or licenses to the intellectual property of any
|
||||||
|
Contributor under this Agreement, whether expressly, by implication,
|
||||||
|
estoppel or otherwise. All rights in the Program not expressly granted
|
||||||
|
under this Agreement are reserved. Nothing in this Agreement is intended
|
||||||
|
to be enforceable by any entity that is not a Contributor or Recipient.
|
||||||
|
No third-party beneficiary rights are created under this Agreement.
|
||||||
|
|
||||||
|
Exhibit A - Form of Secondary Licenses Notice
|
||||||
|
|
||||||
|
"This Source Code may also be made available under the following
|
||||||
|
Secondary Licenses when the conditions for such availability set forth
|
||||||
|
in the Eclipse Public License, v. 2.0 are satisfied: {name license(s),
|
||||||
|
version(s), and exceptions or additional permissions here}."
|
||||||
|
|
||||||
|
Simply including a copy of this Agreement, including this Exhibit A
|
||||||
|
is not sufficient to license the Source Code under Secondary Licenses.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular
|
||||||
|
file, then You may include the notice in a location (such as a LICENSE
|
||||||
|
file in a relevant directory) where a recipient would be likely to
|
||||||
|
look for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
|
|||||||
77
vendor/github.com/eclipse/paho.mqtt.golang/NOTICE.md
generated
vendored
Normal file
77
vendor/github.com/eclipse/paho.mqtt.golang/NOTICE.md
generated
vendored
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
# Notices for paho.mqtt.golang
|
||||||
|
|
||||||
|
This content is produced and maintained by the Eclipse Paho project.
|
||||||
|
|
||||||
|
* Project home: https://www.eclipse.org/paho/
|
||||||
|
|
||||||
|
Note that a [separate mqtt v5 client](https://github.com/eclipse/paho.golang) also exists (this is a full rewrite
|
||||||
|
and deliberately incompatible with this library).
|
||||||
|
|
||||||
|
## Trademarks
|
||||||
|
|
||||||
|
Eclipse Mosquitto trademarks of the Eclipse Foundation. Eclipse, and the
|
||||||
|
Eclipse Logo are registered trademarks of the Eclipse Foundation.
|
||||||
|
|
||||||
|
Paho is a trademark of the Eclipse Foundation. Eclipse, and the Eclipse Logo are
|
||||||
|
registered trademarks of the Eclipse Foundation.
|
||||||
|
|
||||||
|
## Copyright
|
||||||
|
|
||||||
|
All content is the property of the respective authors or their employers.
|
||||||
|
For more information regarding authorship of content, please consult the
|
||||||
|
listed source code repository logs.
|
||||||
|
|
||||||
|
## Declared Project Licenses
|
||||||
|
|
||||||
|
This program and the accompanying materials are made available under the terms of the
|
||||||
|
Eclipse Public License v2.0 and Eclipse Distribution License v1.0 which accompany this
|
||||||
|
distribution.
|
||||||
|
|
||||||
|
The Eclipse Public License is available at
|
||||||
|
https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
and the Eclipse Distribution License is available at
|
||||||
|
http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
|
||||||
|
For an explanation of what dual-licensing means to you, see:
|
||||||
|
https://www.eclipse.org/legal/eplfaq.php#DUALLIC
|
||||||
|
|
||||||
|
SPDX-License-Identifier: EPL-2.0 or BSD-3-Clause
|
||||||
|
|
||||||
|
## Source Code
|
||||||
|
|
||||||
|
The project maintains the following source code repositories:
|
||||||
|
|
||||||
|
* https://github.com/eclipse/paho.mqtt.golang
|
||||||
|
|
||||||
|
## Third-party Content
|
||||||
|
|
||||||
|
This project makes use of the follow third party projects.
|
||||||
|
|
||||||
|
Go Programming Language and Standard Library
|
||||||
|
|
||||||
|
* License: BSD-style license (https://golang.org/LICENSE)
|
||||||
|
* Project: https://golang.org/
|
||||||
|
|
||||||
|
Go Networking
|
||||||
|
|
||||||
|
* License: BSD 3-Clause style license and patent grant.
|
||||||
|
* Project: https://cs.opensource.google/go/x/net
|
||||||
|
|
||||||
|
Go Sync
|
||||||
|
|
||||||
|
* License: BSD 3-Clause style license and patent grant.
|
||||||
|
* Project: https://cs.opensource.google/go/x/sync/
|
||||||
|
|
||||||
|
Gorilla Websockets v1.4.2
|
||||||
|
|
||||||
|
* License: BSD 2-Clause "Simplified" License
|
||||||
|
* Project: https://github.com/gorilla/websocket
|
||||||
|
|
||||||
|
## Cryptography
|
||||||
|
|
||||||
|
Content may contain encryption software. The country in which you are currently
|
||||||
|
may have restrictions on the import, possession, and use, and/or re-export to
|
||||||
|
another country, of encryption software. BEFORE using any encryption software,
|
||||||
|
please check the country's laws, regulations and policies concerning the import,
|
||||||
|
possession, or use, and re-export of encryption software, to see if this is
|
||||||
|
permitted.
|
||||||
163
vendor/github.com/eclipse/paho.mqtt.golang/README.md
generated
vendored
163
vendor/github.com/eclipse/paho.mqtt.golang/README.md
generated
vendored
@@ -1,32 +1,47 @@
|
|||||||
|
|
||||||
[](https://godoc.org/github.com/eclipse/paho.mqtt.golang)
|
[](https://pkg.go.dev/github.com/eclipse/paho.mqtt.golang)
|
||||||
[](https://goreportcard.com/report/github.com/eclipse/paho.mqtt.golang)
|
[](https://goreportcard.com/report/github.com/eclipse/paho.mqtt.golang)
|
||||||
|
|
||||||
Eclipse Paho MQTT Go client
|
Eclipse Paho MQTT Go client
|
||||||
===========================
|
===========================
|
||||||
|
|
||||||
|
|
||||||
This repository contains the source code for the [Eclipse Paho](http://eclipse.org/paho) MQTT Go client library.
|
This repository contains the source code for the [Eclipse Paho](https://eclipse.org/paho) MQTT 3.1/3.11 Go client library.
|
||||||
|
|
||||||
This code builds a library which enable applications to connect to an [MQTT](http://mqtt.org) broker to publish messages, and to subscribe to topics and receive published messages.
|
This code builds a library which enable applications to connect to an [MQTT](https://mqtt.org) broker to publish
|
||||||
|
messages, and to subscribe to topics and receive published messages.
|
||||||
|
|
||||||
This library supports a fully asynchronous mode of operation.
|
This library supports a fully asynchronous mode of operation.
|
||||||
|
|
||||||
|
A client supporting MQTT V5 is [also available](https://github.com/eclipse/paho.golang).
|
||||||
|
|
||||||
Installation and Build
|
Installation and Build
|
||||||
----------------------
|
----------------------
|
||||||
|
|
||||||
This client is designed to work with the standard Go tools, so installation is as easy as:
|
The process depends upon whether you are using [modules](https://golang.org/ref/mod) (recommended) or `GOPATH`.
|
||||||
|
|
||||||
|
#### Modules
|
||||||
|
|
||||||
|
If you are using [modules](https://blog.golang.org/using-go-modules) then `import "github.com/eclipse/paho.mqtt.golang"`
|
||||||
|
and start using it. The necessary packages will be download automatically when you run `go build`.
|
||||||
|
|
||||||
|
Note that the latest release will be downloaded and changes may have been made since the release. If you have
|
||||||
|
encountered an issue, or wish to try the latest code for another reason, then run
|
||||||
|
`go get github.com/eclipse/paho.mqtt.golang@master` to get the latest commit.
|
||||||
|
|
||||||
|
#### GOPATH
|
||||||
|
|
||||||
|
Installation is as easy as:
|
||||||
|
|
||||||
```
|
```
|
||||||
go get github.com/eclipse/paho.mqtt.golang
|
go get github.com/eclipse/paho.mqtt.golang
|
||||||
```
|
```
|
||||||
|
|
||||||
The client depends on Google's [websockets](https://godoc.org/golang.org/x/net/websocket) and [proxy](https://godoc.org/golang.org/x/net/proxy) package,
|
The client depends on Google's [proxy](https://godoc.org/golang.org/x/net/proxy) package and the
|
||||||
also easily installed with the commands:
|
[websockets](https://godoc.org/github.com/gorilla/websocket) package, also easily installed with the commands:
|
||||||
|
|
||||||
```
|
```
|
||||||
go get golang.org/x/net/websocket
|
go get github.com/gorilla/websocket
|
||||||
go get golang.org/x/net/proxy
|
go get golang.org/x/net/proxy
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -35,31 +50,147 @@ Usage and API
|
|||||||
-------------
|
-------------
|
||||||
|
|
||||||
Detailed API documentation is available by using to godoc tool, or can be browsed online
|
Detailed API documentation is available by using to godoc tool, or can be browsed online
|
||||||
using the [godoc.org](http://godoc.org/github.com/eclipse/paho.mqtt.golang) service.
|
using the [pkg.go.dev](https://pkg.go.dev/github.com/eclipse/paho.mqtt.golang) service.
|
||||||
|
|
||||||
Make use of the library by importing it in your Go client source code. For example,
|
|
||||||
```
|
|
||||||
import "github.com/eclipse/paho.mqtt.golang"
|
|
||||||
```
|
|
||||||
|
|
||||||
Samples are available in the `cmd` directory for reference.
|
Samples are available in the `cmd` directory for reference.
|
||||||
|
|
||||||
|
Note:
|
||||||
|
|
||||||
Runtime tracing
|
The library also supports using MQTT over websockets by using the `ws://` (unsecure) or `wss://` (secure) prefix in the
|
||||||
|
URI. If the client is running behind a corporate http/https proxy then the following environment variables `HTTP_PROXY`,
|
||||||
|
`HTTPS_PROXY` and `NO_PROXY` are taken into account when establishing the connection.
|
||||||
|
|
||||||
|
Troubleshooting
|
||||||
---------------
|
---------------
|
||||||
|
|
||||||
Tracing is enabled by assigning logs (from the Go log package) to the logging endpoints, ERROR, CRITICAL, WARN and DEBUG
|
If you are new to MQTT and your application is not working as expected reviewing the
|
||||||
|
[MQTT specification](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html), which this library implements,
|
||||||
|
is a good first step. [MQTT.org](https://mqtt.org) has some [good resources](https://mqtt.org/getting-started/) that answer many
|
||||||
|
common questions.
|
||||||
|
|
||||||
|
### Error Handling
|
||||||
|
|
||||||
|
The asynchronous nature of this library makes it easy to forget to check for errors. Consider using a go routine to
|
||||||
|
log these:
|
||||||
|
|
||||||
|
```go
|
||||||
|
t := client.Publish("topic", qos, retained, msg)
|
||||||
|
go func() {
|
||||||
|
_ = t.Wait() // Can also use '<-t.Done()' in releases > 1.2.0
|
||||||
|
if t.Error() != nil {
|
||||||
|
log.Error(t.Error()) // Use your preferred logging technique (or just fmt.Printf)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Logging
|
||||||
|
|
||||||
|
If you are encountering issues then enabling logging, both within this library and on your broker, is a good way to
|
||||||
|
begin troubleshooting. This library can produce various levels of log by assigning the logging endpoints, ERROR,
|
||||||
|
CRITICAL, WARN and DEBUG. For example:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func main() {
|
||||||
|
mqtt.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
|
||||||
|
mqtt.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0)
|
||||||
|
mqtt.WARN = log.New(os.Stdout, "[WARN] ", 0)
|
||||||
|
mqtt.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)
|
||||||
|
|
||||||
|
// Connect, Subscribe, Publish etc..
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common Problems
|
||||||
|
|
||||||
|
* Seemingly random disconnections may be caused by another client connecting to the broker with the same client
|
||||||
|
identifier; this is as per the [spec](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800405).
|
||||||
|
* Unless ordered delivery of messages is essential (and you have configured your broker to support this e.g.
|
||||||
|
`max_inflight_messages=1` in mosquitto) then set `ClientOptions.SetOrderMatters(false)`. Doing so will avoid the
|
||||||
|
below issue (deadlocks due to blocking message handlers).
|
||||||
|
* A `MessageHandler` (called when a new message is received) must not block (unless
|
||||||
|
`ClientOptions.SetOrderMatters(false)` set). If you wish to perform a long-running task, or publish a message, then
|
||||||
|
please use a go routine (blocking in the handler is a common cause of unexpected `pingresp
|
||||||
|
not received, disconnecting` errors).
|
||||||
|
* When QOS1+ subscriptions have been created previously and you connect with `CleanSession` set to false it is possible
|
||||||
|
that the broker will deliver retained messages before `Subscribe` can be called. To process these messages either
|
||||||
|
configure a handler with `AddRoute` or set a `DefaultPublishHandler`. If there is no handler (or `DefaultPublishHandler`)
|
||||||
|
then inbound messages will not be acknowledged. Adding a handler (even if it's `opts.SetDefaultPublishHandler(func(mqtt.Client, mqtt.Message) {})`)
|
||||||
|
is highly recommended to avoid inadvertently hitting inflight message limits.
|
||||||
|
* Loss of network connectivity may not be detected immediately. If this is an issue then consider setting
|
||||||
|
`ClientOptions.KeepAlive` (sends regular messages to check the link is active).
|
||||||
|
* Reusing a `Client` is not completely safe. After calling `Disconnect` please create a new Client (`NewClient()`) rather
|
||||||
|
than attempting to reuse the existing one (note that features such as `SetAutoReconnect` mean this is rarely necessary).
|
||||||
|
* Brokers offer many configuration options; some settings may lead to unexpected results.
|
||||||
|
* Publish tokens will complete if the connection is lost and re-established using the default
|
||||||
|
options.SetAutoReconnect(true) functionality (token.Error() will return nil). Attempts will be made to re-deliver the
|
||||||
|
message but there is currently no easy way know when such messages are delivered.
|
||||||
|
|
||||||
|
If using Mosquitto then there are a range of fairly common issues:
|
||||||
|
* `listener` - By default [Mosquitto v2+](https://mosquitto.org/documentation/migrating-to-2-0/) listens on loopback
|
||||||
|
interfaces only (meaning it will only accept connections made from the computer its running on).
|
||||||
|
* `max_inflight_messages` - Unless this is set to 1 mosquitto does not guarantee ordered delivery of messages.
|
||||||
|
* `max_queued_messages` / `max_queued_bytes` - These impose limits on the number/size of queued messages. The defaults
|
||||||
|
may lead to messages being silently dropped.
|
||||||
|
* `persistence` - Defaults to false (messages will not survive a broker restart)
|
||||||
|
* `max_keepalive` - defaults to 65535 and, from version 2.0.12, `SetKeepAlive(0)` will result in a rejected connection
|
||||||
|
by default.
|
||||||
|
|
||||||
Reporting bugs
|
Reporting bugs
|
||||||
--------------
|
--------------
|
||||||
|
|
||||||
Please report bugs by raising issues for this project in github https://github.com/eclipse/paho.mqtt.golang/issues
|
Please report bugs by raising issues for this project in github https://github.com/eclipse/paho.mqtt.golang/issues
|
||||||
|
|
||||||
|
A limited number of contributors monitor the issues section so if you have a general question please see the
|
||||||
|
resources in the [more information](#more-information) section for help.
|
||||||
|
|
||||||
|
We welcome bug reports, but it is important they are actionable. A significant percentage of issues reported are not
|
||||||
|
resolved due to a lack of information. If we cannot replicate the problem then it is unlikely we will be able to fix it.
|
||||||
|
The information required will vary from issue to issue but almost all bug reports would be expected to include:
|
||||||
|
|
||||||
|
* Which version of the package you are using (tag or commit - this should be in your `go.mod` file)
|
||||||
|
* A full, clear, description of the problem (detail what you are expecting vs what actually happens).
|
||||||
|
* Configuration information (code showing how you connect, please include all references to `ClientOption`)
|
||||||
|
* Broker details (name and version).
|
||||||
|
|
||||||
|
If at all possible please also include:
|
||||||
|
* Details of your attempts to resolve the issue (what have you tried, what worked, what did not).
|
||||||
|
* A [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Providing an example
|
||||||
|
is the best way to demonstrate the issue you are facing; it is important this includes all relevant information
|
||||||
|
(including broker configuration). Docker (see `cmd/docker`) makes it relatively simple to provide a working end-to-end
|
||||||
|
example.
|
||||||
|
* Broker logs covering the period the issue occurred.
|
||||||
|
* [Application Logs](#logging) covering the period the issue occurred. Unless you have isolated the root cause of the
|
||||||
|
issue please include a link to a full log (including data from well before the problem arose).
|
||||||
|
|
||||||
|
It is important to remember that this library does not stand alone; it communicates with a broker and any issues you are
|
||||||
|
seeing may be due to:
|
||||||
|
|
||||||
|
* Bugs in your code.
|
||||||
|
* Bugs in this library.
|
||||||
|
* The broker configuration.
|
||||||
|
* Bugs in the broker.
|
||||||
|
* Issues with whatever you are communicating with.
|
||||||
|
|
||||||
|
When submitting an issue, please ensure that you provide sufficient details to enable us to eliminate causes outside of
|
||||||
|
this library.
|
||||||
|
|
||||||
|
Contributing
|
||||||
|
------------
|
||||||
|
|
||||||
|
We welcome pull requests but before your contribution can be accepted by the project, you need to create and
|
||||||
|
electronically sign the Eclipse Contributor Agreement (ECA) and sign off on the Eclipse Foundation Certificate of Origin.
|
||||||
|
|
||||||
|
More information is available in the
|
||||||
|
[Eclipse Development Resources](http://wiki.eclipse.org/Development_Resources/Contributing_via_Git); please take special
|
||||||
|
note of the requirement that the commit record contain a "Signed-off-by" entry.
|
||||||
|
|
||||||
More information
|
More information
|
||||||
----------------
|
----------------
|
||||||
|
|
||||||
|
[Stack Overflow](https://stackoverflow.com/questions/tagged/mqtt+go) has a range questions/answers covering a range of
|
||||||
|
common issues (both relating to use of this library and MQTT in general). This is the best place to ask general questions
|
||||||
|
(including those relating to the use of this library).
|
||||||
|
|
||||||
Discussion of the Paho clients takes place on the [Eclipse paho-dev mailing list](https://dev.eclipse.org/mailman/listinfo/paho-dev).
|
Discussion of the Paho clients takes place on the [Eclipse paho-dev mailing list](https://dev.eclipse.org/mailman/listinfo/paho-dev).
|
||||||
|
|
||||||
General questions about the MQTT protocol are discussed in the [MQTT Google Group](https://groups.google.com/forum/?hl=en-US&fromgroups#!forum/mqtt).
|
General questions about the MQTT protocol are discussed in the [MQTT Google Group](https://groups.google.com/forum/?hl=en-US&fromgroups#!forum/mqtt).
|
||||||
|
|||||||
41
vendor/github.com/eclipse/paho.mqtt.golang/about.html
generated
vendored
41
vendor/github.com/eclipse/paho.mqtt.golang/about.html
generated
vendored
@@ -1,41 +0,0 @@
|
|||||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
|
||||||
<html xmlns="http://www.w3.org/1999/xhtml"><head>
|
|
||||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
|
||||||
<title>About</title>
|
|
||||||
</head>
|
|
||||||
<body lang="EN-US">
|
|
||||||
<h2>About This Content</h2>
|
|
||||||
|
|
||||||
<p><em>December 9, 2013</em></p>
|
|
||||||
<h3>License</h3>
|
|
||||||
|
|
||||||
<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
|
|
||||||
indicated below, the Content is provided to you under the terms and conditions of the
|
|
||||||
Eclipse Public License Version 1.0 ("EPL") and Eclipse Distribution License Version 1.0 ("EDL").
|
|
||||||
A copy of the EPL is available at
|
|
||||||
<a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>
|
|
||||||
and a copy of the EDL is available at
|
|
||||||
<a href="http://www.eclipse.org/org/documents/edl-v10.php">http://www.eclipse.org/org/documents/edl-v10.php</a>.
|
|
||||||
For purposes of the EPL, "Program" will mean the Content.</p>
|
|
||||||
|
|
||||||
<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
|
|
||||||
being redistributed by another party ("Redistributor") and different terms and conditions may
|
|
||||||
apply to your use of any object code in the Content. Check the Redistributor's license that was
|
|
||||||
provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
|
|
||||||
indicated below, the terms and conditions of the EPL still apply to any source code in the Content
|
|
||||||
and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
|
|
||||||
|
|
||||||
|
|
||||||
<h3>Third Party Content</h3>
|
|
||||||
<p>The Content includes items that have been sourced from third parties as set out below. If you
|
|
||||||
did not receive this Content directly from the Eclipse Foundation, the following is provided
|
|
||||||
for informational purposes only, and you should look to the Redistributor's license for
|
|
||||||
terms and conditions of use.</p>
|
|
||||||
<p><em>
|
|
||||||
<strong>None</strong> <br><br>
|
|
||||||
<br><br>
|
|
||||||
</em></p>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
</body></html>
|
|
||||||
104
vendor/github.com/eclipse/paho.mqtt.golang/backoff.go
generated
vendored
Normal file
104
vendor/github.com/eclipse/paho.mqtt.golang/backoff.go
generated
vendored
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Matt Brittan
|
||||||
|
* Daichi Tomaru
|
||||||
|
*/
|
||||||
|
|
||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Controller for sleep with backoff when the client attempts reconnection
|
||||||
|
// It has statuses for each situations cause reconnection.
|
||||||
|
type backoffController struct {
|
||||||
|
sync.RWMutex
|
||||||
|
statusMap map[string]*backoffStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
type backoffStatus struct {
|
||||||
|
lastSleepPeriod time.Duration
|
||||||
|
lastErrorTime time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func newBackoffController() *backoffController {
|
||||||
|
return &backoffController{
|
||||||
|
statusMap: map[string]*backoffStatus{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate next sleep period from the specified parameters.
|
||||||
|
// Returned values are next sleep period and whether the error situation is continual.
|
||||||
|
// If connection errors continuouslly occurs, its sleep period is exponentially increased.
|
||||||
|
// Also if there is a lot of time between last and this error, sleep period is initialized.
|
||||||
|
func (b *backoffController) getBackoffSleepTime(
|
||||||
|
situation string, initSleepPeriod time.Duration, maxSleepPeriod time.Duration, processTime time.Duration, skipFirst bool,
|
||||||
|
) (time.Duration, bool) {
|
||||||
|
// Decide first sleep time if the situation is not continual.
|
||||||
|
var firstProcess = func(status *backoffStatus, init time.Duration, skip bool) (time.Duration, bool) {
|
||||||
|
if skip {
|
||||||
|
status.lastSleepPeriod = 0
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
status.lastSleepPeriod = init
|
||||||
|
return init, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prioritize maxSleep.
|
||||||
|
if initSleepPeriod > maxSleepPeriod {
|
||||||
|
initSleepPeriod = maxSleepPeriod
|
||||||
|
}
|
||||||
|
b.Lock()
|
||||||
|
defer b.Unlock()
|
||||||
|
|
||||||
|
status, exist := b.statusMap[situation]
|
||||||
|
if !exist {
|
||||||
|
b.statusMap[situation] = &backoffStatus{initSleepPeriod, time.Now()}
|
||||||
|
return firstProcess(b.statusMap[situation], initSleepPeriod, skipFirst)
|
||||||
|
}
|
||||||
|
|
||||||
|
oldTime := status.lastErrorTime
|
||||||
|
status.lastErrorTime = time.Now()
|
||||||
|
|
||||||
|
// When there is a lot of time between last and this error, sleep period is initialized.
|
||||||
|
if status.lastErrorTime.Sub(oldTime) > (processTime * 2 + status.lastSleepPeriod) {
|
||||||
|
return firstProcess(status, initSleepPeriod, skipFirst)
|
||||||
|
}
|
||||||
|
|
||||||
|
if status.lastSleepPeriod == 0 {
|
||||||
|
status.lastSleepPeriod = initSleepPeriod
|
||||||
|
return initSleepPeriod, true
|
||||||
|
}
|
||||||
|
|
||||||
|
if nextSleepPeriod := status.lastSleepPeriod * 2; nextSleepPeriod <= maxSleepPeriod {
|
||||||
|
status.lastSleepPeriod = nextSleepPeriod
|
||||||
|
} else {
|
||||||
|
status.lastSleepPeriod = maxSleepPeriod
|
||||||
|
}
|
||||||
|
|
||||||
|
return status.lastSleepPeriod, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute sleep the time returned from getBackoffSleepTime.
|
||||||
|
func (b *backoffController) sleepWithBackoff(
|
||||||
|
situation string, initSleepPeriod time.Duration, maxSleepPeriod time.Duration, processTime time.Duration, skipFirst bool,
|
||||||
|
) (time.Duration, bool) {
|
||||||
|
sleep, isFirst := b.getBackoffSleepTime(situation, initSleepPeriod, maxSleepPeriod, processTime, skipFirst)
|
||||||
|
if sleep != 0 {
|
||||||
|
time.Sleep(sleep)
|
||||||
|
}
|
||||||
|
return sleep, isFirst
|
||||||
|
}
|
||||||
1264
vendor/github.com/eclipse/paho.mqtt.golang/client.go
generated
vendored
1264
vendor/github.com/eclipse/paho.mqtt.golang/client.go
generated
vendored
File diff suppressed because it is too large
Load Diff
13
vendor/github.com/eclipse/paho.mqtt.golang/components.go
generated
vendored
13
vendor/github.com/eclipse/paho.mqtt.golang/components.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -28,4 +32,5 @@ const (
|
|||||||
TST component = "[test] "
|
TST component = "[test] "
|
||||||
STA component = "[state] "
|
STA component = "[state] "
|
||||||
ERR component = "[error] "
|
ERR component = "[error] "
|
||||||
|
ROU component = "[router] "
|
||||||
)
|
)
|
||||||
|
|||||||
70
vendor/github.com/eclipse/paho.mqtt.golang/epl-v10
generated
vendored
70
vendor/github.com/eclipse/paho.mqtt.golang/epl-v10
generated
vendored
@@ -1,70 +0,0 @@
|
|||||||
Eclipse Public License - v 1.0
|
|
||||||
|
|
||||||
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
|
|
||||||
|
|
||||||
1. DEFINITIONS
|
|
||||||
|
|
||||||
"Contribution" means:
|
|
||||||
|
|
||||||
a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
|
|
||||||
b) in the case of each subsequent Contributor:
|
|
||||||
i) changes to the Program, and
|
|
||||||
ii) additions to the Program;
|
|
||||||
where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
|
|
||||||
"Contributor" means any person or entity that distributes the Program.
|
|
||||||
|
|
||||||
"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
|
|
||||||
|
|
||||||
"Program" means the Contributions distributed in accordance with this Agreement.
|
|
||||||
|
|
||||||
"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
|
|
||||||
|
|
||||||
2. GRANT OF RIGHTS
|
|
||||||
|
|
||||||
a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
|
|
||||||
b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
|
|
||||||
c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
|
|
||||||
d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
|
|
||||||
3. REQUIREMENTS
|
|
||||||
|
|
||||||
A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
|
|
||||||
|
|
||||||
a) it complies with the terms and conditions of this Agreement; and
|
|
||||||
b) its license agreement:
|
|
||||||
i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
|
|
||||||
ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
|
|
||||||
iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
|
|
||||||
iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
|
|
||||||
When the Program is made available in source code form:
|
|
||||||
|
|
||||||
a) it must be made available under this Agreement; and
|
|
||||||
b) a copy of this Agreement must be included with each copy of the Program.
|
|
||||||
Contributors may not remove or alter any copyright notices contained within the Program.
|
|
||||||
|
|
||||||
Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
|
|
||||||
|
|
||||||
4. COMMERCIAL DISTRIBUTION
|
|
||||||
|
|
||||||
Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
|
|
||||||
|
|
||||||
For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
|
|
||||||
|
|
||||||
5. NO WARRANTY
|
|
||||||
|
|
||||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
|
|
||||||
|
|
||||||
6. DISCLAIMER OF LIABILITY
|
|
||||||
|
|
||||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
|
||||||
7. GENERAL
|
|
||||||
|
|
||||||
If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
|
|
||||||
|
|
||||||
If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
|
|
||||||
|
|
||||||
All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
|
|
||||||
|
|
||||||
Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
|
|
||||||
|
|
||||||
This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
|
|
||||||
277
vendor/github.com/eclipse/paho.mqtt.golang/epl-v20
generated
vendored
Normal file
277
vendor/github.com/eclipse/paho.mqtt.golang/epl-v20
generated
vendored
Normal file
@@ -0,0 +1,277 @@
|
|||||||
|
Eclipse Public License - v 2.0
|
||||||
|
|
||||||
|
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
|
||||||
|
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
|
||||||
|
OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
|
||||||
|
|
||||||
|
1. DEFINITIONS
|
||||||
|
|
||||||
|
"Contribution" means:
|
||||||
|
|
||||||
|
a) in the case of the initial Contributor, the initial content
|
||||||
|
Distributed under this Agreement, and
|
||||||
|
|
||||||
|
b) in the case of each subsequent Contributor:
|
||||||
|
i) changes to the Program, and
|
||||||
|
ii) additions to the Program;
|
||||||
|
where such changes and/or additions to the Program originate from
|
||||||
|
and are Distributed by that particular Contributor. A Contribution
|
||||||
|
"originates" from a Contributor if it was added to the Program by
|
||||||
|
such Contributor itself or anyone acting on such Contributor's behalf.
|
||||||
|
Contributions do not include changes or additions to the Program that
|
||||||
|
are not Modified Works.
|
||||||
|
|
||||||
|
"Contributor" means any person or entity that Distributes the Program.
|
||||||
|
|
||||||
|
"Licensed Patents" mean patent claims licensable by a Contributor which
|
||||||
|
are necessarily infringed by the use or sale of its Contribution alone
|
||||||
|
or when combined with the Program.
|
||||||
|
|
||||||
|
"Program" means the Contributions Distributed in accordance with this
|
||||||
|
Agreement.
|
||||||
|
|
||||||
|
"Recipient" means anyone who receives the Program under this Agreement
|
||||||
|
or any Secondary License (as applicable), including Contributors.
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source Code or other
|
||||||
|
form, that is based on (or derived from) the Program and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship.
|
||||||
|
|
||||||
|
"Modified Works" shall mean any work in Source Code or other form that
|
||||||
|
results from an addition to, deletion from, or modification of the
|
||||||
|
contents of the Program, including, for purposes of clarity any new file
|
||||||
|
in Source Code form that contains any contents of the Program. Modified
|
||||||
|
Works shall not include works that contain only declarations,
|
||||||
|
interfaces, types, classes, structures, or files of the Program solely
|
||||||
|
in each case in order to link to, bind by name, or subclass the Program
|
||||||
|
or Modified Works thereof.
|
||||||
|
|
||||||
|
"Distribute" means the acts of a) distributing or b) making available
|
||||||
|
in any manner that enables the transfer of a copy.
|
||||||
|
|
||||||
|
"Source Code" means the form of a Program preferred for making
|
||||||
|
modifications, including but not limited to software source code,
|
||||||
|
documentation source, and configuration files.
|
||||||
|
|
||||||
|
"Secondary License" means either the GNU General Public License,
|
||||||
|
Version 2.0, or any later versions of that license, including any
|
||||||
|
exceptions or additional permissions as identified by the initial
|
||||||
|
Contributor.
|
||||||
|
|
||||||
|
2. GRANT OF RIGHTS
|
||||||
|
|
||||||
|
a) Subject to the terms of this Agreement, each Contributor hereby
|
||||||
|
grants Recipient a non-exclusive, worldwide, royalty-free copyright
|
||||||
|
license to reproduce, prepare Derivative Works of, publicly display,
|
||||||
|
publicly perform, Distribute and sublicense the Contribution of such
|
||||||
|
Contributor, if any, and such Derivative Works.
|
||||||
|
|
||||||
|
b) Subject to the terms of this Agreement, each Contributor hereby
|
||||||
|
grants Recipient a non-exclusive, worldwide, royalty-free patent
|
||||||
|
license under Licensed Patents to make, use, sell, offer to sell,
|
||||||
|
import and otherwise transfer the Contribution of such Contributor,
|
||||||
|
if any, in Source Code or other form. This patent license shall
|
||||||
|
apply to the combination of the Contribution and the Program if, at
|
||||||
|
the time the Contribution is added by the Contributor, such addition
|
||||||
|
of the Contribution causes such combination to be covered by the
|
||||||
|
Licensed Patents. The patent license shall not apply to any other
|
||||||
|
combinations which include the Contribution. No hardware per se is
|
||||||
|
licensed hereunder.
|
||||||
|
|
||||||
|
c) Recipient understands that although each Contributor grants the
|
||||||
|
licenses to its Contributions set forth herein, no assurances are
|
||||||
|
provided by any Contributor that the Program does not infringe the
|
||||||
|
patent or other intellectual property rights of any other entity.
|
||||||
|
Each Contributor disclaims any liability to Recipient for claims
|
||||||
|
brought by any other entity based on infringement of intellectual
|
||||||
|
property rights or otherwise. As a condition to exercising the
|
||||||
|
rights and licenses granted hereunder, each Recipient hereby
|
||||||
|
assumes sole responsibility to secure any other intellectual
|
||||||
|
property rights needed, if any. For example, if a third party
|
||||||
|
patent license is required to allow Recipient to Distribute the
|
||||||
|
Program, it is Recipient's responsibility to acquire that license
|
||||||
|
before distributing the Program.
|
||||||
|
|
||||||
|
d) Each Contributor represents that to its knowledge it has
|
||||||
|
sufficient copyright rights in its Contribution, if any, to grant
|
||||||
|
the copyright license set forth in this Agreement.
|
||||||
|
|
||||||
|
e) Notwithstanding the terms of any Secondary License, no
|
||||||
|
Contributor makes additional grants to any Recipient (other than
|
||||||
|
those set forth in this Agreement) as a result of such Recipient's
|
||||||
|
receipt of the Program under the terms of a Secondary License
|
||||||
|
(if permitted under the terms of Section 3).
|
||||||
|
|
||||||
|
3. REQUIREMENTS
|
||||||
|
|
||||||
|
3.1 If a Contributor Distributes the Program in any form, then:
|
||||||
|
|
||||||
|
a) the Program must also be made available as Source Code, in
|
||||||
|
accordance with section 3.2, and the Contributor must accompany
|
||||||
|
the Program with a statement that the Source Code for the Program
|
||||||
|
is available under this Agreement, and informs Recipients how to
|
||||||
|
obtain it in a reasonable manner on or through a medium customarily
|
||||||
|
used for software exchange; and
|
||||||
|
|
||||||
|
b) the Contributor may Distribute the Program under a license
|
||||||
|
different than this Agreement, provided that such license:
|
||||||
|
i) effectively disclaims on behalf of all other Contributors all
|
||||||
|
warranties and conditions, express and implied, including
|
||||||
|
warranties or conditions of title and non-infringement, and
|
||||||
|
implied warranties or conditions of merchantability and fitness
|
||||||
|
for a particular purpose;
|
||||||
|
|
||||||
|
ii) effectively excludes on behalf of all other Contributors all
|
||||||
|
liability for damages, including direct, indirect, special,
|
||||||
|
incidental and consequential damages, such as lost profits;
|
||||||
|
|
||||||
|
iii) does not attempt to limit or alter the recipients' rights
|
||||||
|
in the Source Code under section 3.2; and
|
||||||
|
|
||||||
|
iv) requires any subsequent distribution of the Program by any
|
||||||
|
party to be under a license that satisfies the requirements
|
||||||
|
of this section 3.
|
||||||
|
|
||||||
|
3.2 When the Program is Distributed as Source Code:
|
||||||
|
|
||||||
|
a) it must be made available under this Agreement, or if the
|
||||||
|
Program (i) is combined with other material in a separate file or
|
||||||
|
files made available under a Secondary License, and (ii) the initial
|
||||||
|
Contributor attached to the Source Code the notice described in
|
||||||
|
Exhibit A of this Agreement, then the Program may be made available
|
||||||
|
under the terms of such Secondary Licenses, and
|
||||||
|
|
||||||
|
b) a copy of this Agreement must be included with each copy of
|
||||||
|
the Program.
|
||||||
|
|
||||||
|
3.3 Contributors may not remove or alter any copyright, patent,
|
||||||
|
trademark, attribution notices, disclaimers of warranty, or limitations
|
||||||
|
of liability ("notices") contained within the Program from any copy of
|
||||||
|
the Program which they Distribute, provided that Contributors may add
|
||||||
|
their own appropriate notices.
|
||||||
|
|
||||||
|
4. COMMERCIAL DISTRIBUTION
|
||||||
|
|
||||||
|
Commercial distributors of software may accept certain responsibilities
|
||||||
|
with respect to end users, business partners and the like. While this
|
||||||
|
license is intended to facilitate the commercial use of the Program,
|
||||||
|
the Contributor who includes the Program in a commercial product
|
||||||
|
offering should do so in a manner which does not create potential
|
||||||
|
liability for other Contributors. Therefore, if a Contributor includes
|
||||||
|
the Program in a commercial product offering, such Contributor
|
||||||
|
("Commercial Contributor") hereby agrees to defend and indemnify every
|
||||||
|
other Contributor ("Indemnified Contributor") against any losses,
|
||||||
|
damages and costs (collectively "Losses") arising from claims, lawsuits
|
||||||
|
and other legal actions brought by a third party against the Indemnified
|
||||||
|
Contributor to the extent caused by the acts or omissions of such
|
||||||
|
Commercial Contributor in connection with its distribution of the Program
|
||||||
|
in a commercial product offering. The obligations in this section do not
|
||||||
|
apply to any claims or Losses relating to any actual or alleged
|
||||||
|
intellectual property infringement. In order to qualify, an Indemnified
|
||||||
|
Contributor must: a) promptly notify the Commercial Contributor in
|
||||||
|
writing of such claim, and b) allow the Commercial Contributor to control,
|
||||||
|
and cooperate with the Commercial Contributor in, the defense and any
|
||||||
|
related settlement negotiations. The Indemnified Contributor may
|
||||||
|
participate in any such claim at its own expense.
|
||||||
|
|
||||||
|
For example, a Contributor might include the Program in a commercial
|
||||||
|
product offering, Product X. That Contributor is then a Commercial
|
||||||
|
Contributor. If that Commercial Contributor then makes performance
|
||||||
|
claims, or offers warranties related to Product X, those performance
|
||||||
|
claims and warranties are such Commercial Contributor's responsibility
|
||||||
|
alone. Under this section, the Commercial Contributor would have to
|
||||||
|
defend claims against the other Contributors related to those performance
|
||||||
|
claims and warranties, and if a court requires any other Contributor to
|
||||||
|
pay any damages as a result, the Commercial Contributor must pay
|
||||||
|
those damages.
|
||||||
|
|
||||||
|
5. NO WARRANTY
|
||||||
|
|
||||||
|
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
|
||||||
|
PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS"
|
||||||
|
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
|
||||||
|
IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
|
||||||
|
TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. Each Recipient is solely responsible for determining the
|
||||||
|
appropriateness of using and distributing the Program and assumes all
|
||||||
|
risks associated with its exercise of rights under this Agreement,
|
||||||
|
including but not limited to the risks and costs of program errors,
|
||||||
|
compliance with applicable laws, damage to or loss of data, programs
|
||||||
|
or equipment, and unavailability or interruption of operations.
|
||||||
|
|
||||||
|
6. DISCLAIMER OF LIABILITY
|
||||||
|
|
||||||
|
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
|
||||||
|
PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS
|
||||||
|
SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||||
|
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
|
||||||
|
PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||||
|
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||||
|
ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
|
||||||
|
EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
|
||||||
|
POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
7. GENERAL
|
||||||
|
|
||||||
|
If any provision of this Agreement is invalid or unenforceable under
|
||||||
|
applicable law, it shall not affect the validity or enforceability of
|
||||||
|
the remainder of the terms of this Agreement, and without further
|
||||||
|
action by the parties hereto, such provision shall be reformed to the
|
||||||
|
minimum extent necessary to make such provision valid and enforceable.
|
||||||
|
|
||||||
|
If Recipient institutes patent litigation against any entity
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that the
|
||||||
|
Program itself (excluding combinations of the Program with other software
|
||||||
|
or hardware) infringes such Recipient's patent(s), then such Recipient's
|
||||||
|
rights granted under Section 2(b) shall terminate as of the date such
|
||||||
|
litigation is filed.
|
||||||
|
|
||||||
|
All Recipient's rights under this Agreement shall terminate if it
|
||||||
|
fails to comply with any of the material terms or conditions of this
|
||||||
|
Agreement and does not cure such failure in a reasonable period of
|
||||||
|
time after becoming aware of such noncompliance. If all Recipient's
|
||||||
|
rights under this Agreement terminate, Recipient agrees to cease use
|
||||||
|
and distribution of the Program as soon as reasonably practicable.
|
||||||
|
However, Recipient's obligations under this Agreement and any licenses
|
||||||
|
granted by Recipient relating to the Program shall continue and survive.
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute copies of this Agreement,
|
||||||
|
but in order to avoid inconsistency the Agreement is copyrighted and
|
||||||
|
may only be modified in the following manner. The Agreement Steward
|
||||||
|
reserves the right to publish new versions (including revisions) of
|
||||||
|
this Agreement from time to time. No one other than the Agreement
|
||||||
|
Steward has the right to modify this Agreement. The Eclipse Foundation
|
||||||
|
is the initial Agreement Steward. The Eclipse Foundation may assign the
|
||||||
|
responsibility to serve as the Agreement Steward to a suitable separate
|
||||||
|
entity. Each new version of the Agreement will be given a distinguishing
|
||||||
|
version number. The Program (including Contributions) may always be
|
||||||
|
Distributed subject to the version of the Agreement under which it was
|
||||||
|
received. In addition, after a new version of the Agreement is published,
|
||||||
|
Contributor may elect to Distribute the Program (including its
|
||||||
|
Contributions) under the new version.
|
||||||
|
|
||||||
|
Except as expressly stated in Sections 2(a) and 2(b) above, Recipient
|
||||||
|
receives no rights or licenses to the intellectual property of any
|
||||||
|
Contributor under this Agreement, whether expressly, by implication,
|
||||||
|
estoppel or otherwise. All rights in the Program not expressly granted
|
||||||
|
under this Agreement are reserved. Nothing in this Agreement is intended
|
||||||
|
to be enforceable by any entity that is not a Contributor or Recipient.
|
||||||
|
No third-party beneficiary rights are created under this Agreement.
|
||||||
|
|
||||||
|
Exhibit A - Form of Secondary Licenses Notice
|
||||||
|
|
||||||
|
"This Source Code may also be made available under the following
|
||||||
|
Secondary Licenses when the conditions for such availability set forth
|
||||||
|
in the Eclipse Public License, v. 2.0 are satisfied: {name license(s),
|
||||||
|
version(s), and exceptions or additional permissions here}."
|
||||||
|
|
||||||
|
Simply including a copy of this Agreement, including this Exhibit A
|
||||||
|
is not sufficient to license the Source Code under Secondary Licenses.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular
|
||||||
|
file, then You may include the notice in a location (such as a LICENSE
|
||||||
|
file in a relevant directory) where a recipient would be likely to
|
||||||
|
look for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
39
vendor/github.com/eclipse/paho.mqtt.golang/filestore.go
generated
vendored
39
vendor/github.com/eclipse/paho.mqtt.golang/filestore.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -15,7 +19,7 @@
|
|||||||
package mqtt
|
package mqtt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
"io/fs"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"sort"
|
"sort"
|
||||||
@@ -101,7 +105,7 @@ func (store *FileStore) Get(key string) packets.ControlPacket {
|
|||||||
store.RLock()
|
store.RLock()
|
||||||
defer store.RUnlock()
|
defer store.RUnlock()
|
||||||
if !store.opened {
|
if !store.opened {
|
||||||
ERROR.Println(STR, "Trying to use file store, but not open")
|
ERROR.Println(STR, "trying to use file store, but not open")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
filepath := fullpath(store.directory, key)
|
filepath := fullpath(store.directory, key)
|
||||||
@@ -117,14 +121,16 @@ func (store *FileStore) Get(key string) packets.ControlPacket {
|
|||||||
if rerr != nil {
|
if rerr != nil {
|
||||||
newpath := corruptpath(store.directory, key)
|
newpath := corruptpath(store.directory, key)
|
||||||
WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath)
|
WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath)
|
||||||
os.Rename(filepath, newpath)
|
if err := os.Rename(filepath, newpath); err != nil {
|
||||||
|
ERROR.Println(STR, err)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return msg
|
return msg
|
||||||
}
|
}
|
||||||
|
|
||||||
// All will provide a list of all of the keys associated with messages
|
// All will provide a list of all of the keys associated with messages
|
||||||
// currenly residing in the FileStore.
|
// currently residing in the FileStore.
|
||||||
func (store *FileStore) All() []string {
|
func (store *FileStore) All() []string {
|
||||||
store.RLock()
|
store.RLock()
|
||||||
defer store.RUnlock()
|
defer store.RUnlock()
|
||||||
@@ -153,20 +159,25 @@ func (store *FileStore) Reset() {
|
|||||||
func (store *FileStore) all() []string {
|
func (store *FileStore) all() []string {
|
||||||
var err error
|
var err error
|
||||||
var keys []string
|
var keys []string
|
||||||
var files fileInfos
|
|
||||||
|
|
||||||
if !store.opened {
|
if !store.opened {
|
||||||
ERROR.Println(STR, "Trying to use file store, but not open")
|
ERROR.Println(STR, "trying to use file store, but not open")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
files, err = ioutil.ReadDir(store.directory)
|
entries, err := os.ReadDir(store.directory)
|
||||||
chkerr(err)
|
chkerr(err)
|
||||||
|
files := make(fileInfos, 0, len(entries))
|
||||||
|
for _, entry := range entries {
|
||||||
|
info, err := entry.Info()
|
||||||
|
chkerr(err)
|
||||||
|
files = append(files, info)
|
||||||
|
}
|
||||||
sort.Sort(files)
|
sort.Sort(files)
|
||||||
for _, f := range files {
|
for _, f := range files {
|
||||||
DEBUG.Println(STR, "file in All():", f.Name())
|
DEBUG.Println(STR, "file in All():", f.Name())
|
||||||
name := f.Name()
|
name := f.Name()
|
||||||
if name[len(name)-4:len(name)] != msgExt {
|
if len(name) < len(msgExt) || name[len(name)-len(msgExt):] != msgExt {
|
||||||
DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name)
|
DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -179,7 +190,7 @@ func (store *FileStore) all() []string {
|
|||||||
// lockless
|
// lockless
|
||||||
func (store *FileStore) del(key string) {
|
func (store *FileStore) del(key string) {
|
||||||
if !store.opened {
|
if !store.opened {
|
||||||
ERROR.Println(STR, "Trying to use file store, but not open")
|
ERROR.Println(STR, "trying to use file store, but not open")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
DEBUG.Println(STR, "store del filepath:", store.directory)
|
DEBUG.Println(STR, "store del filepath:", store.directory)
|
||||||
@@ -240,7 +251,7 @@ func exists(file string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
type fileInfos []os.FileInfo
|
type fileInfos []fs.FileInfo
|
||||||
|
|
||||||
func (f fileInfos) Len() int {
|
func (f fileInfos) Len() int {
|
||||||
return len(f)
|
return len(f)
|
||||||
|
|||||||
14
vendor/github.com/eclipse/paho.mqtt.golang/memstore.go
generated
vendored
14
vendor/github.com/eclipse/paho.mqtt.golang/memstore.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -88,7 +92,7 @@ func (store *MemoryStore) All() []string {
|
|||||||
ERROR.Println(STR, "Trying to use memory store, but not open")
|
ERROR.Println(STR, "Trying to use memory store, but not open")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
keys := []string{}
|
var keys []string
|
||||||
for k := range store.messages {
|
for k := range store.messages {
|
||||||
keys = append(keys, k)
|
keys = append(keys, k)
|
||||||
}
|
}
|
||||||
|
|||||||
166
vendor/github.com/eclipse/paho.mqtt.golang/memstore_ordered.go
generated
vendored
Normal file
166
vendor/github.com/eclipse/paho.mqtt.golang/memstore_ordered.go
generated
vendored
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Seth Hoenig
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
* Mike Robertson
|
||||||
|
* Matt Brittan
|
||||||
|
*/
|
||||||
|
|
||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OrderedMemoryStore uses a map internally so the order in which All() returns packets is
|
||||||
|
// undefined. OrderedMemoryStore resolves this by storing the time the message is added
|
||||||
|
// and sorting based upon this.
|
||||||
|
|
||||||
|
// storedMessage encapsulates a message and the time it was initially stored
|
||||||
|
type storedMessage struct {
|
||||||
|
ts time.Time
|
||||||
|
msg packets.ControlPacket
|
||||||
|
}
|
||||||
|
|
||||||
|
// OrderedMemoryStore implements the store interface to provide a "persistence"
|
||||||
|
// mechanism wholly stored in memory. This is only useful for
|
||||||
|
// as long as the client instance exists.
|
||||||
|
type OrderedMemoryStore struct {
|
||||||
|
sync.RWMutex
|
||||||
|
messages map[string]storedMessage
|
||||||
|
opened bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOrderedMemoryStore returns a pointer to a new instance of
|
||||||
|
// OrderedMemoryStore, the instance is not initialized and ready to
|
||||||
|
// use until Open() has been called on it.
|
||||||
|
func NewOrderedMemoryStore() *OrderedMemoryStore {
|
||||||
|
store := &OrderedMemoryStore{
|
||||||
|
messages: make(map[string]storedMessage),
|
||||||
|
opened: false,
|
||||||
|
}
|
||||||
|
return store
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open initializes a OrderedMemoryStore instance.
|
||||||
|
func (store *OrderedMemoryStore) Open() {
|
||||||
|
store.Lock()
|
||||||
|
defer store.Unlock()
|
||||||
|
store.opened = true
|
||||||
|
DEBUG.Println(STR, "OrderedMemoryStore initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put takes a key and a pointer to a Message and stores the
|
||||||
|
// message.
|
||||||
|
func (store *OrderedMemoryStore) Put(key string, message packets.ControlPacket) {
|
||||||
|
store.Lock()
|
||||||
|
defer store.Unlock()
|
||||||
|
if !store.opened {
|
||||||
|
ERROR.Println(STR, "Trying to use memory store, but not open")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
store.messages[key] = storedMessage{ts: time.Now(), msg: message}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get takes a key and looks in the store for a matching Message
|
||||||
|
// returning either the Message pointer or nil.
|
||||||
|
func (store *OrderedMemoryStore) Get(key string) packets.ControlPacket {
|
||||||
|
store.RLock()
|
||||||
|
defer store.RUnlock()
|
||||||
|
if !store.opened {
|
||||||
|
ERROR.Println(STR, "Trying to use memory store, but not open")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
mid := mIDFromKey(key)
|
||||||
|
m, ok := store.messages[key]
|
||||||
|
if !ok || m.msg == nil {
|
||||||
|
CRITICAL.Println(STR, "OrderedMemoryStore get: message", mid, "not found")
|
||||||
|
} else {
|
||||||
|
DEBUG.Println(STR, "OrderedMemoryStore get: message", mid, "found")
|
||||||
|
}
|
||||||
|
return m.msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// All returns a slice of strings containing all the keys currently
|
||||||
|
// in the OrderedMemoryStore.
|
||||||
|
func (store *OrderedMemoryStore) All() []string {
|
||||||
|
store.RLock()
|
||||||
|
defer store.RUnlock()
|
||||||
|
if !store.opened {
|
||||||
|
ERROR.Println(STR, "Trying to use memory store, but not open")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
type tsAndKey struct {
|
||||||
|
ts time.Time
|
||||||
|
key string
|
||||||
|
}
|
||||||
|
|
||||||
|
tsKeys := make([]tsAndKey, 0, len(store.messages))
|
||||||
|
for k, v := range store.messages {
|
||||||
|
tsKeys = append(tsKeys, tsAndKey{ts: v.ts, key: k})
|
||||||
|
}
|
||||||
|
sort.Slice(tsKeys, func(a int, b int) bool { return tsKeys[a].ts.Before(tsKeys[b].ts) })
|
||||||
|
|
||||||
|
keys := make([]string, len(tsKeys))
|
||||||
|
for i := range tsKeys {
|
||||||
|
keys[i] = tsKeys[i].key
|
||||||
|
}
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
|
// Del takes a key, searches the OrderedMemoryStore and if the key is found
|
||||||
|
// deletes the Message pointer associated with it.
|
||||||
|
func (store *OrderedMemoryStore) Del(key string) {
|
||||||
|
store.Lock()
|
||||||
|
defer store.Unlock()
|
||||||
|
if !store.opened {
|
||||||
|
ERROR.Println(STR, "Trying to use memory store, but not open")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mid := mIDFromKey(key)
|
||||||
|
_, ok := store.messages[key]
|
||||||
|
if !ok {
|
||||||
|
WARN.Println(STR, "OrderedMemoryStore del: message", mid, "not found")
|
||||||
|
} else {
|
||||||
|
delete(store.messages, key)
|
||||||
|
DEBUG.Println(STR, "OrderedMemoryStore del: message", mid, "was deleted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close will disallow modifications to the state of the store.
|
||||||
|
func (store *OrderedMemoryStore) Close() {
|
||||||
|
store.Lock()
|
||||||
|
defer store.Unlock()
|
||||||
|
if !store.opened {
|
||||||
|
ERROR.Println(STR, "Trying to close memory store, but not open")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
store.opened = false
|
||||||
|
DEBUG.Println(STR, "OrderedMemoryStore closed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset eliminates all persisted message data in the store.
|
||||||
|
func (store *OrderedMemoryStore) Reset() {
|
||||||
|
store.Lock()
|
||||||
|
defer store.Unlock()
|
||||||
|
if !store.opened {
|
||||||
|
ERROR.Println(STR, "Trying to reset memory store, but not open")
|
||||||
|
}
|
||||||
|
store.messages = make(map[string]storedMessage)
|
||||||
|
WARN.Println(STR, "OrderedMemoryStore wiped")
|
||||||
|
}
|
||||||
16
vendor/github.com/eclipse/paho.mqtt.golang/message.go
generated
vendored
16
vendor/github.com/eclipse/paho.mqtt.golang/message.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -16,9 +20,9 @@ package mqtt
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
"sync"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Message defines the externals that a message implementation must support
|
// Message defines the externals that a message implementation must support
|
||||||
@@ -114,7 +118,7 @@ func newConnectMsgFromOptions(options *ClientOptions, broker *url.URL) *packets.
|
|||||||
if username != "" {
|
if username != "" {
|
||||||
m.UsernameFlag = true
|
m.UsernameFlag = true
|
||||||
m.Username = username
|
m.Username = username
|
||||||
//mustn't have password without user as well
|
// mustn't have password without user as well
|
||||||
if password != "" {
|
if password != "" {
|
||||||
m.PasswordFlag = true
|
m.PasswordFlag = true
|
||||||
m.Password = []byte(password)
|
m.Password = []byte(password)
|
||||||
|
|||||||
125
vendor/github.com/eclipse/paho.mqtt.golang/messageids.go
generated
vendored
125
vendor/github.com/eclipse/paho.mqtt.golang/messageids.go
generated
vendored
@@ -1,15 +1,20 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2013 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
* Allan Stockdill-Mander
|
* Allan Stockdill-Mander
|
||||||
* Mike Robertson
|
* Mike Robertson
|
||||||
|
* Matt Brittan
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package mqtt
|
package mqtt
|
||||||
@@ -26,8 +31,10 @@ import (
|
|||||||
type MId uint16
|
type MId uint16
|
||||||
|
|
||||||
type messageIds struct {
|
type messageIds struct {
|
||||||
sync.RWMutex
|
mu sync.RWMutex // Named to prevent Mu from being accessible directly via client
|
||||||
index map[uint16]tokenCompletor
|
index map[uint16]tokenCompletor
|
||||||
|
|
||||||
|
lastIssuedID uint16 // The most recently issued ID. Used so we cycle through ids rather than immediately reusing them (can make debugging easier)
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -35,35 +42,54 @@ const (
|
|||||||
midMax uint16 = 65535
|
midMax uint16 = 65535
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// cleanup clears the message ID map; completes all token types and sets error on PUB, SUB and UNSUB tokens.
|
||||||
func (mids *messageIds) cleanUp() {
|
func (mids *messageIds) cleanUp() {
|
||||||
mids.Lock()
|
mids.mu.Lock()
|
||||||
for _, token := range mids.index {
|
for _, token := range mids.index {
|
||||||
switch token.(type) {
|
switch token.(type) {
|
||||||
case *PublishToken:
|
case *PublishToken:
|
||||||
token.setError(fmt.Errorf("Connection lost before Publish completed"))
|
token.setError(fmt.Errorf("connection lost before Publish completed"))
|
||||||
case *SubscribeToken:
|
case *SubscribeToken:
|
||||||
token.setError(fmt.Errorf("Connection lost before Subscribe completed"))
|
token.setError(fmt.Errorf("connection lost before Subscribe completed"))
|
||||||
case *UnsubscribeToken:
|
case *UnsubscribeToken:
|
||||||
token.setError(fmt.Errorf("Connection lost before Unsubscribe completed"))
|
token.setError(fmt.Errorf("connection lost before Unsubscribe completed"))
|
||||||
case nil:
|
case nil: // should not be any nil entries
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
token.flowComplete()
|
token.flowComplete()
|
||||||
}
|
}
|
||||||
mids.index = make(map[uint16]tokenCompletor)
|
mids.index = make(map[uint16]tokenCompletor)
|
||||||
mids.Unlock()
|
mids.mu.Unlock()
|
||||||
DEBUG.Println(MID, "cleaned up")
|
DEBUG.Println(MID, "cleaned up")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cleanUpSubscribe removes all SUBSCRIBE and UNSUBSCRIBE tokens (setting error)
|
||||||
|
// This may be called when the connection is lost, and we will not be resending SUB/UNSUB packets
|
||||||
|
func (mids *messageIds) cleanUpSubscribe() {
|
||||||
|
mids.mu.Lock()
|
||||||
|
for mid, token := range mids.index {
|
||||||
|
switch token.(type) {
|
||||||
|
case *SubscribeToken:
|
||||||
|
token.setError(fmt.Errorf("connection lost before Subscribe completed"))
|
||||||
|
delete(mids.index, mid)
|
||||||
|
case *UnsubscribeToken:
|
||||||
|
token.setError(fmt.Errorf("connection lost before Unsubscribe completed"))
|
||||||
|
delete(mids.index, mid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mids.mu.Unlock()
|
||||||
|
DEBUG.Println(MID, "cleaned up subs")
|
||||||
|
}
|
||||||
|
|
||||||
func (mids *messageIds) freeID(id uint16) {
|
func (mids *messageIds) freeID(id uint16) {
|
||||||
mids.Lock()
|
mids.mu.Lock()
|
||||||
delete(mids.index, id)
|
delete(mids.index, id)
|
||||||
mids.Unlock()
|
mids.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mids *messageIds) claimID(token tokenCompletor, id uint16) {
|
func (mids *messageIds) claimID(token tokenCompletor, id uint16) {
|
||||||
mids.Lock()
|
mids.mu.Lock()
|
||||||
defer mids.Unlock()
|
defer mids.mu.Unlock()
|
||||||
if _, ok := mids.index[id]; !ok {
|
if _, ok := mids.index[id]; !ok {
|
||||||
mids.index[id] = token
|
mids.index[id] = token
|
||||||
} else {
|
} else {
|
||||||
@@ -71,23 +97,38 @@ func (mids *messageIds) claimID(token tokenCompletor, id uint16) {
|
|||||||
old.flowComplete()
|
old.flowComplete()
|
||||||
mids.index[id] = token
|
mids.index[id] = token
|
||||||
}
|
}
|
||||||
|
if id > mids.lastIssuedID {
|
||||||
|
mids.lastIssuedID = id
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getID will return an available id or 0 if none available
|
||||||
|
// The id will generally be the previous id + 1 (because this makes tracing messages a bit simpler)
|
||||||
func (mids *messageIds) getID(t tokenCompletor) uint16 {
|
func (mids *messageIds) getID(t tokenCompletor) uint16 {
|
||||||
mids.Lock()
|
mids.mu.Lock()
|
||||||
defer mids.Unlock()
|
defer mids.mu.Unlock()
|
||||||
for i := midMin; i < midMax; i++ {
|
i := mids.lastIssuedID // note: the only situation where lastIssuedID is 0 the map will be empty
|
||||||
|
looped := false // uint16 will loop from 65535->0
|
||||||
|
for {
|
||||||
|
i++
|
||||||
|
if i == 0 { // skip 0 because its not a valid id (Control Packets MUST contain a non-zero 16-bit Packet Identifier [MQTT-2.3.1-1])
|
||||||
|
i++
|
||||||
|
looped = true
|
||||||
|
}
|
||||||
if _, ok := mids.index[i]; !ok {
|
if _, ok := mids.index[i]; !ok {
|
||||||
mids.index[i] = t
|
mids.index[i] = t
|
||||||
|
mids.lastIssuedID = i
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
|
if (looped && i == mids.lastIssuedID) || (mids.lastIssuedID == 0 && i == midMax) { // lastIssuedID will be 0 at startup
|
||||||
|
return 0 // no free ids
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mids *messageIds) getToken(id uint16) tokenCompletor {
|
func (mids *messageIds) getToken(id uint16) tokenCompletor {
|
||||||
mids.RLock()
|
mids.mu.RLock()
|
||||||
defer mids.RUnlock()
|
defer mids.mu.RUnlock()
|
||||||
if token, ok := mids.index[id]; ok {
|
if token, ok := mids.index[id]; ok {
|
||||||
return token
|
return token
|
||||||
}
|
}
|
||||||
@@ -98,14 +139,23 @@ type DummyToken struct {
|
|||||||
id uint16
|
id uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Wait implements the Token Wait method.
|
||||||
func (d *DummyToken) Wait() bool {
|
func (d *DummyToken) Wait() bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WaitTimeout implements the Token WaitTimeout method.
|
||||||
func (d *DummyToken) WaitTimeout(t time.Duration) bool {
|
func (d *DummyToken) WaitTimeout(t time.Duration) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Done implements the Token Done method.
|
||||||
|
func (d *DummyToken) Done() <-chan struct{} {
|
||||||
|
ch := make(chan struct{})
|
||||||
|
close(ch)
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
func (d *DummyToken) flowComplete() {
|
func (d *DummyToken) flowComplete() {
|
||||||
ERROR.Printf("A lookup for token %d returned nil\n", d.id)
|
ERROR.Printf("A lookup for token %d returned nil\n", d.id)
|
||||||
}
|
}
|
||||||
@@ -115,3 +165,36 @@ func (d *DummyToken) Error() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *DummyToken) setError(e error) {}
|
func (d *DummyToken) setError(e error) {}
|
||||||
|
|
||||||
|
// PlaceHolderToken does nothing and was implemented to allow a messageid to be reserved
|
||||||
|
// it differs from DummyToken in that calling flowComplete does not generate an error (it
|
||||||
|
// is expected that flowComplete will be called when the token is overwritten with a real token)
|
||||||
|
type PlaceHolderToken struct {
|
||||||
|
id uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait implements the Token Wait method.
|
||||||
|
func (p *PlaceHolderToken) Wait() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// WaitTimeout implements the Token WaitTimeout method.
|
||||||
|
func (p *PlaceHolderToken) WaitTimeout(t time.Duration) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Done implements the Token Done method.
|
||||||
|
func (p *PlaceHolderToken) Done() <-chan struct{} {
|
||||||
|
ch := make(chan struct{})
|
||||||
|
close(ch)
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PlaceHolderToken) flowComplete() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PlaceHolderToken) Error() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PlaceHolderToken) setError(e error) {}
|
||||||
|
|||||||
646
vendor/github.com/eclipse/paho.mqtt.golang/net.go
generated
vendored
646
vendor/github.com/eclipse/paho.mqtt.golang/net.go
generated
vendored
@@ -1,355 +1,469 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
* Allan Stockdill-Mander
|
* Allan Stockdill-Mander
|
||||||
* Mike Robertson
|
* Mike Robertson
|
||||||
|
* Matt Brittan
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package mqtt
|
package mqtt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
"sync/atomic"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
"golang.org/x/net/proxy"
|
|
||||||
"golang.org/x/net/websocket"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func signalError(c chan<- error, err error) {
|
const closedNetConnErrorText = "use of closed network connection" // error string for closed conn (https://golang.org/src/net/error_test.go)
|
||||||
select {
|
|
||||||
case c <- err:
|
// ConnectMQTT takes a connected net.Conn and performs the initial MQTT handshake. Parameters are:
|
||||||
|
// conn - Connected net.Conn
|
||||||
|
// cm - Connect Packet with everything other than the protocol name/version populated (historical reasons)
|
||||||
|
// protocolVersion - The protocol version to attempt to connect with
|
||||||
|
//
|
||||||
|
// Note that, for backward compatibility, ConnectMQTT() suppresses the actual connection error (compare to connectMQTT()).
|
||||||
|
func ConnectMQTT(conn net.Conn, cm *packets.ConnectPacket, protocolVersion uint) (byte, bool) {
|
||||||
|
rc, sessionPresent, _ := connectMQTT(conn, cm, protocolVersion)
|
||||||
|
return rc, sessionPresent
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectMQTT(conn io.ReadWriter, cm *packets.ConnectPacket, protocolVersion uint) (byte, bool, error) {
|
||||||
|
switch protocolVersion {
|
||||||
|
case 3:
|
||||||
|
DEBUG.Println(CLI, "Using MQTT 3.1 protocol")
|
||||||
|
cm.ProtocolName = "MQIsdp"
|
||||||
|
cm.ProtocolVersion = 3
|
||||||
|
case 0x83:
|
||||||
|
DEBUG.Println(CLI, "Using MQTT 3.1b protocol")
|
||||||
|
cm.ProtocolName = "MQIsdp"
|
||||||
|
cm.ProtocolVersion = 0x83
|
||||||
|
case 0x84:
|
||||||
|
DEBUG.Println(CLI, "Using MQTT 3.1.1b protocol")
|
||||||
|
cm.ProtocolName = "MQTT"
|
||||||
|
cm.ProtocolVersion = 0x84
|
||||||
default:
|
default:
|
||||||
|
DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol")
|
||||||
|
cm.ProtocolName = "MQTT"
|
||||||
|
cm.ProtocolVersion = 4
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := cm.Write(conn); err != nil {
|
||||||
|
ERROR.Println(CLI, err)
|
||||||
|
return packets.ErrNetworkError, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
rc, sessionPresent, err := verifyCONNACK(conn)
|
||||||
|
return rc, sessionPresent, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration, headers http.Header) (net.Conn, error) {
|
// This function is only used for receiving a connack
|
||||||
switch uri.Scheme {
|
// when the connection is first started.
|
||||||
case "ws":
|
// This prevents receiving incoming data while resume
|
||||||
config, _ := websocket.NewConfig(uri.String(), fmt.Sprintf("http://%s", uri.Host))
|
// is in progress if clean session is false.
|
||||||
config.Protocol = []string{"mqtt"}
|
func verifyCONNACK(conn io.Reader) (byte, bool, error) {
|
||||||
config.Header = headers
|
DEBUG.Println(NET, "connect started")
|
||||||
config.Dialer = &net.Dialer{Timeout: timeout}
|
|
||||||
conn, err := websocket.DialConfig(config)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
conn.PayloadType = websocket.BinaryFrame
|
|
||||||
return conn, err
|
|
||||||
case "wss":
|
|
||||||
config, _ := websocket.NewConfig(uri.String(), fmt.Sprintf("https://%s", uri.Host))
|
|
||||||
config.Protocol = []string{"mqtt"}
|
|
||||||
config.TlsConfig = tlsc
|
|
||||||
config.Header = headers
|
|
||||||
config.Dialer = &net.Dialer{Timeout: timeout}
|
|
||||||
conn, err := websocket.DialConfig(config)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
conn.PayloadType = websocket.BinaryFrame
|
|
||||||
return conn, err
|
|
||||||
case "tcp":
|
|
||||||
allProxy := os.Getenv("all_proxy")
|
|
||||||
if len(allProxy) == 0 {
|
|
||||||
conn, err := net.DialTimeout("tcp", uri.Host, timeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
proxyDialer := proxy.FromEnvironment()
|
|
||||||
|
|
||||||
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
ca, err := packets.ReadPacket(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
ERROR.Println(NET, "connect got error", err)
|
||||||
}
|
return packets.ErrNetworkError, false, err
|
||||||
return conn, nil
|
|
||||||
case "unix":
|
|
||||||
conn, err := net.DialTimeout("unix", uri.Host, timeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
case "ssl":
|
|
||||||
fallthrough
|
|
||||||
case "tls":
|
|
||||||
fallthrough
|
|
||||||
case "tcps":
|
|
||||||
allProxy := os.Getenv("all_proxy")
|
|
||||||
if len(allProxy) == 0 {
|
|
||||||
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", uri.Host, tlsc)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
proxyDialer := proxy.FromEnvironment()
|
|
||||||
|
|
||||||
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsConn := tls.Client(conn, tlsc)
|
|
||||||
|
|
||||||
err = tlsConn.Handshake()
|
|
||||||
if err != nil {
|
|
||||||
conn.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return tlsConn, nil
|
|
||||||
}
|
}
|
||||||
return nil, errors.New("Unknown protocol")
|
|
||||||
|
if ca == nil {
|
||||||
|
ERROR.Println(NET, "received nil packet")
|
||||||
|
return packets.ErrNetworkError, false, errors.New("nil CONNACK packet")
|
||||||
|
}
|
||||||
|
|
||||||
|
msg, ok := ca.(*packets.ConnackPacket)
|
||||||
|
if !ok {
|
||||||
|
ERROR.Println(NET, "received msg that was not CONNACK")
|
||||||
|
return packets.ErrNetworkError, false, errors.New("non-CONNACK first packet received")
|
||||||
|
}
|
||||||
|
|
||||||
|
DEBUG.Println(NET, "received connack")
|
||||||
|
return msg.ReturnCode, msg.SessionPresent, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// actually read incoming messages off the wire
|
// inbound encapsulates the output from startIncoming.
|
||||||
// send Message object into ibound channel
|
// err - If != nil then an error has occurred
|
||||||
func incoming(c *client) {
|
// cp - A control packet received over the network link
|
||||||
|
type inbound struct {
|
||||||
|
err error
|
||||||
|
cp packets.ControlPacket
|
||||||
|
}
|
||||||
|
|
||||||
|
// startIncoming initiates a goroutine that reads incoming messages off the wire and sends them to the channel (returned).
|
||||||
|
// If there are any issues with the network connection then the returned channel will be closed and the goroutine will exit
|
||||||
|
// (so closing the connection will terminate the goroutine)
|
||||||
|
func startIncoming(conn io.Reader) <-chan inbound {
|
||||||
var err error
|
var err error
|
||||||
var cp packets.ControlPacket
|
var cp packets.ControlPacket
|
||||||
|
ibound := make(chan inbound)
|
||||||
defer c.workers.Done()
|
|
||||||
|
|
||||||
DEBUG.Println(NET, "incoming started")
|
DEBUG.Println(NET, "incoming started")
|
||||||
|
|
||||||
for {
|
go func() {
|
||||||
if cp, err = packets.ReadPacket(c.conn); err != nil {
|
for {
|
||||||
break
|
if cp, err = packets.ReadPacket(conn); err != nil {
|
||||||
}
|
// We do not want to log the error if it is due to the network connection having been closed
|
||||||
DEBUG.Println(NET, "Received Message")
|
// elsewhere (i.e. after sending DisconnectPacket). Detecting this situation is the subject of
|
||||||
select {
|
// https://github.com/golang/go/issues/4373
|
||||||
case c.ibound <- cp:
|
if !strings.Contains(err.Error(), closedNetConnErrorText) {
|
||||||
// Notify keepalive logic that we recently received a packet
|
ibound <- inbound{err: err}
|
||||||
if c.options.KeepAlive != 0 {
|
|
||||||
c.lastReceived.Store(time.Now())
|
|
||||||
}
|
|
||||||
case <-c.stop:
|
|
||||||
// This avoids a deadlock should a message arrive while shutting down.
|
|
||||||
// In that case the "reader" of c.ibound might already be gone
|
|
||||||
WARN.Println(NET, "incoming dropped a received message during shutdown")
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// We received an error on read.
|
|
||||||
// If disconnect is in progress, swallow error and return
|
|
||||||
select {
|
|
||||||
case <-c.stop:
|
|
||||||
DEBUG.Println(NET, "incoming stopped")
|
|
||||||
return
|
|
||||||
// Not trying to disconnect, send the error to the errors channel
|
|
||||||
default:
|
|
||||||
ERROR.Println(NET, "incoming stopped with error", err)
|
|
||||||
signalError(c.errors, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// receive a Message object on obound, and then
|
|
||||||
// actually send outgoing message to the wire
|
|
||||||
func outgoing(c *client) {
|
|
||||||
defer c.workers.Done()
|
|
||||||
DEBUG.Println(NET, "outgoing started")
|
|
||||||
|
|
||||||
for {
|
|
||||||
DEBUG.Println(NET, "outgoing waiting for an outbound message")
|
|
||||||
select {
|
|
||||||
case <-c.stop:
|
|
||||||
DEBUG.Println(NET, "outgoing stopped")
|
|
||||||
return
|
|
||||||
case pub := <-c.obound:
|
|
||||||
msg := pub.p.(*packets.PublishPacket)
|
|
||||||
|
|
||||||
if c.options.WriteTimeout > 0 {
|
|
||||||
c.conn.SetWriteDeadline(time.Now().Add(c.options.WriteTimeout))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := msg.Write(c.conn); err != nil {
|
|
||||||
ERROR.Println(NET, "outgoing stopped with error", err)
|
|
||||||
pub.t.setError(err)
|
|
||||||
signalError(c.errors, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.options.WriteTimeout > 0 {
|
|
||||||
// If we successfully wrote, we don't want the timeout to happen during an idle period
|
|
||||||
// so we reset it to infinite.
|
|
||||||
c.conn.SetWriteDeadline(time.Time{})
|
|
||||||
}
|
|
||||||
|
|
||||||
if msg.Qos == 0 {
|
|
||||||
pub.t.flowComplete()
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "obound wrote msg, id:", msg.MessageID)
|
|
||||||
case msg := <-c.oboundP:
|
|
||||||
switch msg.p.(type) {
|
|
||||||
case *packets.SubscribePacket:
|
|
||||||
msg.p.(*packets.SubscribePacket).MessageID = c.getID(msg.t)
|
|
||||||
case *packets.UnsubscribePacket:
|
|
||||||
msg.p.(*packets.UnsubscribePacket).MessageID = c.getID(msg.t)
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "obound priority msg to write, type", reflect.TypeOf(msg.p))
|
|
||||||
if err := msg.p.Write(c.conn); err != nil {
|
|
||||||
ERROR.Println(NET, "outgoing stopped with error", err)
|
|
||||||
if msg.t != nil {
|
|
||||||
msg.t.setError(err)
|
|
||||||
}
|
}
|
||||||
signalError(c.errors, err)
|
close(ibound)
|
||||||
return
|
DEBUG.Println(NET, "incoming complete")
|
||||||
}
|
|
||||||
switch msg.p.(type) {
|
|
||||||
case *packets.DisconnectPacket:
|
|
||||||
msg.t.(*DisconnectToken).flowComplete()
|
|
||||||
DEBUG.Println(NET, "outbound wrote disconnect, stopping")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
DEBUG.Println(NET, "startIncoming Received Message")
|
||||||
|
ibound <- inbound{cp: cp}
|
||||||
}
|
}
|
||||||
// Reset ping timer after sending control packet.
|
}()
|
||||||
if c.options.KeepAlive != 0 {
|
|
||||||
c.lastSent.Store(time.Now())
|
return ibound
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// receive Message objects on ibound
|
// incomingComms encapsulates the possible output of the incomingComms routine. If err != nil then an error has occurred and
|
||||||
// store messages if necessary
|
// the routine will have terminated; otherwise one of the other members should be non-nil
|
||||||
// send replies on obound
|
type incomingComms struct {
|
||||||
// delete messages from store if necessary
|
err error // If non-nil then there has been an error (ignore everything else)
|
||||||
func alllogic(c *client) {
|
outbound *PacketAndToken // Packet (with token) than needs to be sent out (e.g. an acknowledgement)
|
||||||
defer c.workers.Done()
|
incomingPub *packets.PublishPacket // A new publish has been received; this will need to be passed on to our user
|
||||||
DEBUG.Println(NET, "logic started")
|
}
|
||||||
|
|
||||||
for {
|
// startIncomingComms initiates incoming communications; this includes starting a goroutine to process incoming
|
||||||
DEBUG.Println(NET, "logic waiting for msg on ibound")
|
// messages.
|
||||||
|
// Accepts a channel of inbound messages from the store (persisted messages); note this must be closed as soon as
|
||||||
|
// everything in the store has been sent.
|
||||||
|
// Returns a channel that will be passed any received packets; this will be closed on a network error (and inboundFromStore closed)
|
||||||
|
func startIncomingComms(conn io.Reader,
|
||||||
|
c commsFns,
|
||||||
|
inboundFromStore <-chan packets.ControlPacket,
|
||||||
|
) <-chan incomingComms {
|
||||||
|
ibound := startIncoming(conn) // Start goroutine that reads from network connection
|
||||||
|
output := make(chan incomingComms)
|
||||||
|
|
||||||
|
DEBUG.Println(NET, "startIncomingComms started")
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
if inboundFromStore == nil && ibound == nil {
|
||||||
|
close(output)
|
||||||
|
DEBUG.Println(NET, "startIncomingComms goroutine complete")
|
||||||
|
return // As soon as ibound is closed we can exit (should have already processed an error)
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "logic waiting for msg on ibound")
|
||||||
|
|
||||||
|
var msg packets.ControlPacket
|
||||||
|
var ok bool
|
||||||
|
select {
|
||||||
|
case msg, ok = <-inboundFromStore:
|
||||||
|
if !ok {
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: inboundFromStore complete")
|
||||||
|
inboundFromStore = nil // should happen quickly as this is only for persisted messages
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: got msg from store")
|
||||||
|
case ibMsg, ok := <-ibound:
|
||||||
|
if !ok {
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: ibound complete")
|
||||||
|
ibound = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: got msg on ibound")
|
||||||
|
// If the inbound comms routine encounters any issues it will send us an error.
|
||||||
|
if ibMsg.err != nil {
|
||||||
|
output <- incomingComms{err: ibMsg.err}
|
||||||
|
continue // Usually the channel will be closed immediately after sending an error but safer that we do not assume this
|
||||||
|
}
|
||||||
|
msg = ibMsg.cp
|
||||||
|
|
||||||
|
c.persistInbound(msg)
|
||||||
|
c.UpdateLastReceived() // Notify keepalive logic that we recently received a packet
|
||||||
|
}
|
||||||
|
|
||||||
select {
|
|
||||||
case msg := <-c.ibound:
|
|
||||||
DEBUG.Println(NET, "logic got msg on ibound")
|
|
||||||
persistInbound(c.persist, msg)
|
|
||||||
switch m := msg.(type) {
|
switch m := msg.(type) {
|
||||||
case *packets.PingrespPacket:
|
case *packets.PingrespPacket:
|
||||||
DEBUG.Println(NET, "received pingresp")
|
DEBUG.Println(NET, "startIncomingComms: received pingresp")
|
||||||
atomic.StoreInt32(&c.pingOutstanding, 0)
|
c.pingRespReceived()
|
||||||
case *packets.SubackPacket:
|
case *packets.SubackPacket:
|
||||||
DEBUG.Println(NET, "received suback, id:", m.MessageID)
|
DEBUG.Println(NET, "startIncomingComms: received suback, id:", m.MessageID)
|
||||||
token := c.getToken(m.MessageID)
|
token := c.getToken(m.MessageID)
|
||||||
switch t := token.(type) {
|
|
||||||
case *SubscribeToken:
|
if t, ok := token.(*SubscribeToken); ok {
|
||||||
DEBUG.Println(NET, "granted qoss", m.ReturnCodes)
|
DEBUG.Println(NET, "startIncomingComms: granted qoss", m.ReturnCodes)
|
||||||
for i, qos := range m.ReturnCodes {
|
for i, qos := range m.ReturnCodes {
|
||||||
t.subResult[t.subs[i]] = qos
|
t.subResult[t.subs[i]] = qos
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
token.flowComplete()
|
token.flowComplete()
|
||||||
c.freeID(m.MessageID)
|
c.freeID(m.MessageID)
|
||||||
case *packets.UnsubackPacket:
|
case *packets.UnsubackPacket:
|
||||||
DEBUG.Println(NET, "received unsuback, id:", m.MessageID)
|
DEBUG.Println(NET, "startIncomingComms: received unsuback, id:", m.MessageID)
|
||||||
c.getToken(m.MessageID).flowComplete()
|
c.getToken(m.MessageID).flowComplete()
|
||||||
c.freeID(m.MessageID)
|
c.freeID(m.MessageID)
|
||||||
case *packets.PublishPacket:
|
case *packets.PublishPacket:
|
||||||
DEBUG.Println(NET, "received publish, msgId:", m.MessageID)
|
DEBUG.Println(NET, "startIncomingComms: received publish, msgId:", m.MessageID)
|
||||||
DEBUG.Println(NET, "putting msg on onPubChan")
|
output <- incomingComms{incomingPub: m}
|
||||||
switch m.Qos {
|
|
||||||
case 2:
|
|
||||||
c.incomingPubChan <- m
|
|
||||||
DEBUG.Println(NET, "done putting msg on incomingPubChan")
|
|
||||||
case 1:
|
|
||||||
c.incomingPubChan <- m
|
|
||||||
DEBUG.Println(NET, "done putting msg on incomingPubChan")
|
|
||||||
case 0:
|
|
||||||
select {
|
|
||||||
case c.incomingPubChan <- m:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "done putting msg on incomingPubChan")
|
|
||||||
}
|
|
||||||
case *packets.PubackPacket:
|
case *packets.PubackPacket:
|
||||||
DEBUG.Println(NET, "received puback, id:", m.MessageID)
|
DEBUG.Println(NET, "startIncomingComms: received puback, id:", m.MessageID)
|
||||||
// c.receipts.get(msg.MsgId()) <- Receipt{}
|
|
||||||
// c.receipts.end(msg.MsgId())
|
|
||||||
c.getToken(m.MessageID).flowComplete()
|
c.getToken(m.MessageID).flowComplete()
|
||||||
c.freeID(m.MessageID)
|
c.freeID(m.MessageID)
|
||||||
case *packets.PubrecPacket:
|
case *packets.PubrecPacket:
|
||||||
DEBUG.Println(NET, "received pubrec, id:", m.MessageID)
|
DEBUG.Println(NET, "startIncomingComms: received pubrec, id:", m.MessageID)
|
||||||
prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket)
|
prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket)
|
||||||
prel.MessageID = m.MessageID
|
prel.MessageID = m.MessageID
|
||||||
select {
|
output <- incomingComms{outbound: &PacketAndToken{p: prel, t: nil}}
|
||||||
case c.oboundP <- &PacketAndToken{p: prel, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
case *packets.PubrelPacket:
|
case *packets.PubrelPacket:
|
||||||
DEBUG.Println(NET, "received pubrel, id:", m.MessageID)
|
DEBUG.Println(NET, "startIncomingComms: received pubrel, id:", m.MessageID)
|
||||||
pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket)
|
pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket)
|
||||||
pc.MessageID = m.MessageID
|
pc.MessageID = m.MessageID
|
||||||
persistOutbound(c.persist, pc)
|
c.persistOutbound(pc)
|
||||||
select {
|
output <- incomingComms{outbound: &PacketAndToken{p: pc, t: nil}}
|
||||||
case c.oboundP <- &PacketAndToken{p: pc, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
case *packets.PubcompPacket:
|
case *packets.PubcompPacket:
|
||||||
DEBUG.Println(NET, "received pubcomp, id:", m.MessageID)
|
DEBUG.Println(NET, "startIncomingComms: received pubcomp, id:", m.MessageID)
|
||||||
c.getToken(m.MessageID).flowComplete()
|
c.getToken(m.MessageID).flowComplete()
|
||||||
c.freeID(m.MessageID)
|
c.freeID(m.MessageID)
|
||||||
}
|
}
|
||||||
case <-c.stop:
|
|
||||||
WARN.Println(NET, "logic stopped")
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}()
|
||||||
|
return output
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ackFunc(packet *packets.PublishPacket) func() {
|
// startOutgoingComms initiates a go routine to transmit outgoing packets.
|
||||||
|
// Pass in an open network connection and channels for outbound messages (including those triggered
|
||||||
|
// directly from incoming comms).
|
||||||
|
// Returns a channel that will receive details of any errors (closed when the goroutine exits)
|
||||||
|
// This function wil only terminate when all input channels are closed
|
||||||
|
func startOutgoingComms(conn net.Conn,
|
||||||
|
c commsFns,
|
||||||
|
oboundp <-chan *PacketAndToken,
|
||||||
|
obound <-chan *PacketAndToken,
|
||||||
|
oboundFromIncoming <-chan *PacketAndToken,
|
||||||
|
) <-chan error {
|
||||||
|
errChan := make(chan error)
|
||||||
|
DEBUG.Println(NET, "outgoing started")
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
DEBUG.Println(NET, "outgoing waiting for an outbound message")
|
||||||
|
|
||||||
|
// This goroutine will only exits when all of the input channels we receive on have been closed. This approach is taken to avoid any
|
||||||
|
// deadlocks (if the connection goes down there are limited options as to what we can do with anything waiting on us and
|
||||||
|
// throwing away the packets seems the best option)
|
||||||
|
if oboundp == nil && obound == nil && oboundFromIncoming == nil {
|
||||||
|
DEBUG.Println(NET, "outgoing comms stopping")
|
||||||
|
close(errChan)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case pub, ok := <-obound:
|
||||||
|
if !ok {
|
||||||
|
obound = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
msg := pub.p.(*packets.PublishPacket)
|
||||||
|
DEBUG.Println(NET, "obound msg to write", msg.MessageID)
|
||||||
|
|
||||||
|
writeTimeout := c.getWriteTimeOut()
|
||||||
|
if writeTimeout > 0 {
|
||||||
|
if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
|
||||||
|
ERROR.Println(NET, "SetWriteDeadline ", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := msg.Write(conn); err != nil {
|
||||||
|
ERROR.Println(NET, "outgoing obound reporting error ", err)
|
||||||
|
pub.t.setError(err)
|
||||||
|
// report error if it's not due to the connection being closed elsewhere
|
||||||
|
if !strings.Contains(err.Error(), closedNetConnErrorText) {
|
||||||
|
errChan <- err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if writeTimeout > 0 {
|
||||||
|
// If we successfully wrote, we don't want the timeout to happen during an idle period
|
||||||
|
// so we reset it to infinite.
|
||||||
|
if err := conn.SetWriteDeadline(time.Time{}); err != nil {
|
||||||
|
ERROR.Println(NET, "SetWriteDeadline to 0 ", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if msg.Qos == 0 {
|
||||||
|
pub.t.flowComplete()
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "obound wrote msg, id:", msg.MessageID)
|
||||||
|
case msg, ok := <-oboundp:
|
||||||
|
if !ok {
|
||||||
|
oboundp = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "obound priority msg to write, type", reflect.TypeOf(msg.p))
|
||||||
|
if err := msg.p.Write(conn); err != nil {
|
||||||
|
ERROR.Println(NET, "outgoing oboundp reporting error ", err)
|
||||||
|
if msg.t != nil {
|
||||||
|
msg.t.setError(err)
|
||||||
|
}
|
||||||
|
errChan <- err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := msg.p.(*packets.DisconnectPacket); ok {
|
||||||
|
msg.t.(*DisconnectToken).flowComplete()
|
||||||
|
DEBUG.Println(NET, "outbound wrote disconnect, closing connection")
|
||||||
|
// As per the MQTT spec "After sending a DISCONNECT Packet the Client MUST close the Network Connection"
|
||||||
|
// Closing the connection will cause the goroutines to end in sequence (starting with incoming comms)
|
||||||
|
_ = conn.Close()
|
||||||
|
}
|
||||||
|
case msg, ok := <-oboundFromIncoming: // message triggered by an inbound message (PubrecPacket or PubrelPacket)
|
||||||
|
if !ok {
|
||||||
|
oboundFromIncoming = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "obound from incoming msg to write, type", reflect.TypeOf(msg.p), " ID ", msg.p.Details().MessageID)
|
||||||
|
if err := msg.p.Write(conn); err != nil {
|
||||||
|
ERROR.Println(NET, "outgoing oboundFromIncoming reporting error", err)
|
||||||
|
if msg.t != nil {
|
||||||
|
msg.t.setError(err)
|
||||||
|
}
|
||||||
|
errChan <- err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.UpdateLastSent() // Record that a packet has been received (for keepalive routine)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return errChan
|
||||||
|
}
|
||||||
|
|
||||||
|
// commsFns provide access to the client state (messageids, requesting disconnection and updating timing)
|
||||||
|
type commsFns interface {
|
||||||
|
getToken(id uint16) tokenCompletor // Retrieve the token for the specified messageid (if none then a dummy token must be returned)
|
||||||
|
freeID(id uint16) // Release the specified messageid (clearing out of any persistent store)
|
||||||
|
UpdateLastReceived() // Must be called whenever a packet is received
|
||||||
|
UpdateLastSent() // Must be called whenever a packet is successfully sent
|
||||||
|
getWriteTimeOut() time.Duration // Return the writetimeout (or 0 if none)
|
||||||
|
persistOutbound(m packets.ControlPacket) // add the packet to the outbound store
|
||||||
|
persistInbound(m packets.ControlPacket) // add the packet to the inbound store
|
||||||
|
pingRespReceived() // Called when a ping response is received
|
||||||
|
}
|
||||||
|
|
||||||
|
// startComms initiates goroutines that handles communications over the network connection
|
||||||
|
// Messages will be stored (via commsFns) and deleted from the store as necessary
|
||||||
|
// It returns two channels:
|
||||||
|
//
|
||||||
|
// packets.PublishPacket - Will receive publish packets received over the network.
|
||||||
|
// Closed when incoming comms routines exit (on shutdown or if network link closed)
|
||||||
|
// error - Any errors will be sent on this channel. The channel is closed when all comms routines have shut down
|
||||||
|
//
|
||||||
|
// Note: The comms routines monitoring oboundp and obound will not shutdown until those channels are both closed. Any messages received between the
|
||||||
|
// connection being closed and those channels being closed will generate errors (and nothing will be sent). That way the chance of a deadlock is
|
||||||
|
// minimised.
|
||||||
|
func startComms(conn net.Conn, // Network connection (must be active)
|
||||||
|
c commsFns, // getters and setters to enable us to cleanly interact with client
|
||||||
|
inboundFromStore <-chan packets.ControlPacket, // Inbound packets from the persistence store (should be closed relatively soon after startup)
|
||||||
|
oboundp <-chan *PacketAndToken,
|
||||||
|
obound <-chan *PacketAndToken) (
|
||||||
|
<-chan *packets.PublishPacket, // Publishpackages received over the network
|
||||||
|
<-chan error, // Any errors (should generally trigger a disconnect)
|
||||||
|
) {
|
||||||
|
// Start inbound comms handler; this needs to be able to transmit messages so we start a go routine to add these to the priority outbound channel
|
||||||
|
ibound := startIncomingComms(conn, c, inboundFromStore)
|
||||||
|
outboundFromIncoming := make(chan *PacketAndToken) // Will accept outgoing messages triggered by startIncomingComms (e.g. acknowledgements)
|
||||||
|
|
||||||
|
// Start the outgoing handler. It is important to note that output from startIncomingComms is fed into startOutgoingComms (for ACK's)
|
||||||
|
oboundErr := startOutgoingComms(conn, c, oboundp, obound, outboundFromIncoming)
|
||||||
|
DEBUG.Println(NET, "startComms started")
|
||||||
|
|
||||||
|
// Run up go routines to handle the output from the above comms functions - these are handled in separate
|
||||||
|
// go routines because they can interact (e.g. ibound triggers an ACK to obound which triggers an error)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(2)
|
||||||
|
|
||||||
|
outPublish := make(chan *packets.PublishPacket)
|
||||||
|
outError := make(chan error)
|
||||||
|
|
||||||
|
// Any messages received get passed to the appropriate channel
|
||||||
|
go func() {
|
||||||
|
for ic := range ibound {
|
||||||
|
if ic.err != nil {
|
||||||
|
outError <- ic.err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ic.outbound != nil {
|
||||||
|
outboundFromIncoming <- ic.outbound
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ic.incomingPub != nil {
|
||||||
|
outPublish <- ic.incomingPub
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ERROR.Println(STR, "startComms received empty incomingComms msg")
|
||||||
|
}
|
||||||
|
// Close channels that will not be written to again (allowing other routines to exit)
|
||||||
|
close(outboundFromIncoming)
|
||||||
|
close(outPublish)
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Any errors will be passed out to our caller
|
||||||
|
go func() {
|
||||||
|
for err := range oboundErr {
|
||||||
|
outError <- err
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// outError is used by both routines so can only be closed when they are both complete
|
||||||
|
go func() {
|
||||||
|
wg.Wait()
|
||||||
|
close(outError)
|
||||||
|
DEBUG.Println(NET, "startComms closing outError")
|
||||||
|
}()
|
||||||
|
|
||||||
|
return outPublish, outError
|
||||||
|
}
|
||||||
|
|
||||||
|
// ackFunc acknowledges a packet
|
||||||
|
// WARNING sendAck may be called at any time (even after the connection is dead). At the time of writing ACK sent after
|
||||||
|
// connection loss will be dropped (this is not ideal)
|
||||||
|
func ackFunc(sendAck func(*PacketAndToken), persist Store, packet *packets.PublishPacket) func() {
|
||||||
return func() {
|
return func() {
|
||||||
switch packet.Qos {
|
switch packet.Qos {
|
||||||
case 2:
|
case 2:
|
||||||
pr := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket)
|
pr := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket)
|
||||||
pr.MessageID = packet.MessageID
|
pr.MessageID = packet.MessageID
|
||||||
DEBUG.Println(NET, "putting pubrec msg on obound")
|
DEBUG.Println(NET, "putting pubrec msg on obound")
|
||||||
select {
|
sendAck(&PacketAndToken{p: pr, t: nil})
|
||||||
case c.oboundP <- &PacketAndToken{p: pr, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "done putting pubrec msg on obound")
|
DEBUG.Println(NET, "done putting pubrec msg on obound")
|
||||||
case 1:
|
case 1:
|
||||||
pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
|
pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
|
||||||
pa.MessageID = packet.MessageID
|
pa.MessageID = packet.MessageID
|
||||||
DEBUG.Println(NET, "putting puback msg on obound")
|
DEBUG.Println(NET, "putting puback msg on obound")
|
||||||
persistOutbound(c.persist, pa)
|
persistOutbound(persist, pa) // May fail if store has been closed
|
||||||
select {
|
sendAck(&PacketAndToken{p: pa, t: nil})
|
||||||
case c.oboundP <- &PacketAndToken{p: pa, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "done putting puback msg on obound")
|
DEBUG.Println(NET, "done putting puback msg on obound")
|
||||||
case 0:
|
case 0:
|
||||||
// do nothing, since there is no need to send an ack packet back
|
// do nothing, since there is no need to send an ack packet back
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func errorWatch(c *client) {
|
|
||||||
defer c.workers.Done()
|
|
||||||
select {
|
|
||||||
case <-c.stop:
|
|
||||||
WARN.Println(NET, "errorWatch stopped")
|
|
||||||
return
|
|
||||||
case err := <-c.errors:
|
|
||||||
ERROR.Println(NET, "error triggered, stopping")
|
|
||||||
go c.internalConnLost(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
101
vendor/github.com/eclipse/paho.mqtt.golang/netconn.go
generated
vendored
Normal file
101
vendor/github.com/eclipse/paho.mqtt.golang/netconn.go
generated
vendored
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Seth Hoenig
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
* Mike Robertson
|
||||||
|
* MAtt Brittan
|
||||||
|
*/
|
||||||
|
|
||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/net/proxy"
|
||||||
|
)
|
||||||
|
|
||||||
|
//
|
||||||
|
// This just establishes the network connection; once established the type of connection should be irrelevant
|
||||||
|
//
|
||||||
|
|
||||||
|
// openConnection opens a network connection using the protocol indicated in the URL.
|
||||||
|
// Does not carry out any MQTT specific handshakes.
|
||||||
|
func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration, headers http.Header, websocketOptions *WebsocketOptions, dialer *net.Dialer) (net.Conn, error) {
|
||||||
|
switch uri.Scheme {
|
||||||
|
case "ws":
|
||||||
|
dialURI := *uri // #623 - Gorilla Websockets does not accept URL's where uri.User != nil
|
||||||
|
dialURI.User = nil
|
||||||
|
conn, err := NewWebsocket(dialURI.String(), nil, timeout, headers, websocketOptions)
|
||||||
|
return conn, err
|
||||||
|
case "wss":
|
||||||
|
dialURI := *uri // #623 - Gorilla Websockets does not accept URL's where uri.User != nil
|
||||||
|
dialURI.User = nil
|
||||||
|
conn, err := NewWebsocket(dialURI.String(), tlsc, timeout, headers, websocketOptions)
|
||||||
|
return conn, err
|
||||||
|
case "mqtt", "tcp":
|
||||||
|
proxyDialer := proxy.FromEnvironmentUsing(dialer)
|
||||||
|
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
case "unix":
|
||||||
|
var conn net.Conn
|
||||||
|
var err error
|
||||||
|
|
||||||
|
// this check is preserved for compatibility with older versions
|
||||||
|
// which used uri.Host only (it works for local paths, e.g. unix://socket.sock in current dir)
|
||||||
|
if len(uri.Host) > 0 {
|
||||||
|
conn, err = dialer.Dial("unix", uri.Host)
|
||||||
|
} else {
|
||||||
|
conn, err = dialer.Dial("unix", uri.Path)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
case "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
|
||||||
|
allProxy := os.Getenv("all_proxy")
|
||||||
|
if len(allProxy) == 0 {
|
||||||
|
conn, err := tls.DialWithDialer(dialer, "tcp", uri.Host, tlsc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
proxyDialer := proxy.FromEnvironment()
|
||||||
|
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConn := tls.Client(conn, tlsc)
|
||||||
|
|
||||||
|
err = tlsConn.Handshake()
|
||||||
|
if err != nil {
|
||||||
|
_ = conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tlsConn, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("unknown protocol")
|
||||||
|
}
|
||||||
108
vendor/github.com/eclipse/paho.mqtt.golang/notice.html
generated
vendored
108
vendor/github.com/eclipse/paho.mqtt.golang/notice.html
generated
vendored
@@ -1,108 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
|
||||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
|
||||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
|
||||||
<head>
|
|
||||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
|
|
||||||
<title>Eclipse Foundation Software User Agreement</title>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body lang="EN-US">
|
|
||||||
<h2>Eclipse Foundation Software User Agreement</h2>
|
|
||||||
<p>February 1, 2011</p>
|
|
||||||
|
|
||||||
<h3>Usage Of Content</h3>
|
|
||||||
|
|
||||||
<p>THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS
|
|
||||||
(COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND
|
|
||||||
CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE
|
|
||||||
OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR
|
|
||||||
NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND
|
|
||||||
CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.</p>
|
|
||||||
|
|
||||||
<h3>Applicable Licenses</h3>
|
|
||||||
|
|
||||||
<p>Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0
|
|
||||||
("EPL"). A copy of the EPL is provided with this Content and is also available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
|
|
||||||
For purposes of the EPL, "Program" will mean the Content.</p>
|
|
||||||
|
|
||||||
<p>Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code
|
|
||||||
repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").</p>
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
<li>Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").</li>
|
|
||||||
<li>Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".</li>
|
|
||||||
<li>A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins
|
|
||||||
and/or Fragments associated with that Feature.</li>
|
|
||||||
<li>Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p>The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and
|
|
||||||
Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module
|
|
||||||
including, but not limited to the following locations:</p>
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
<li>The top-level (root) directory</li>
|
|
||||||
<li>Plug-in and Fragment directories</li>
|
|
||||||
<li>Inside Plug-ins and Fragments packaged as JARs</li>
|
|
||||||
<li>Sub-directories of the directory named "src" of certain Plug-ins</li>
|
|
||||||
<li>Feature directories</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p>Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the
|
|
||||||
installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or
|
|
||||||
inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature.
|
|
||||||
Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in
|
|
||||||
that directory.</p>
|
|
||||||
|
|
||||||
<p>THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE
|
|
||||||
OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):</p>
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
<li>Eclipse Distribution License Version 1.0 (available at <a href="http://www.eclipse.org/licenses/edl-v10.html">http://www.eclipse.org/licenses/edl-v1.0.html</a>)</li>
|
|
||||||
<li>Common Public License Version 1.0 (available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>)</li>
|
|
||||||
<li>Apache Software License 1.1 (available at <a href="http://www.apache.org/licenses/LICENSE">http://www.apache.org/licenses/LICENSE</a>)</li>
|
|
||||||
<li>Apache Software License 2.0 (available at <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>)</li>
|
|
||||||
<li>Metro Link Public License 1.00 (available at <a href="http://www.opengroup.org/openmotif/supporters/metrolink/license.html">http://www.opengroup.org/openmotif/supporters/metrolink/license.html</a>)</li>
|
|
||||||
<li>Mozilla Public License Version 1.1 (available at <a href="http://www.mozilla.org/MPL/MPL-1.1.html">http://www.mozilla.org/MPL/MPL-1.1.html</a>)</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p>IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please
|
|
||||||
contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.</p>
|
|
||||||
|
|
||||||
|
|
||||||
<h3>Use of Provisioning Technology</h3>
|
|
||||||
|
|
||||||
<p>The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse
|
|
||||||
Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or
|
|
||||||
other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to
|
|
||||||
install, extend and update Eclipse-based products. Information about packaging Installable Software is available at <a
|
|
||||||
href="http://eclipse.org/equinox/p2/repository_packaging.html">http://eclipse.org/equinox/p2/repository_packaging.html</a>
|
|
||||||
("Specification").</p>
|
|
||||||
|
|
||||||
<p>You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the
|
|
||||||
applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology
|
|
||||||
in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the
|
|
||||||
Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:</p>
|
|
||||||
|
|
||||||
<ol>
|
|
||||||
<li>A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology
|
|
||||||
on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based
|
|
||||||
product.</li>
|
|
||||||
<li>During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be
|
|
||||||
accessed and copied to the Target Machine.</li>
|
|
||||||
<li>Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable
|
|
||||||
Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target
|
|
||||||
Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern
|
|
||||||
the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such
|
|
||||||
indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.</li>
|
|
||||||
</ol>
|
|
||||||
|
|
||||||
<h3>Cryptography</h3>
|
|
||||||
|
|
||||||
<p>Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to
|
|
||||||
another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import,
|
|
||||||
possession, or use, and re-export of encryption software, to see if this is permitted.</p>
|
|
||||||
|
|
||||||
<p><small>Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.</small></p>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
12
vendor/github.com/eclipse/paho.mqtt.golang/oops.go
generated
vendored
12
vendor/github.com/eclipse/paho.mqtt.golang/oops.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
|
|||||||
285
vendor/github.com/eclipse/paho.mqtt.golang/options.go
generated
vendored
285
vendor/github.com/eclipse/paho.mqtt.golang/options.go
generated
vendored
@@ -1,15 +1,20 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
* Allan Stockdill-Mander
|
* Allan Stockdill-Mander
|
||||||
* Mike Robertson
|
* Mike Robertson
|
||||||
|
* Måns Ansgariusson
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Portions copyright © 2018 TIBCO Software Inc.
|
// Portions copyright © 2018 TIBCO Software Inc.
|
||||||
@@ -18,6 +23,7 @@ package mqtt
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -44,74 +50,111 @@ type ConnectionLostHandler func(Client, error)
|
|||||||
// at initial connection and on reconnection
|
// at initial connection and on reconnection
|
||||||
type OnConnectHandler func(Client)
|
type OnConnectHandler func(Client)
|
||||||
|
|
||||||
// ClientOptions contains configurable options for an Client.
|
// ReconnectHandler is invoked prior to reconnecting after
|
||||||
|
// the initial connection is lost
|
||||||
|
type ReconnectHandler func(Client, *ClientOptions)
|
||||||
|
|
||||||
|
// ConnectionAttemptHandler is invoked prior to making the initial connection.
|
||||||
|
type ConnectionAttemptHandler func(broker *url.URL, tlsCfg *tls.Config) *tls.Config
|
||||||
|
|
||||||
|
// OpenConnectionFunc is invoked to establish the underlying network connection
|
||||||
|
// Its purpose if for custom network transports.
|
||||||
|
// Does not carry out any MQTT specific handshakes.
|
||||||
|
type OpenConnectionFunc func(uri *url.URL, options ClientOptions) (net.Conn, error)
|
||||||
|
|
||||||
|
// ConnectionNotificationHandler is invoked for any type of connection event.
|
||||||
|
type ConnectionNotificationHandler func(Client, ConnectionNotification)
|
||||||
|
|
||||||
|
// ClientOptions contains configurable options for an Client. Note that these should be set using the
|
||||||
|
// relevant methods (e.g. AddBroker) rather than directly. See those functions for information on usage.
|
||||||
|
// WARNING: Create the below using NewClientOptions unless you have a compelling reason not to. It is easy
|
||||||
|
// to create a configuration with difficult to trace issues (e.g. Mosquitto 2.0.12+ will reject connections
|
||||||
|
// with KeepAlive=0 by default).
|
||||||
type ClientOptions struct {
|
type ClientOptions struct {
|
||||||
Servers []*url.URL
|
Servers []*url.URL
|
||||||
ClientID string
|
ClientID string
|
||||||
Username string
|
Username string
|
||||||
Password string
|
Password string
|
||||||
CredentialsProvider CredentialsProvider
|
CredentialsProvider CredentialsProvider
|
||||||
CleanSession bool
|
CleanSession bool
|
||||||
Order bool
|
Order bool
|
||||||
WillEnabled bool
|
WillEnabled bool
|
||||||
WillTopic string
|
WillTopic string
|
||||||
WillPayload []byte
|
WillPayload []byte
|
||||||
WillQos byte
|
WillQos byte
|
||||||
WillRetained bool
|
WillRetained bool
|
||||||
ProtocolVersion uint
|
ProtocolVersion uint
|
||||||
protocolVersionExplicit bool
|
protocolVersionExplicit bool
|
||||||
TLSConfig *tls.Config
|
TLSConfig *tls.Config
|
||||||
KeepAlive int64
|
KeepAlive int64 // Warning: Some brokers may reject connections with Keepalive = 0.
|
||||||
PingTimeout time.Duration
|
PingTimeout time.Duration
|
||||||
ConnectTimeout time.Duration
|
ConnectTimeout time.Duration
|
||||||
MaxReconnectInterval time.Duration
|
MaxReconnectInterval time.Duration
|
||||||
AutoReconnect bool
|
AutoReconnect bool
|
||||||
Store Store
|
ConnectRetryInterval time.Duration
|
||||||
DefaultPublishHandler MessageHandler
|
ConnectRetry bool
|
||||||
OnConnect OnConnectHandler
|
Store Store
|
||||||
OnConnectionLost ConnectionLostHandler
|
DefaultPublishHandler MessageHandler
|
||||||
WriteTimeout time.Duration
|
OnConnect OnConnectHandler
|
||||||
MessageChannelDepth uint
|
OnConnectionLost ConnectionLostHandler
|
||||||
ResumeSubs bool
|
OnReconnecting ReconnectHandler
|
||||||
HTTPHeaders http.Header
|
OnConnectAttempt ConnectionAttemptHandler
|
||||||
|
OnConnectionNotification ConnectionNotificationHandler
|
||||||
|
WriteTimeout time.Duration
|
||||||
|
MessageChannelDepth uint
|
||||||
|
ResumeSubs bool
|
||||||
|
HTTPHeaders http.Header
|
||||||
|
WebsocketOptions *WebsocketOptions
|
||||||
|
MaxResumePubInFlight int // // 0 = no limit; otherwise this is the maximum simultaneous messages sent while resuming
|
||||||
|
Dialer *net.Dialer
|
||||||
|
CustomOpenConnectionFn OpenConnectionFunc
|
||||||
|
AutoAckDisabled bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClientOptions will create a new ClientClientOptions type with some
|
// NewClientOptions will create a new ClientClientOptions type with some
|
||||||
// default values.
|
// default values.
|
||||||
// Port: 1883
|
//
|
||||||
// CleanSession: True
|
// Port: 1883
|
||||||
// Order: True
|
// CleanSession: True
|
||||||
// KeepAlive: 30 (seconds)
|
// Order: True (note: it is recommended that this be set to FALSE unless order is important)
|
||||||
// ConnectTimeout: 30 (seconds)
|
// KeepAlive: 30 (seconds)
|
||||||
// MaxReconnectInterval 10 (minutes)
|
// ConnectTimeout: 30 (seconds)
|
||||||
// AutoReconnect: True
|
// MaxReconnectInterval 10 (minutes)
|
||||||
|
// AutoReconnect: True
|
||||||
func NewClientOptions() *ClientOptions {
|
func NewClientOptions() *ClientOptions {
|
||||||
o := &ClientOptions{
|
o := &ClientOptions{
|
||||||
Servers: nil,
|
Servers: nil,
|
||||||
ClientID: "",
|
ClientID: "",
|
||||||
Username: "",
|
Username: "",
|
||||||
Password: "",
|
Password: "",
|
||||||
CleanSession: true,
|
CleanSession: true,
|
||||||
Order: true,
|
Order: true,
|
||||||
WillEnabled: false,
|
WillEnabled: false,
|
||||||
WillTopic: "",
|
WillTopic: "",
|
||||||
WillPayload: nil,
|
WillPayload: nil,
|
||||||
WillQos: 0,
|
WillQos: 0,
|
||||||
WillRetained: false,
|
WillRetained: false,
|
||||||
ProtocolVersion: 0,
|
ProtocolVersion: 0,
|
||||||
protocolVersionExplicit: false,
|
protocolVersionExplicit: false,
|
||||||
KeepAlive: 30,
|
KeepAlive: 30,
|
||||||
PingTimeout: 10 * time.Second,
|
PingTimeout: 10 * time.Second,
|
||||||
ConnectTimeout: 30 * time.Second,
|
ConnectTimeout: 30 * time.Second,
|
||||||
MaxReconnectInterval: 10 * time.Minute,
|
MaxReconnectInterval: 10 * time.Minute,
|
||||||
AutoReconnect: true,
|
AutoReconnect: true,
|
||||||
Store: nil,
|
ConnectRetryInterval: 30 * time.Second,
|
||||||
OnConnect: nil,
|
ConnectRetry: false,
|
||||||
OnConnectionLost: DefaultConnectionLostHandler,
|
Store: nil,
|
||||||
WriteTimeout: 0, // 0 represents timeout disabled
|
OnConnect: nil,
|
||||||
MessageChannelDepth: 100,
|
OnConnectionLost: DefaultConnectionLostHandler,
|
||||||
ResumeSubs: false,
|
OnConnectAttempt: nil,
|
||||||
HTTPHeaders: make(map[string][]string),
|
OnConnectionNotification: nil,
|
||||||
|
WriteTimeout: 0, // 0 represents timeout disabled
|
||||||
|
ResumeSubs: false,
|
||||||
|
HTTPHeaders: make(map[string][]string),
|
||||||
|
WebsocketOptions: &WebsocketOptions{},
|
||||||
|
Dialer: &net.Dialer{Timeout: 30 * time.Second},
|
||||||
|
CustomOpenConnectionFn: nil,
|
||||||
|
AutoAckDisabled: false,
|
||||||
}
|
}
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
@@ -149,7 +192,7 @@ func (o *ClientOptions) SetResumeSubs(resume bool) *ClientOptions {
|
|||||||
|
|
||||||
// SetClientID will set the client id to be used by this client when
|
// SetClientID will set the client id to be used by this client when
|
||||||
// connecting to the MQTT broker. According to the MQTT v3.1 specification,
|
// connecting to the MQTT broker. According to the MQTT v3.1 specification,
|
||||||
// a client id mus be no longer than 23 characters.
|
// a client id must be no longer than 23 characters.
|
||||||
func (o *ClientOptions) SetClientID(id string) *ClientOptions {
|
func (o *ClientOptions) SetClientID(id string) *ClientOptions {
|
||||||
o.ClientID = id
|
o.ClientID = id
|
||||||
return o
|
return o
|
||||||
@@ -157,7 +200,7 @@ func (o *ClientOptions) SetClientID(id string) *ClientOptions {
|
|||||||
|
|
||||||
// SetUsername will set the username to be used by this client when connecting
|
// SetUsername will set the username to be used by this client when connecting
|
||||||
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
||||||
// be sent in plaintext accross the wire.
|
// be sent in plaintext across the wire.
|
||||||
func (o *ClientOptions) SetUsername(u string) *ClientOptions {
|
func (o *ClientOptions) SetUsername(u string) *ClientOptions {
|
||||||
o.Username = u
|
o.Username = u
|
||||||
return o
|
return o
|
||||||
@@ -165,7 +208,7 @@ func (o *ClientOptions) SetUsername(u string) *ClientOptions {
|
|||||||
|
|
||||||
// SetPassword will set the password to be used by this client when connecting
|
// SetPassword will set the password to be used by this client when connecting
|
||||||
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
||||||
// be sent in plaintext accross the wire.
|
// be sent in plaintext across the wire.
|
||||||
func (o *ClientOptions) SetPassword(p string) *ClientOptions {
|
func (o *ClientOptions) SetPassword(p string) *ClientOptions {
|
||||||
o.Password = p
|
o.Password = p
|
||||||
return o
|
return o
|
||||||
@@ -174,7 +217,7 @@ func (o *ClientOptions) SetPassword(p string) *ClientOptions {
|
|||||||
// SetCredentialsProvider will set a method to be called by this client when
|
// SetCredentialsProvider will set a method to be called by this client when
|
||||||
// connecting to the MQTT broker that provide the current username and password.
|
// connecting to the MQTT broker that provide the current username and password.
|
||||||
// Note: without the use of SSL/TLS, this information will be sent
|
// Note: without the use of SSL/TLS, this information will be sent
|
||||||
// in plaintext accross the wire.
|
// in plaintext across the wire.
|
||||||
func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions {
|
func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions {
|
||||||
o.CredentialsProvider = p
|
o.CredentialsProvider = p
|
||||||
return o
|
return o
|
||||||
@@ -184,7 +227,7 @@ func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOpt
|
|||||||
// when this client connects to an MQTT broker. By setting this flag, you are
|
// when this client connects to an MQTT broker. By setting this flag, you are
|
||||||
// indicating that no messages saved by the broker for this client should be
|
// indicating that no messages saved by the broker for this client should be
|
||||||
// delivered. Any messages that were going to be sent by this client before
|
// delivered. Any messages that were going to be sent by this client before
|
||||||
// diconnecting previously but didn't will not be sent upon connecting to the
|
// disconnecting previously but didn't will not be sent upon connecting to the
|
||||||
// broker.
|
// broker.
|
||||||
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions {
|
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions {
|
||||||
o.CleanSession = clean
|
o.CleanSession = clean
|
||||||
@@ -192,9 +235,13 @@ func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetOrderMatters will set the message routing to guarantee order within
|
// SetOrderMatters will set the message routing to guarantee order within
|
||||||
// each QoS level. By default, this value is true. If set to false,
|
// each QoS level. By default, this value is true. If set to false (recommended),
|
||||||
// this flag indicates that messages can be delivered asynchronously
|
// this flag indicates that messages can be delivered asynchronously
|
||||||
// from the client to the application and possibly arrive out of order.
|
// from the client to the application and possibly arrive out of order.
|
||||||
|
// Specifically, the message handler is called in its own go routine.
|
||||||
|
// Note that setting this to true does not guarantee in-order delivery
|
||||||
|
// (this is subject to broker settings like "max_inflight_messages=1" in mosquitto)
|
||||||
|
// and if true then handlers must not block.
|
||||||
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions {
|
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions {
|
||||||
o.Order = order
|
o.Order = order
|
||||||
return o
|
return o
|
||||||
@@ -274,6 +321,11 @@ func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, re
|
|||||||
|
|
||||||
// SetDefaultPublishHandler sets the MessageHandler that will be called when a message
|
// SetDefaultPublishHandler sets the MessageHandler that will be called when a message
|
||||||
// is received that does not match any known subscriptions.
|
// is received that does not match any known subscriptions.
|
||||||
|
//
|
||||||
|
// If OrderMatters is true (the defaultHandler) then callback must not block or
|
||||||
|
// call functions within this package that may block (e.g. Publish) other than in
|
||||||
|
// a new go routine.
|
||||||
|
// defaultHandler must be safe for concurrent use by multiple goroutines.
|
||||||
func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions {
|
func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions {
|
||||||
o.DefaultPublishHandler = defaultHandler
|
o.DefaultPublishHandler = defaultHandler
|
||||||
return o
|
return o
|
||||||
@@ -293,18 +345,42 @@ func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *
|
|||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetReconnectingHandler sets the OnReconnecting callback to be executed prior
|
||||||
|
// to the client attempting a reconnect to the MQTT broker.
|
||||||
|
func (o *ClientOptions) SetReconnectingHandler(cb ReconnectHandler) *ClientOptions {
|
||||||
|
o.OnReconnecting = cb
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConnectionAttemptHandler sets the ConnectionAttemptHandler callback to be executed prior
|
||||||
|
// to each attempt to connect to an MQTT broker. Returns the *tls.Config that will be used when establishing
|
||||||
|
// the connection (a copy of the tls.Config from ClientOptions will be passed in along with the broker URL).
|
||||||
|
// This allows connection specific changes to be made to the *tls.Config.
|
||||||
|
func (o *ClientOptions) SetConnectionAttemptHandler(onConnectAttempt ConnectionAttemptHandler) *ClientOptions {
|
||||||
|
o.OnConnectAttempt = onConnectAttempt
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConnectionNotificationHandler sets the ConnectionNotificationHandler callback to receive all types of connection
|
||||||
|
// events.
|
||||||
|
func (o *ClientOptions) SetConnectionNotificationHandler(onConnectionNotification ConnectionNotificationHandler) *ClientOptions {
|
||||||
|
o.OnConnectionNotification = onConnectionNotification
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a
|
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a
|
||||||
// timeout error. A duration of 0 never times out. Default 30 seconds
|
// timeout error. A duration of 0 never times out. Default never times out
|
||||||
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions {
|
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions {
|
||||||
o.WriteTimeout = t
|
o.WriteTimeout = t
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetConnectTimeout limits how long the client will wait when trying to open a connection
|
// SetConnectTimeout limits how long the client will wait when trying to open a connection
|
||||||
// to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out.
|
// to an MQTT server before timing out. A duration of 0 never times out.
|
||||||
// Default 30 seconds. Currently only operational on TCP/TLS connections.
|
// Default 30 seconds. Currently only operational on TCP/TLS connections.
|
||||||
func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions {
|
func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions {
|
||||||
o.ConnectTimeout = t
|
o.ConnectTimeout = t
|
||||||
|
o.Dialer.Timeout = t
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,10 +399,25 @@ func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions {
|
|||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetMessageChannelDepth sets the size of the internal queue that holds messages while the
|
// SetConnectRetryInterval sets the time that will be waited between connection attempts
|
||||||
// client is temporairily offline, allowing the application to publish when the client is
|
// when initially connecting if ConnectRetry is TRUE
|
||||||
// reconnecting. This setting is only valid if AutoReconnect is set to true, it is otherwise
|
func (o *ClientOptions) SetConnectRetryInterval(t time.Duration) *ClientOptions {
|
||||||
// ignored.
|
o.ConnectRetryInterval = t
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConnectRetry sets whether the connect function will automatically retry the connection
|
||||||
|
// in the event of a failure (when true the token returned by the Connect function will
|
||||||
|
// not complete until the connection is up or it is cancelled)
|
||||||
|
// If ConnectRetry is true then subscriptions should be requested in OnConnect handler
|
||||||
|
// Setting this to TRUE permits messages to be published before the connection is established
|
||||||
|
func (o *ClientOptions) SetConnectRetry(a bool) *ClientOptions {
|
||||||
|
o.ConnectRetry = a
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetMessageChannelDepth DEPRECATED The value set here no longer has any effect, this function
|
||||||
|
// remains so the API is not altered.
|
||||||
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions {
|
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions {
|
||||||
o.MessageChannelDepth = s
|
o.MessageChannelDepth = s
|
||||||
return o
|
return o
|
||||||
@@ -338,3 +429,43 @@ func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions {
|
|||||||
o.HTTPHeaders = h
|
o.HTTPHeaders = h
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetWebsocketOptions sets the additional websocket options used in a WebSocket connection
|
||||||
|
func (o *ClientOptions) SetWebsocketOptions(w *WebsocketOptions) *ClientOptions {
|
||||||
|
o.WebsocketOptions = w
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetMaxResumePubInFlight sets the maximum simultaneous publish messages that will be sent while resuming. Note that
|
||||||
|
// this only applies to messages coming from the store (so additional sends may push us over the limit)
|
||||||
|
// Note that the connect token will not be flagged as complete until all messages have been sent from the
|
||||||
|
// store. If broker does not respond to messages then resume may not complete.
|
||||||
|
// This option was put in place because resuming after downtime can saturate low capacity links.
|
||||||
|
func (o *ClientOptions) SetMaxResumePubInFlight(MaxResumePubInFlight int) *ClientOptions {
|
||||||
|
o.MaxResumePubInFlight = MaxResumePubInFlight
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDialer sets the tcp dialer options used in a tcp connection
|
||||||
|
func (o *ClientOptions) SetDialer(dialer *net.Dialer) *ClientOptions {
|
||||||
|
o.Dialer = dialer
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetCustomOpenConnectionFn replaces the inbuilt function that establishes a network connection with a custom function.
|
||||||
|
// The passed in function should return an open `net.Conn` or an error (see the existing openConnection function for an example)
|
||||||
|
// It enables custom networking types in addition to the defaults (tcp, tls, websockets...)
|
||||||
|
func (o *ClientOptions) SetCustomOpenConnectionFn(customOpenConnectionFn OpenConnectionFunc) *ClientOptions {
|
||||||
|
if customOpenConnectionFn != nil {
|
||||||
|
o.CustomOpenConnectionFn = customOpenConnectionFn
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetAutoAckDisabled enables or disables the Automated Acking of Messages received by the handler.
|
||||||
|
//
|
||||||
|
// By default it is set to false. Setting it to true will disable the auto-ack globally.
|
||||||
|
func (o *ClientOptions) SetAutoAckDisabled(autoAckDisabled bool) *ClientOptions {
|
||||||
|
o.AutoAckDisabled = autoAckDisabled
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|||||||
57
vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go
generated
vendored
57
vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -26,7 +30,22 @@ type ClientOptionsReader struct {
|
|||||||
options *ClientOptions
|
options *ClientOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
//Servers returns a slice of the servers defined in the clientoptions
|
// NewOptionsReader creates a ClientOptionsReader, this should only be used for mocking purposes.
|
||||||
|
//
|
||||||
|
// An example implementation:
|
||||||
|
//
|
||||||
|
// func (c *mqttClientMock) OptionsReader() mqtt.ClientOptionsReader {
|
||||||
|
// opts := mqtt.NewClientOptions()
|
||||||
|
// opts.UserName = "TestUserName"
|
||||||
|
// return mqtt.NewOptionsReader(opts)
|
||||||
|
// }
|
||||||
|
func NewOptionsReader(o *ClientOptions) ClientOptionsReader {
|
||||||
|
return ClientOptionsReader{
|
||||||
|
options: o,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Servers returns a slice of the servers defined in the clientoptions
|
||||||
func (r *ClientOptionsReader) Servers() []*url.URL {
|
func (r *ClientOptionsReader) Servers() []*url.URL {
|
||||||
s := make([]*url.URL, len(r.options.Servers))
|
s := make([]*url.URL, len(r.options.Servers))
|
||||||
|
|
||||||
@@ -38,31 +57,31 @@ func (r *ClientOptionsReader) Servers() []*url.URL {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
//ResumeSubs returns true if resuming stored (un)sub is enabled
|
// ResumeSubs returns true if resuming stored (un)sub is enabled
|
||||||
func (r *ClientOptionsReader) ResumeSubs() bool {
|
func (r *ClientOptionsReader) ResumeSubs() bool {
|
||||||
s := r.options.ResumeSubs
|
s := r.options.ResumeSubs
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
//ClientID returns the set client id
|
// ClientID returns the set client id
|
||||||
func (r *ClientOptionsReader) ClientID() string {
|
func (r *ClientOptionsReader) ClientID() string {
|
||||||
s := r.options.ClientID
|
s := r.options.ClientID
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
//Username returns the set username
|
// Username returns the set username
|
||||||
func (r *ClientOptionsReader) Username() string {
|
func (r *ClientOptionsReader) Username() string {
|
||||||
s := r.options.Username
|
s := r.options.Username
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
//Password returns the set password
|
// Password returns the set password
|
||||||
func (r *ClientOptionsReader) Password() string {
|
func (r *ClientOptionsReader) Password() string {
|
||||||
s := r.options.Password
|
s := r.options.Password
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
//CleanSession returns whether Cleansession is set
|
// CleanSession returns whether Cleansession is set
|
||||||
func (r *ClientOptionsReader) CleanSession() bool {
|
func (r *ClientOptionsReader) CleanSession() bool {
|
||||||
s := r.options.CleanSession
|
s := r.options.CleanSession
|
||||||
return s
|
return s
|
||||||
@@ -133,6 +152,18 @@ func (r *ClientOptionsReader) AutoReconnect() bool {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ConnectRetryInterval returns the delay between retries on the initial connection (if ConnectRetry true)
|
||||||
|
func (r *ClientOptionsReader) ConnectRetryInterval() time.Duration {
|
||||||
|
s := r.options.ConnectRetryInterval
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectRetry returns whether the initial connection request will be retried until connection established
|
||||||
|
func (r *ClientOptionsReader) ConnectRetry() bool {
|
||||||
|
s := r.options.ConnectRetry
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
func (r *ClientOptionsReader) WriteTimeout() time.Duration {
|
func (r *ClientOptionsReader) WriteTimeout() time.Duration {
|
||||||
s := r.options.WriteTimeout
|
s := r.options.WriteTimeout
|
||||||
return s
|
return s
|
||||||
@@ -147,3 +178,9 @@ func (r *ClientOptionsReader) HTTPHeaders() http.Header {
|
|||||||
h := r.options.HTTPHeaders
|
h := r.options.HTTPHeaders
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WebsocketOptions returns the currently configured WebSocket options
|
||||||
|
func (r *ClientOptionsReader) WebsocketOptions() *WebsocketOptions {
|
||||||
|
s := r.options.WebsocketOptions
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,8 +22,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//ConnackPacket is an internal representation of the fields of the
|
// ConnackPacket is an internal representation of the fields of the
|
||||||
//Connack MQTT packet
|
// Connack MQTT packet
|
||||||
type ConnackPacket struct {
|
type ConnackPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
SessionPresent bool
|
SessionPresent bool
|
||||||
@@ -15,10 +31,7 @@ type ConnackPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ca *ConnackPacket) String() string {
|
func (ca *ConnackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", ca.FixedHeader)
|
return fmt.Sprintf("%s sessionpresent: %t returncode: %d", ca.FixedHeader, ca.SessionPresent, ca.ReturnCode)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("sessionpresent: %t returncode: %d", ca.SessionPresent, ca.ReturnCode)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ca *ConnackPacket) Write(w io.Writer) error {
|
func (ca *ConnackPacket) Write(w io.Writer) error {
|
||||||
@@ -35,8 +48,8 @@ func (ca *ConnackPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (ca *ConnackPacket) Unpack(b io.Reader) error {
|
func (ca *ConnackPacket) Unpack(b io.Reader) error {
|
||||||
flags, err := decodeByte(b)
|
flags, err := decodeByte(b)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -48,8 +61,8 @@ func (ca *ConnackPacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (ca *ConnackPacket) Details() Details {
|
func (ca *ConnackPacket) Details() Details {
|
||||||
return Details{Qos: 0, MessageID: 0}
|
return Details{Qos: 0, MessageID: 0}
|
||||||
}
|
}
|
||||||
|
|||||||
49
vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go
generated
vendored
49
vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,8 +22,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//ConnectPacket is an internal representation of the fields of the
|
// ConnectPacket is an internal representation of the fields of the
|
||||||
//Connect MQTT packet
|
// Connect MQTT packet
|
||||||
type ConnectPacket struct {
|
type ConnectPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
ProtocolName string
|
ProtocolName string
|
||||||
@@ -29,10 +45,11 @@ type ConnectPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConnectPacket) String() string {
|
func (c *ConnectPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", c.FixedHeader)
|
var password string
|
||||||
str += " "
|
if len(c.Password) > 0 {
|
||||||
str += fmt.Sprintf("protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, c.Password)
|
password = "<redacted>"
|
||||||
return str
|
}
|
||||||
|
return fmt.Sprintf("%s protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.FixedHeader, c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, password)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConnectPacket) Write(w io.Writer) error {
|
func (c *ConnectPacket) Write(w io.Writer) error {
|
||||||
@@ -62,8 +79,8 @@ func (c *ConnectPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (c *ConnectPacket) Unpack(b io.Reader) error {
|
func (c *ConnectPacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
c.ProtocolName, err = decodeString(b)
|
c.ProtocolName, err = decodeString(b)
|
||||||
@@ -119,36 +136,36 @@ func (c *ConnectPacket) Unpack(b io.Reader) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Validate performs validation of the fields of a Connect packet
|
// Validate performs validation of the fields of a Connect packet
|
||||||
func (c *ConnectPacket) Validate() byte {
|
func (c *ConnectPacket) Validate() byte {
|
||||||
if c.PasswordFlag && !c.UsernameFlag {
|
if c.PasswordFlag && !c.UsernameFlag {
|
||||||
return ErrRefusedBadUsernameOrPassword
|
return ErrRefusedBadUsernameOrPassword
|
||||||
}
|
}
|
||||||
if c.ReservedBit != 0 {
|
if c.ReservedBit != 0 {
|
||||||
//Bad reserved bit
|
// Bad reserved bit
|
||||||
return ErrProtocolViolation
|
return ErrProtocolViolation
|
||||||
}
|
}
|
||||||
if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) {
|
if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) {
|
||||||
//Mismatched or unsupported protocol version
|
// Mismatched or unsupported protocol version
|
||||||
return ErrRefusedBadProtocolVersion
|
return ErrRefusedBadProtocolVersion
|
||||||
}
|
}
|
||||||
if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" {
|
if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" {
|
||||||
//Bad protocol name
|
// Bad protocol name
|
||||||
return ErrProtocolViolation
|
return ErrProtocolViolation
|
||||||
}
|
}
|
||||||
if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 {
|
if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 {
|
||||||
//Bad size field
|
// Bad size field
|
||||||
return ErrProtocolViolation
|
return ErrProtocolViolation
|
||||||
}
|
}
|
||||||
if len(c.ClientIdentifier) == 0 && !c.CleanSession {
|
if len(c.ClientIdentifier) == 0 && !c.CleanSession {
|
||||||
//Bad client identifier
|
// Bad client identifier
|
||||||
return ErrRefusedIDRejected
|
return ErrRefusedIDRejected
|
||||||
}
|
}
|
||||||
return Accepted
|
return Accepted
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (c *ConnectPacket) Details() Details {
|
func (c *ConnectPacket) Details() Details {
|
||||||
return Details{Qos: 0, MessageID: 0}
|
return Details{Qos: 0, MessageID: 0}
|
||||||
}
|
}
|
||||||
|
|||||||
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go
generated
vendored
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go
generated
vendored
@@ -1,19 +1,33 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//DisconnectPacket is an internal representation of the fields of the
|
// DisconnectPacket is an internal representation of the fields of the
|
||||||
//Disconnect MQTT packet
|
// Disconnect MQTT packet
|
||||||
type DisconnectPacket struct {
|
type DisconnectPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DisconnectPacket) String() string {
|
func (d *DisconnectPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", d.FixedHeader)
|
return d.FixedHeader.String()
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DisconnectPacket) Write(w io.Writer) error {
|
func (d *DisconnectPacket) Write(w io.Writer) error {
|
||||||
@@ -23,14 +37,14 @@ func (d *DisconnectPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (d *DisconnectPacket) Unpack(b io.Reader) error {
|
func (d *DisconnectPacket) Unpack(b io.Reader) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (d *DisconnectPacket) Details() Details {
|
func (d *DisconnectPacket) Details() Details {
|
||||||
return Details{Qos: 0, MessageID: 0}
|
return Details{Qos: 0, MessageID: 0}
|
||||||
}
|
}
|
||||||
|
|||||||
111
vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go
generated
vendored
111
vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -8,9 +24,9 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//ControlPacket defines the interface for structs intended to hold
|
// ControlPacket defines the interface for structs intended to hold
|
||||||
//decoded MQTT packets, either from being read or before being
|
// decoded MQTT packets, either from being read or before being
|
||||||
//written
|
// written
|
||||||
type ControlPacket interface {
|
type ControlPacket interface {
|
||||||
Write(io.Writer) error
|
Write(io.Writer) error
|
||||||
Unpack(io.Reader) error
|
Unpack(io.Reader) error
|
||||||
@@ -18,8 +34,8 @@ type ControlPacket interface {
|
|||||||
Details() Details
|
Details() Details
|
||||||
}
|
}
|
||||||
|
|
||||||
//PacketNames maps the constants for each of the MQTT packet types
|
// PacketNames maps the constants for each of the MQTT packet types
|
||||||
//to a string representation of their name.
|
// to a string representation of their name.
|
||||||
var PacketNames = map[uint8]string{
|
var PacketNames = map[uint8]string{
|
||||||
1: "CONNECT",
|
1: "CONNECT",
|
||||||
2: "CONNACK",
|
2: "CONNACK",
|
||||||
@@ -37,7 +53,7 @@ var PacketNames = map[uint8]string{
|
|||||||
14: "DISCONNECT",
|
14: "DISCONNECT",
|
||||||
}
|
}
|
||||||
|
|
||||||
//Below are the constants assigned to each of the MQTT packet types
|
// Below are the constants assigned to each of the MQTT packet types
|
||||||
const (
|
const (
|
||||||
Connect = 1
|
Connect = 1
|
||||||
Connack = 2
|
Connack = 2
|
||||||
@@ -55,8 +71,8 @@ const (
|
|||||||
Disconnect = 14
|
Disconnect = 14
|
||||||
)
|
)
|
||||||
|
|
||||||
//Below are the const definitions for error codes returned by
|
// Below are the const definitions for error codes returned by
|
||||||
//Connect()
|
// Connect()
|
||||||
const (
|
const (
|
||||||
Accepted = 0x00
|
Accepted = 0x00
|
||||||
ErrRefusedBadProtocolVersion = 0x01
|
ErrRefusedBadProtocolVersion = 0x01
|
||||||
@@ -68,8 +84,8 @@ const (
|
|||||||
ErrProtocolViolation = 0xFF
|
ErrProtocolViolation = 0xFF
|
||||||
)
|
)
|
||||||
|
|
||||||
//ConnackReturnCodes is a map of the error codes constants for Connect()
|
// ConnackReturnCodes is a map of the error codes constants for Connect()
|
||||||
//to a string representation of the error
|
// to a string representation of the error
|
||||||
var ConnackReturnCodes = map[uint8]string{
|
var ConnackReturnCodes = map[uint8]string{
|
||||||
0: "Connection Accepted",
|
0: "Connection Accepted",
|
||||||
1: "Connection Refused: Bad Protocol Version",
|
1: "Connection Refused: Bad Protocol Version",
|
||||||
@@ -81,23 +97,33 @@ var ConnackReturnCodes = map[uint8]string{
|
|||||||
255: "Connection Refused: Protocol Violation",
|
255: "Connection Refused: Protocol Violation",
|
||||||
}
|
}
|
||||||
|
|
||||||
//ConnErrors is a map of the errors codes constants for Connect()
|
var (
|
||||||
//to a Go error
|
ErrorRefusedBadProtocolVersion = errors.New("unacceptable protocol version")
|
||||||
|
ErrorRefusedIDRejected = errors.New("identifier rejected")
|
||||||
|
ErrorRefusedServerUnavailable = errors.New("server Unavailable")
|
||||||
|
ErrorRefusedBadUsernameOrPassword = errors.New("bad user name or password")
|
||||||
|
ErrorRefusedNotAuthorised = errors.New("not Authorized")
|
||||||
|
ErrorNetworkError = errors.New("network Error")
|
||||||
|
ErrorProtocolViolation = errors.New("protocol Violation")
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConnErrors is a map of the errors codes constants for Connect()
|
||||||
|
// to a Go error
|
||||||
var ConnErrors = map[byte]error{
|
var ConnErrors = map[byte]error{
|
||||||
Accepted: nil,
|
Accepted: nil,
|
||||||
ErrRefusedBadProtocolVersion: errors.New("Unnacceptable protocol version"),
|
ErrRefusedBadProtocolVersion: ErrorRefusedBadProtocolVersion,
|
||||||
ErrRefusedIDRejected: errors.New("Identifier rejected"),
|
ErrRefusedIDRejected: ErrorRefusedIDRejected,
|
||||||
ErrRefusedServerUnavailable: errors.New("Server Unavailable"),
|
ErrRefusedServerUnavailable: ErrorRefusedServerUnavailable,
|
||||||
ErrRefusedBadUsernameOrPassword: errors.New("Bad user name or password"),
|
ErrRefusedBadUsernameOrPassword: ErrorRefusedBadUsernameOrPassword,
|
||||||
ErrRefusedNotAuthorised: errors.New("Not Authorized"),
|
ErrRefusedNotAuthorised: ErrorRefusedNotAuthorised,
|
||||||
ErrNetworkError: errors.New("Network Error"),
|
ErrNetworkError: ErrorNetworkError,
|
||||||
ErrProtocolViolation: errors.New("Protocol Violation"),
|
ErrProtocolViolation: ErrorProtocolViolation,
|
||||||
}
|
}
|
||||||
|
|
||||||
//ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts
|
// ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts
|
||||||
//to read an MQTT packet from the stream. It returns a ControlPacket
|
// to read an MQTT packet from the stream. It returns a ControlPacket
|
||||||
//representing the decoded MQTT packet and an error. One of these returns will
|
// representing the decoded MQTT packet and an error. One of these returns will
|
||||||
//always be nil, a nil ControlPacket indicating an error occurred.
|
// always be nil, a nil ControlPacket indicating an error occurred.
|
||||||
func ReadPacket(r io.Reader) (ControlPacket, error) {
|
func ReadPacket(r io.Reader) (ControlPacket, error) {
|
||||||
var fh FixedHeader
|
var fh FixedHeader
|
||||||
b := make([]byte, 1)
|
b := make([]byte, 1)
|
||||||
@@ -123,17 +149,17 @@ func ReadPacket(r io.Reader) (ControlPacket, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if n != fh.RemainingLength {
|
if n != fh.RemainingLength {
|
||||||
return nil, errors.New("Failed to read expected data")
|
return nil, errors.New("failed to read expected data")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = cp.Unpack(bytes.NewBuffer(packetBytes))
|
err = cp.Unpack(bytes.NewBuffer(packetBytes))
|
||||||
return cp, err
|
return cp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
//NewControlPacket is used to create a new ControlPacket of the type specified
|
// NewControlPacket is used to create a new ControlPacket of the type specified
|
||||||
//by packetType, this is usually done by reference to the packet type constants
|
// by packetType, this is usually done by reference to the packet type constants
|
||||||
//defined in packets.go. The newly created ControlPacket is empty and a pointer
|
// defined in packets.go. The newly created ControlPacket is empty and a pointer
|
||||||
//is returned.
|
// is returned.
|
||||||
func NewControlPacket(packetType byte) ControlPacket {
|
func NewControlPacket(packetType byte) ControlPacket {
|
||||||
switch packetType {
|
switch packetType {
|
||||||
case Connect:
|
case Connect:
|
||||||
@@ -168,9 +194,9 @@ func NewControlPacket(packetType byte) ControlPacket {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//NewControlPacketWithHeader is used to create a new ControlPacket of the type
|
// NewControlPacketWithHeader is used to create a new ControlPacket of the type
|
||||||
//specified within the FixedHeader that is passed to the function.
|
// specified within the FixedHeader that is passed to the function.
|
||||||
//The newly created ControlPacket is empty and a pointer is returned.
|
// The newly created ControlPacket is empty and a pointer is returned.
|
||||||
func NewControlPacketWithHeader(fh FixedHeader) (ControlPacket, error) {
|
func NewControlPacketWithHeader(fh FixedHeader) (ControlPacket, error) {
|
||||||
switch fh.MessageType {
|
switch fh.MessageType {
|
||||||
case Connect:
|
case Connect:
|
||||||
@@ -205,16 +231,16 @@ func NewControlPacketWithHeader(fh FixedHeader) (ControlPacket, error) {
|
|||||||
return nil, fmt.Errorf("unsupported packet type 0x%x", fh.MessageType)
|
return nil, fmt.Errorf("unsupported packet type 0x%x", fh.MessageType)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details struct returned by the Details() function called on
|
// Details struct returned by the Details() function called on
|
||||||
//ControlPackets to present details of the Qos and MessageID
|
// ControlPackets to present details of the Qos and MessageID
|
||||||
//of the ControlPacket
|
// of the ControlPacket
|
||||||
type Details struct {
|
type Details struct {
|
||||||
Qos byte
|
Qos byte
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
//FixedHeader is a struct to hold the decoded information from
|
// FixedHeader is a struct to hold the decoded information from
|
||||||
//the fixed header of an MQTT ControlPacket
|
// the fixed header of an MQTT ControlPacket
|
||||||
type FixedHeader struct {
|
type FixedHeader struct {
|
||||||
MessageType byte
|
MessageType byte
|
||||||
Dup bool
|
Dup bool
|
||||||
@@ -274,9 +300,9 @@ func decodeUint16(b io.Reader) (uint16, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func encodeUint16(num uint16) []byte {
|
func encodeUint16(num uint16) []byte {
|
||||||
bytes := make([]byte, 2)
|
bytesResult := make([]byte, 2)
|
||||||
binary.BigEndian.PutUint16(bytes, num)
|
binary.BigEndian.PutUint16(bytesResult, num)
|
||||||
return bytes
|
return bytesResult
|
||||||
}
|
}
|
||||||
|
|
||||||
func encodeString(field string) []byte {
|
func encodeString(field string) []byte {
|
||||||
@@ -304,6 +330,11 @@ func decodeBytes(b io.Reader) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func encodeBytes(field []byte) []byte {
|
func encodeBytes(field []byte) []byte {
|
||||||
|
// Attempting to encode more than 65,535 bytes would lead to an unexpected 16-bit length and extra data written
|
||||||
|
// (which would be parsed as later parts of the message). The safest option is to truncate.
|
||||||
|
if len(field) > 65535 {
|
||||||
|
field = field[0:65535]
|
||||||
|
}
|
||||||
fieldLength := make([]byte, 2)
|
fieldLength := make([]byte, 2)
|
||||||
binary.BigEndian.PutUint16(fieldLength, uint16(len(field)))
|
binary.BigEndian.PutUint16(fieldLength, uint16(len(field)))
|
||||||
return append(fieldLength, field...)
|
return append(fieldLength, field...)
|
||||||
@@ -329,7 +360,7 @@ func decodeLength(r io.Reader) (int, error) {
|
|||||||
var rLength uint32
|
var rLength uint32
|
||||||
var multiplier uint32
|
var multiplier uint32
|
||||||
b := make([]byte, 1)
|
b := make([]byte, 1)
|
||||||
for multiplier < 27 { //fix: Infinite '(digit & 128) == 1' will cause the dead loop
|
for multiplier < 27 { // fix: Infinite '(digit & 128) == 1' will cause the dead loop
|
||||||
_, err := io.ReadFull(r, b)
|
_, err := io.ReadFull(r, b)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
|
|||||||
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go
generated
vendored
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go
generated
vendored
@@ -1,19 +1,33 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//PingreqPacket is an internal representation of the fields of the
|
// PingreqPacket is an internal representation of the fields of the
|
||||||
//Pingreq MQTT packet
|
// Pingreq MQTT packet
|
||||||
type PingreqPacket struct {
|
type PingreqPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingreqPacket) String() string {
|
func (pr *PingreqPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return pr.FixedHeader.String()
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingreqPacket) Write(w io.Writer) error {
|
func (pr *PingreqPacket) Write(w io.Writer) error {
|
||||||
@@ -23,14 +37,14 @@ func (pr *PingreqPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (pr *PingreqPacket) Unpack(b io.Reader) error {
|
func (pr *PingreqPacket) Unpack(b io.Reader) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (pr *PingreqPacket) Details() Details {
|
func (pr *PingreqPacket) Details() Details {
|
||||||
return Details{Qos: 0, MessageID: 0}
|
return Details{Qos: 0, MessageID: 0}
|
||||||
}
|
}
|
||||||
|
|||||||
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go
generated
vendored
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go
generated
vendored
@@ -1,19 +1,33 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//PingrespPacket is an internal representation of the fields of the
|
// PingrespPacket is an internal representation of the fields of the
|
||||||
//Pingresp MQTT packet
|
// Pingresp MQTT packet
|
||||||
type PingrespPacket struct {
|
type PingrespPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingrespPacket) String() string {
|
func (pr *PingrespPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return pr.FixedHeader.String()
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingrespPacket) Write(w io.Writer) error {
|
func (pr *PingrespPacket) Write(w io.Writer) error {
|
||||||
@@ -23,14 +37,14 @@ func (pr *PingrespPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (pr *PingrespPacket) Unpack(b io.Reader) error {
|
func (pr *PingrespPacket) Unpack(b io.Reader) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (pr *PingrespPacket) Details() Details {
|
func (pr *PingrespPacket) Details() Details {
|
||||||
return Details{Qos: 0, MessageID: 0}
|
return Details{Qos: 0, MessageID: 0}
|
||||||
}
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,18 +21,15 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//PubackPacket is an internal representation of the fields of the
|
// PubackPacket is an internal representation of the fields of the
|
||||||
//Puback MQTT packet
|
// Puback MQTT packet
|
||||||
type PubackPacket struct {
|
type PubackPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pa *PubackPacket) String() string {
|
func (pa *PubackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pa.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pa.FixedHeader, pa.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pa.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pa *PubackPacket) Write(w io.Writer) error {
|
func (pa *PubackPacket) Write(w io.Writer) error {
|
||||||
@@ -29,8 +42,8 @@ func (pa *PubackPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (pa *PubackPacket) Unpack(b io.Reader) error {
|
func (pa *PubackPacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
pa.MessageID, err = decodeUint16(b)
|
pa.MessageID, err = decodeUint16(b)
|
||||||
@@ -38,8 +51,8 @@ func (pa *PubackPacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (pa *PubackPacket) Details() Details {
|
func (pa *PubackPacket) Details() Details {
|
||||||
return Details{Qos: pa.Qos, MessageID: pa.MessageID}
|
return Details{Qos: pa.Qos, MessageID: pa.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,18 +21,15 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//PubcompPacket is an internal representation of the fields of the
|
// PubcompPacket is an internal representation of the fields of the
|
||||||
//Pubcomp MQTT packet
|
// Pubcomp MQTT packet
|
||||||
type PubcompPacket struct {
|
type PubcompPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pc *PubcompPacket) String() string {
|
func (pc *PubcompPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pc.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pc.FixedHeader, pc.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pc.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pc *PubcompPacket) Write(w io.Writer) error {
|
func (pc *PubcompPacket) Write(w io.Writer) error {
|
||||||
@@ -29,8 +42,8 @@ func (pc *PubcompPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (pc *PubcompPacket) Unpack(b io.Reader) error {
|
func (pc *PubcompPacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
pc.MessageID, err = decodeUint16(b)
|
pc.MessageID, err = decodeUint16(b)
|
||||||
@@ -38,8 +51,8 @@ func (pc *PubcompPacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (pc *PubcompPacket) Details() Details {
|
func (pc *PubcompPacket) Details() Details {
|
||||||
return Details{Qos: pc.Qos, MessageID: pc.MessageID}
|
return Details{Qos: pc.Qos, MessageID: pc.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
45
vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go
generated
vendored
45
vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,8 +22,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//PublishPacket is an internal representation of the fields of the
|
// PublishPacket is an internal representation of the fields of the
|
||||||
//Publish MQTT packet
|
// Publish MQTT packet
|
||||||
type PublishPacket struct {
|
type PublishPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
TopicName string
|
TopicName string
|
||||||
@@ -16,12 +32,7 @@ type PublishPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *PublishPacket) String() string {
|
func (p *PublishPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", p.FixedHeader)
|
return fmt.Sprintf("%s topicName: %s MessageID: %d payload: %s", p.FixedHeader, p.TopicName, p.MessageID, string(p.Payload))
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("topicName: %s MessageID: %d", p.TopicName, p.MessageID)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("payload: %s", string(p.Payload))
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *PublishPacket) Write(w io.Writer) error {
|
func (p *PublishPacket) Write(w io.Writer) error {
|
||||||
@@ -41,8 +52,8 @@ func (p *PublishPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (p *PublishPacket) Unpack(b io.Reader) error {
|
func (p *PublishPacket) Unpack(b io.Reader) error {
|
||||||
var payloadLength = p.FixedHeader.RemainingLength
|
var payloadLength = p.FixedHeader.RemainingLength
|
||||||
var err error
|
var err error
|
||||||
@@ -61,7 +72,7 @@ func (p *PublishPacket) Unpack(b io.Reader) error {
|
|||||||
payloadLength -= len(p.TopicName) + 2
|
payloadLength -= len(p.TopicName) + 2
|
||||||
}
|
}
|
||||||
if payloadLength < 0 {
|
if payloadLength < 0 {
|
||||||
return fmt.Errorf("Error unpacking publish, payload length < 0")
|
return fmt.Errorf("error unpacking publish, payload length < 0")
|
||||||
}
|
}
|
||||||
p.Payload = make([]byte, payloadLength)
|
p.Payload = make([]byte, payloadLength)
|
||||||
_, err = b.Read(p.Payload)
|
_, err = b.Read(p.Payload)
|
||||||
@@ -69,10 +80,10 @@ func (p *PublishPacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Copy creates a new PublishPacket with the same topic and payload
|
// Copy creates a new PublishPacket with the same topic and payload
|
||||||
//but an empty fixed header, useful for when you want to deliver
|
// but an empty fixed header, useful for when you want to deliver
|
||||||
//a message with different properties such as Qos but the same
|
// a message with different properties such as Qos but the same
|
||||||
//content
|
// content
|
||||||
func (p *PublishPacket) Copy() *PublishPacket {
|
func (p *PublishPacket) Copy() *PublishPacket {
|
||||||
newP := NewControlPacket(Publish).(*PublishPacket)
|
newP := NewControlPacket(Publish).(*PublishPacket)
|
||||||
newP.TopicName = p.TopicName
|
newP.TopicName = p.TopicName
|
||||||
@@ -81,8 +92,8 @@ func (p *PublishPacket) Copy() *PublishPacket {
|
|||||||
return newP
|
return newP
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (p *PublishPacket) Details() Details {
|
func (p *PublishPacket) Details() Details {
|
||||||
return Details{Qos: p.Qos, MessageID: p.MessageID}
|
return Details{Qos: p.Qos, MessageID: p.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,18 +21,15 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//PubrecPacket is an internal representation of the fields of the
|
// PubrecPacket is an internal representation of the fields of the
|
||||||
//Pubrec MQTT packet
|
// Pubrec MQTT packet
|
||||||
type PubrecPacket struct {
|
type PubrecPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrecPacket) String() string {
|
func (pr *PubrecPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pr.FixedHeader, pr.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pr.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrecPacket) Write(w io.Writer) error {
|
func (pr *PubrecPacket) Write(w io.Writer) error {
|
||||||
@@ -29,8 +42,8 @@ func (pr *PubrecPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (pr *PubrecPacket) Unpack(b io.Reader) error {
|
func (pr *PubrecPacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
pr.MessageID, err = decodeUint16(b)
|
pr.MessageID, err = decodeUint16(b)
|
||||||
@@ -38,8 +51,8 @@ func (pr *PubrecPacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (pr *PubrecPacket) Details() Details {
|
func (pr *PubrecPacket) Details() Details {
|
||||||
return Details{Qos: pr.Qos, MessageID: pr.MessageID}
|
return Details{Qos: pr.Qos, MessageID: pr.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,18 +21,15 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//PubrelPacket is an internal representation of the fields of the
|
// PubrelPacket is an internal representation of the fields of the
|
||||||
//Pubrel MQTT packet
|
// Pubrel MQTT packet
|
||||||
type PubrelPacket struct {
|
type PubrelPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrelPacket) String() string {
|
func (pr *PubrelPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pr.FixedHeader, pr.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pr.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrelPacket) Write(w io.Writer) error {
|
func (pr *PubrelPacket) Write(w io.Writer) error {
|
||||||
@@ -29,8 +42,8 @@ func (pr *PubrelPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (pr *PubrelPacket) Unpack(b io.Reader) error {
|
func (pr *PubrelPacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
pr.MessageID, err = decodeUint16(b)
|
pr.MessageID, err = decodeUint16(b)
|
||||||
@@ -38,8 +51,8 @@ func (pr *PubrelPacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (pr *PubrelPacket) Details() Details {
|
func (pr *PubrelPacket) Details() Details {
|
||||||
return Details{Qos: pr.Qos, MessageID: pr.MessageID}
|
return Details{Qos: pr.Qos, MessageID: pr.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,8 +22,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//SubackPacket is an internal representation of the fields of the
|
// SubackPacket is an internal representation of the fields of the
|
||||||
//Suback MQTT packet
|
// Suback MQTT packet
|
||||||
type SubackPacket struct {
|
type SubackPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
@@ -15,10 +31,7 @@ type SubackPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (sa *SubackPacket) String() string {
|
func (sa *SubackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", sa.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", sa.FixedHeader, sa.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", sa.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sa *SubackPacket) Write(w io.Writer) error {
|
func (sa *SubackPacket) Write(w io.Writer) error {
|
||||||
@@ -34,8 +47,8 @@ func (sa *SubackPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (sa *SubackPacket) Unpack(b io.Reader) error {
|
func (sa *SubackPacket) Unpack(b io.Reader) error {
|
||||||
var qosBuffer bytes.Buffer
|
var qosBuffer bytes.Buffer
|
||||||
var err error
|
var err error
|
||||||
@@ -53,8 +66,8 @@ func (sa *SubackPacket) Unpack(b io.Reader) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (sa *SubackPacket) Details() Details {
|
func (sa *SubackPacket) Details() Details {
|
||||||
return Details{Qos: 0, MessageID: sa.MessageID}
|
return Details{Qos: 0, MessageID: sa.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
35
vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go
generated
vendored
35
vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,8 +22,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//SubscribePacket is an internal representation of the fields of the
|
// SubscribePacket is an internal representation of the fields of the
|
||||||
//Subscribe MQTT packet
|
// Subscribe MQTT packet
|
||||||
type SubscribePacket struct {
|
type SubscribePacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
@@ -16,10 +32,7 @@ type SubscribePacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *SubscribePacket) String() string {
|
func (s *SubscribePacket) String() string {
|
||||||
str := fmt.Sprintf("%s", s.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d topics: %s", s.FixedHeader, s.MessageID, s.Topics)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d topics: %s", s.MessageID, s.Topics)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SubscribePacket) Write(w io.Writer) error {
|
func (s *SubscribePacket) Write(w io.Writer) error {
|
||||||
@@ -39,8 +52,8 @@ func (s *SubscribePacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (s *SubscribePacket) Unpack(b io.Reader) error {
|
func (s *SubscribePacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
s.MessageID, err = decodeUint16(b)
|
s.MessageID, err = decodeUint16(b)
|
||||||
@@ -59,14 +72,14 @@ func (s *SubscribePacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
s.Qoss = append(s.Qoss, qos)
|
s.Qoss = append(s.Qoss, qos)
|
||||||
payloadLength -= 2 + len(topic) + 1 //2 bytes of string length, plus string, plus 1 byte for Qos
|
payloadLength -= 2 + len(topic) + 1 // 2 bytes of string length, plus string, plus 1 byte for Qos
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (s *SubscribePacket) Details() Details {
|
func (s *SubscribePacket) Details() Details {
|
||||||
return Details{Qos: 1, MessageID: s.MessageID}
|
return Details{Qos: 1, MessageID: s.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,18 +21,15 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//UnsubackPacket is an internal representation of the fields of the
|
// UnsubackPacket is an internal representation of the fields of the
|
||||||
//Unsuback MQTT packet
|
// Unsuback MQTT packet
|
||||||
type UnsubackPacket struct {
|
type UnsubackPacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ua *UnsubackPacket) String() string {
|
func (ua *UnsubackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", ua.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", ua.FixedHeader, ua.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", ua.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ua *UnsubackPacket) Write(w io.Writer) error {
|
func (ua *UnsubackPacket) Write(w io.Writer) error {
|
||||||
@@ -29,8 +42,8 @@ func (ua *UnsubackPacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (ua *UnsubackPacket) Unpack(b io.Reader) error {
|
func (ua *UnsubackPacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
ua.MessageID, err = decodeUint16(b)
|
ua.MessageID, err = decodeUint16(b)
|
||||||
@@ -38,8 +51,8 @@ func (ua *UnsubackPacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (ua *UnsubackPacket) Details() Details {
|
func (ua *UnsubackPacket) Details() Details {
|
||||||
return Details{Qos: 0, MessageID: ua.MessageID}
|
return Details{Qos: 0, MessageID: ua.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go
generated
vendored
33
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go
generated
vendored
@@ -1,3 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
*/
|
||||||
|
|
||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,8 +22,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
//UnsubscribePacket is an internal representation of the fields of the
|
// UnsubscribePacket is an internal representation of the fields of the
|
||||||
//Unsubscribe MQTT packet
|
// Unsubscribe MQTT packet
|
||||||
type UnsubscribePacket struct {
|
type UnsubscribePacket struct {
|
||||||
FixedHeader
|
FixedHeader
|
||||||
MessageID uint16
|
MessageID uint16
|
||||||
@@ -15,10 +31,7 @@ type UnsubscribePacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *UnsubscribePacket) String() string {
|
func (u *UnsubscribePacket) String() string {
|
||||||
str := fmt.Sprintf("%s", u.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", u.FixedHeader, u.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", u.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *UnsubscribePacket) Write(w io.Writer) error {
|
func (u *UnsubscribePacket) Write(w io.Writer) error {
|
||||||
@@ -36,8 +49,8 @@ func (u *UnsubscribePacket) Write(w io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
// Unpack decodes the details of a ControlPacket after the fixed
|
||||||
//header has been read
|
// header has been read
|
||||||
func (u *UnsubscribePacket) Unpack(b io.Reader) error {
|
func (u *UnsubscribePacket) Unpack(b io.Reader) error {
|
||||||
var err error
|
var err error
|
||||||
u.MessageID, err = decodeUint16(b)
|
u.MessageID, err = decodeUint16(b)
|
||||||
@@ -52,8 +65,8 @@ func (u *UnsubscribePacket) Unpack(b io.Reader) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
// Details returns a Details struct containing the Qos and
|
||||||
//MessageID of this ControlPacket
|
// MessageID of this ControlPacket
|
||||||
func (u *UnsubscribePacket) Details() Details {
|
func (u *UnsubscribePacket) Details() Details {
|
||||||
return Details{Qos: 1, MessageID: u.MessageID}
|
return Details{Qos: 1, MessageID: u.MessageID}
|
||||||
}
|
}
|
||||||
|
|||||||
37
vendor/github.com/eclipse/paho.mqtt.golang/ping.go
generated
vendored
37
vendor/github.com/eclipse/paho.mqtt.golang/ping.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -16,25 +20,28 @@ package mqtt
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"io"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
)
|
)
|
||||||
|
|
||||||
func keepalive(c *client) {
|
// keepalive - Send ping when connection unused for set period
|
||||||
|
// connection passed in to avoid race condition on shutdown
|
||||||
|
func keepalive(c *client, conn io.Writer) {
|
||||||
defer c.workers.Done()
|
defer c.workers.Done()
|
||||||
DEBUG.Println(PNG, "keepalive starting")
|
DEBUG.Println(PNG, "keepalive starting")
|
||||||
var checkInterval int64
|
var checkInterval time.Duration
|
||||||
var pingSent time.Time
|
var pingSent time.Time
|
||||||
|
|
||||||
if c.options.KeepAlive > 10 {
|
if c.options.KeepAlive > 10 {
|
||||||
checkInterval = 5
|
checkInterval = 5 * time.Second
|
||||||
} else {
|
} else {
|
||||||
checkInterval = c.options.KeepAlive / 2
|
checkInterval = time.Duration(c.options.KeepAlive) * time.Second / 4
|
||||||
}
|
}
|
||||||
|
|
||||||
intervalTicker := time.NewTicker(time.Duration(checkInterval * int64(time.Second)))
|
intervalTicker := time.NewTicker(checkInterval)
|
||||||
defer intervalTicker.Stop()
|
defer intervalTicker.Stop()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
@@ -51,17 +58,19 @@ func keepalive(c *client) {
|
|||||||
if atomic.LoadInt32(&c.pingOutstanding) == 0 {
|
if atomic.LoadInt32(&c.pingOutstanding) == 0 {
|
||||||
DEBUG.Println(PNG, "keepalive sending ping")
|
DEBUG.Println(PNG, "keepalive sending ping")
|
||||||
ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket)
|
ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket)
|
||||||
//We don't want to wait behind large messages being sent, the Write call
|
// We don't want to wait behind large messages being sent, the `Write` call
|
||||||
//will block until it it able to send the packet.
|
// will block until it is able to send the packet.
|
||||||
atomic.StoreInt32(&c.pingOutstanding, 1)
|
atomic.StoreInt32(&c.pingOutstanding, 1)
|
||||||
ping.Write(c.conn)
|
if err := ping.Write(conn); err != nil {
|
||||||
|
ERROR.Println(PNG, err)
|
||||||
|
}
|
||||||
c.lastSent.Store(time.Now())
|
c.lastSent.Store(time.Now())
|
||||||
pingSent = time.Now()
|
pingSent = time.Now()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if atomic.LoadInt32(&c.pingOutstanding) > 0 && time.Now().Sub(pingSent) >= c.options.PingTimeout {
|
if atomic.LoadInt32(&c.pingOutstanding) > 0 && time.Since(pingSent) >= c.options.PingTimeout {
|
||||||
CRITICAL.Println(PNG, "pingresp not received, disconnecting")
|
CRITICAL.Println(PNG, "pingresp not received, disconnecting")
|
||||||
c.errors <- errors.New("pingresp not received, disconnecting")
|
c.internalConnLost(errors.New("pingresp not received, disconnecting")) // no harm in calling this if the connection is already down (or shutdown is in progress)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
127
vendor/github.com/eclipse/paho.mqtt.golang/router.go
generated
vendored
127
vendor/github.com/eclipse/paho.mqtt.golang/router.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -37,17 +41,11 @@ type route struct {
|
|||||||
// and returns a boolean of the outcome
|
// and returns a boolean of the outcome
|
||||||
func match(route []string, topic []string) bool {
|
func match(route []string, topic []string) bool {
|
||||||
if len(route) == 0 {
|
if len(route) == 0 {
|
||||||
if len(topic) == 0 {
|
return len(topic) == 0
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(topic) == 0 {
|
if len(topic) == 0 {
|
||||||
if route[0] == "#" {
|
return route[0] == "#"
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if route[0] == "#" {
|
if route[0] == "#" {
|
||||||
@@ -87,15 +85,13 @@ type router struct {
|
|||||||
routes *list.List
|
routes *list.List
|
||||||
defaultHandler MessageHandler
|
defaultHandler MessageHandler
|
||||||
messages chan *packets.PublishPacket
|
messages chan *packets.PublishPacket
|
||||||
stop chan bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// newRouter returns a new instance of a Router and channel which can be used to tell the Router
|
// newRouter returns a new instance of a Router and channel which can be used to tell the Router
|
||||||
// to stop
|
// to stop
|
||||||
func newRouter() (*router, chan bool) {
|
func newRouter() *router {
|
||||||
router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)}
|
router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket)}
|
||||||
stop := router.stop
|
return router
|
||||||
return router, stop
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of
|
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of
|
||||||
@@ -105,7 +101,7 @@ func (r *router) addRoute(topic string, callback MessageHandler) {
|
|||||||
r.Lock()
|
r.Lock()
|
||||||
defer r.Unlock()
|
defer r.Unlock()
|
||||||
for e := r.routes.Front(); e != nil; e = e.Next() {
|
for e := r.routes.Front(); e != nil; e = e.Next() {
|
||||||
if e.Value.(*route).match(topic) {
|
if e.Value.(*route).topic == topic {
|
||||||
r := e.Value.(*route)
|
r := e.Value.(*route)
|
||||||
r.callback = callback
|
r.callback = callback
|
||||||
return
|
return
|
||||||
@@ -120,7 +116,7 @@ func (r *router) deleteRoute(topic string) {
|
|||||||
r.Lock()
|
r.Lock()
|
||||||
defer r.Unlock()
|
defer r.Unlock()
|
||||||
for e := r.routes.Front(); e != nil; e = e.Next() {
|
for e := r.routes.Front(); e != nil; e = e.Next() {
|
||||||
if e.Value.(*route).match(topic) {
|
if e.Value.(*route).topic == topic {
|
||||||
r.routes.Remove(e)
|
r.routes.Remove(e)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -139,49 +135,80 @@ func (r *router) setDefaultHandler(handler MessageHandler) {
|
|||||||
// takes messages off the channel, matches them against the internal route list and calls the
|
// takes messages off the channel, matches them against the internal route list and calls the
|
||||||
// associated callback (or the defaultHandler, if one exists and no other route matched). If
|
// associated callback (or the defaultHandler, if one exists and no other route matched). If
|
||||||
// anything is sent down the stop channel the function will end.
|
// anything is sent down the stop channel the function will end.
|
||||||
func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client) {
|
func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client) <-chan *PacketAndToken {
|
||||||
go func() {
|
ackChan := make(chan *PacketAndToken) // Channel returned to caller; closed when goroutine terminates
|
||||||
for {
|
|
||||||
select {
|
// In some cases message acknowledgments may come through after shutdown (connection is down etc). Where this is the
|
||||||
case message := <-messages:
|
// case we need to accept any such requests and then ignore them. Note that this is not a perfect solution, if we
|
||||||
sent := false
|
// have reconnected, and the session is still live, then the Ack really should be sent (see Issus #726)
|
||||||
r.RLock()
|
var ackMutex sync.RWMutex
|
||||||
m := messageFromPublish(message, client.ackFunc(message))
|
sendAckChan := ackChan // This will be set to nil before ackChan is closed
|
||||||
handlers := []MessageHandler{}
|
sendAck := func(ack *PacketAndToken) {
|
||||||
for e := r.routes.Front(); e != nil; e = e.Next() {
|
ackMutex.RLock()
|
||||||
if e.Value.(*route).match(message.TopicName) {
|
defer ackMutex.RUnlock()
|
||||||
if order {
|
if sendAckChan != nil {
|
||||||
handlers = append(handlers, e.Value.(*route).callback)
|
sendAckChan <- ack
|
||||||
} else {
|
} else {
|
||||||
hd := e.Value.(*route).callback
|
DEBUG.Println(ROU, "matchAndDispatch received acknowledgment after processing stopped (ACK dropped).")
|
||||||
go func() {
|
}
|
||||||
hd(client, m)
|
}
|
||||||
|
|
||||||
|
go func() { // Main go routine handling inbound messages
|
||||||
|
var handlers []MessageHandler
|
||||||
|
for message := range messages {
|
||||||
|
// DEBUG.Println(ROU, "matchAndDispatch received message")
|
||||||
|
sent := false
|
||||||
|
r.RLock()
|
||||||
|
m := messageFromPublish(message, ackFunc(sendAck, client.persist, message))
|
||||||
|
for e := r.routes.Front(); e != nil; e = e.Next() {
|
||||||
|
if e.Value.(*route).match(message.TopicName) {
|
||||||
|
if order {
|
||||||
|
handlers = append(handlers, e.Value.(*route).callback)
|
||||||
|
} else {
|
||||||
|
hd := e.Value.(*route).callback
|
||||||
|
go func() {
|
||||||
|
hd(client, m)
|
||||||
|
if !client.options.AutoAckDisabled {
|
||||||
m.Ack()
|
m.Ack()
|
||||||
}()
|
}
|
||||||
}
|
}()
|
||||||
sent = true
|
|
||||||
}
|
}
|
||||||
|
sent = true
|
||||||
}
|
}
|
||||||
if !sent && r.defaultHandler != nil {
|
}
|
||||||
|
if !sent {
|
||||||
|
if r.defaultHandler != nil {
|
||||||
if order {
|
if order {
|
||||||
handlers = append(handlers, r.defaultHandler)
|
handlers = append(handlers, r.defaultHandler)
|
||||||
} else {
|
} else {
|
||||||
go func() {
|
go func() {
|
||||||
r.defaultHandler(client, m)
|
r.defaultHandler(client, m)
|
||||||
m.Ack()
|
if !client.options.AutoAckDisabled {
|
||||||
|
m.Ack()
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
DEBUG.Println(ROU, "matchAndDispatch received message and no handler was available. Message will NOT be acknowledged.")
|
||||||
}
|
}
|
||||||
r.RUnlock()
|
|
||||||
for _, handler := range handlers {
|
|
||||||
func() {
|
|
||||||
handler(client, m)
|
|
||||||
m.Ack()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
case <-r.stop:
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
r.RUnlock()
|
||||||
|
if order {
|
||||||
|
for _, handler := range handlers {
|
||||||
|
handler(client, m)
|
||||||
|
if !client.options.AutoAckDisabled {
|
||||||
|
m.Ack()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handlers = handlers[:0]
|
||||||
|
}
|
||||||
|
// DEBUG.Println(ROU, "matchAndDispatch handled message")
|
||||||
}
|
}
|
||||||
|
ackMutex.Lock()
|
||||||
|
sendAckChan = nil
|
||||||
|
ackMutex.Unlock()
|
||||||
|
close(ackChan) // as sendAckChan is now nil nothing further will be sent on this
|
||||||
|
DEBUG.Println(ROU, "matchAndDispatch exiting")
|
||||||
}()
|
}()
|
||||||
|
return ackChan
|
||||||
}
|
}
|
||||||
|
|||||||
296
vendor/github.com/eclipse/paho.mqtt.golang/status.go
generated
vendored
Normal file
296
vendor/github.com/eclipse/paho.mqtt.golang/status.go
generated
vendored
Normal file
@@ -0,0 +1,296 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Seth Hoenig
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
* Mike Robertson
|
||||||
|
* Matt Brittan
|
||||||
|
*/
|
||||||
|
|
||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Status - Manage the connection status
|
||||||
|
|
||||||
|
// Multiple go routines will want to access/set this. Previously status was implemented as a `uint32` and updated
|
||||||
|
// with a mixture of atomic functions and a mutex (leading to some deadlock type issues that were very hard to debug).
|
||||||
|
|
||||||
|
// In this new implementation `connectionStatus` takes over managing the state and provides functions that allow the
|
||||||
|
// client to request a move to a particular state (it may reject these requests!). In some cases the 'state' is
|
||||||
|
// transitory, for example `connecting`, in those cases a function will be returned that allows the client to move
|
||||||
|
// to a more static state (`disconnected` or `connected`).
|
||||||
|
|
||||||
|
// This "belts-and-braces" may be a little over the top but issues with the status have caused a number of difficult
|
||||||
|
// to trace bugs in the past and the likelihood that introducing a new system would introduce bugs seemed high!
|
||||||
|
// I have written this in a way that should make it very difficult to misuse it (but it does make things a little
|
||||||
|
// complex with functions returning functions that return functions!).
|
||||||
|
|
||||||
|
type status uint32
|
||||||
|
|
||||||
|
const (
|
||||||
|
disconnected status = iota // default (nil) status is disconnected
|
||||||
|
disconnecting // Transitioning from one of the below states back to disconnected
|
||||||
|
connecting
|
||||||
|
reconnecting
|
||||||
|
connected
|
||||||
|
)
|
||||||
|
|
||||||
|
// String simplify output of statuses
|
||||||
|
func (s status) String() string {
|
||||||
|
switch s {
|
||||||
|
case disconnected:
|
||||||
|
return "disconnected"
|
||||||
|
case disconnecting:
|
||||||
|
return "disconnecting"
|
||||||
|
case connecting:
|
||||||
|
return "connecting"
|
||||||
|
case reconnecting:
|
||||||
|
return "reconnecting"
|
||||||
|
case connected:
|
||||||
|
return "connected"
|
||||||
|
default:
|
||||||
|
return "invalid"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type connCompletedFn func(success bool) error
|
||||||
|
type disconnectCompletedFn func()
|
||||||
|
type connectionLostHandledFn func(bool) (connCompletedFn, error)
|
||||||
|
|
||||||
|
/* State transitions
|
||||||
|
|
||||||
|
static states are `disconnected` and `connected`. For all other states a process will hold a function that will move
|
||||||
|
the state to one of those. That function effectively owns the state and any other changes must not proceed until it
|
||||||
|
completes. One exception to that is that the state can always be moved to `disconnecting` which provides a signal that
|
||||||
|
transitions to `connected` will be rejected (this is required because a Disconnect can be requested while in the
|
||||||
|
Connecting state).
|
||||||
|
|
||||||
|
# Basic Operations
|
||||||
|
|
||||||
|
The standard workflows are:
|
||||||
|
|
||||||
|
disconnected -> `Connecting()` -> connecting -> `connCompletedFn(true)` -> connected
|
||||||
|
connected -> `Disconnecting()` -> disconnecting -> `disconnectCompletedFn()` -> disconnected
|
||||||
|
connected -> `ConnectionLost(false)` -> disconnecting -> `connectionLostHandledFn(true/false)` -> disconnected
|
||||||
|
connected -> `ConnectionLost(true)` -> disconnecting -> `connectionLostHandledFn(true)` -> connected
|
||||||
|
|
||||||
|
Unfortunately the above workflows are complicated by the fact that `Disconnecting()` or `ConnectionLost()` may,
|
||||||
|
potentially, be called at any time (i.e. whilst in the middle of transitioning between states). If this happens:
|
||||||
|
|
||||||
|
* The state will be set to disconnecting (which will prevent any request to move the status to connected)
|
||||||
|
* The call to `Disconnecting()`/`ConnectionLost()` will block until the previously active call completes and then
|
||||||
|
handle the disconnection.
|
||||||
|
|
||||||
|
Reading the tests (unit_status_test.go) might help understand these rules.
|
||||||
|
*/
|
||||||
|
|
||||||
|
var (
|
||||||
|
errAbortConnection = errors.New("disconnect called whist connection attempt in progress")
|
||||||
|
errAlreadyConnectedOrReconnecting = errors.New("status is already connected or reconnecting")
|
||||||
|
errStatusMustBeDisconnected = errors.New("status can only transition to connecting from disconnected")
|
||||||
|
errAlreadyDisconnected = errors.New("status is already disconnected")
|
||||||
|
errDisconnectionRequested = errors.New("disconnection was requested whilst the action was in progress")
|
||||||
|
errDisconnectionInProgress = errors.New("disconnection already in progress")
|
||||||
|
errAlreadyHandlingConnectionLoss = errors.New("status is already Connection Lost")
|
||||||
|
errConnLossWhileDisconnecting = errors.New("connection status is disconnecting so loss of connection is expected")
|
||||||
|
)
|
||||||
|
|
||||||
|
// connectionStatus encapsulates, and protects, the connection status.
|
||||||
|
type connectionStatus struct {
|
||||||
|
sync.RWMutex // Protects the variables below
|
||||||
|
status status
|
||||||
|
willReconnect bool // only used when status == disconnecting. Indicates that an attempt will be made to reconnect (allows us to abort that)
|
||||||
|
|
||||||
|
// Some statuses are transitional (e.g. connecting, connectionLost, reconnecting, disconnecting), that is, whatever
|
||||||
|
// process moves us into that status will move us out of it when an action is complete. Sometimes other users
|
||||||
|
// will need to know when the action is complete (e.g. the user calls `Disconnect()` whilst the status is
|
||||||
|
// `connecting`). `actionCompleted` will be set whenever we move into one of the above statues and the channel
|
||||||
|
// returned to anything else requesting a status change. The channel will be closed when the operation is complete.
|
||||||
|
actionCompleted chan struct{} // Only valid whilst status is Connecting or Reconnecting; will be closed when connection completed (success or failure)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectionStatus returns the connection status.
|
||||||
|
// WARNING: the status may change at any time so users should not assume they are the only goroutine touching this
|
||||||
|
func (c *connectionStatus) ConnectionStatus() status {
|
||||||
|
c.RLock()
|
||||||
|
defer c.RUnlock()
|
||||||
|
return c.status
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectionStatusRetry returns the connection status and retry flag (indicates that we expect to reconnect).
|
||||||
|
// WARNING: the status may change at any time so users should not assume they are the only goroutine touching this
|
||||||
|
func (c *connectionStatus) ConnectionStatusRetry() (status, bool) {
|
||||||
|
c.RLock()
|
||||||
|
defer c.RUnlock()
|
||||||
|
return c.status, c.willReconnect
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connecting - Changes the status to connecting if that is a permitted operation
|
||||||
|
// Will do nothing unless the current status is disconnected
|
||||||
|
// Returns a function that MUST be called when the operation is complete (pass in true if successful)
|
||||||
|
func (c *connectionStatus) Connecting() (connCompletedFn, error) {
|
||||||
|
c.Lock()
|
||||||
|
defer c.Unlock()
|
||||||
|
// Calling Connect when already connecting (or if reconnecting) may not always be considered an error
|
||||||
|
if c.status == connected || c.status == reconnecting {
|
||||||
|
return nil, errAlreadyConnectedOrReconnecting
|
||||||
|
}
|
||||||
|
if c.status != disconnected {
|
||||||
|
return nil, errStatusMustBeDisconnected
|
||||||
|
}
|
||||||
|
c.status = connecting
|
||||||
|
c.actionCompleted = make(chan struct{})
|
||||||
|
return c.connected, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// connected is an internal function (it is returned by functions that set the status to connecting or reconnecting,
|
||||||
|
// calling it completes the operation). `success` is used to indicate whether the operation was successfully completed.
|
||||||
|
func (c *connectionStatus) connected(success bool) error {
|
||||||
|
c.Lock()
|
||||||
|
defer func() {
|
||||||
|
close(c.actionCompleted) // Alert anything waiting on the connection process to complete
|
||||||
|
c.actionCompleted = nil // Be tidy
|
||||||
|
c.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Status may have moved to disconnecting in the interim (i.e. at users request)
|
||||||
|
if c.status == disconnecting {
|
||||||
|
return errAbortConnection
|
||||||
|
}
|
||||||
|
if success {
|
||||||
|
c.status = connected
|
||||||
|
} else {
|
||||||
|
c.status = disconnected
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disconnecting - should be called when beginning the disconnection process (cleanup etc.).
|
||||||
|
// Can be called from ANY status and the end result will always be a status of disconnected
|
||||||
|
// Note that if a connection/reconnection attempt is in progress this function will set the status to `disconnecting`
|
||||||
|
// then block until the connection process completes (or aborts).
|
||||||
|
// Returns a function that MUST be called when the operation is complete (assumed to always be successful!)
|
||||||
|
func (c *connectionStatus) Disconnecting() (disconnectCompletedFn, error) {
|
||||||
|
c.Lock()
|
||||||
|
if c.status == disconnected {
|
||||||
|
c.Unlock()
|
||||||
|
return nil, errAlreadyDisconnected // May not always be treated as an error
|
||||||
|
}
|
||||||
|
if c.status == disconnecting { // Need to wait for existing process to complete
|
||||||
|
c.willReconnect = false // Ensure that the existing disconnect process will not reconnect
|
||||||
|
disConnectDone := c.actionCompleted
|
||||||
|
c.Unlock()
|
||||||
|
<-disConnectDone // Wait for existing operation to complete
|
||||||
|
return nil, errAlreadyDisconnected // Well we are now!
|
||||||
|
}
|
||||||
|
|
||||||
|
prevStatus := c.status
|
||||||
|
c.status = disconnecting
|
||||||
|
|
||||||
|
// We may need to wait for connection/reconnection process to complete (they should regularly check the status)
|
||||||
|
if prevStatus == connecting || prevStatus == reconnecting {
|
||||||
|
connectDone := c.actionCompleted
|
||||||
|
c.Unlock() // Safe because the only way to leave the disconnecting status is via this function
|
||||||
|
<-connectDone
|
||||||
|
|
||||||
|
if prevStatus == reconnecting && !c.willReconnect {
|
||||||
|
return nil, errAlreadyDisconnected // Following connectionLost process we will be disconnected
|
||||||
|
}
|
||||||
|
c.Lock()
|
||||||
|
}
|
||||||
|
c.actionCompleted = make(chan struct{})
|
||||||
|
c.Unlock()
|
||||||
|
return c.disconnectionCompleted, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// disconnectionCompleted is an internal function (it is returned by functions that set the status to disconnecting)
|
||||||
|
func (c *connectionStatus) disconnectionCompleted() {
|
||||||
|
c.Lock()
|
||||||
|
defer c.Unlock()
|
||||||
|
c.status = disconnected
|
||||||
|
close(c.actionCompleted) // Alert anything waiting on the connection process to complete
|
||||||
|
c.actionCompleted = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectionLost - should be called when the connection is lost.
|
||||||
|
// This really only differs from Disconnecting in that we may transition into a reconnection (but that could be
|
||||||
|
// cancelled something else calls Disconnecting in the meantime).
|
||||||
|
// The returned function should be called when cleanup is completed. It will return a function to be called when
|
||||||
|
// reconnect completes (or nil if no reconnect requested/disconnect called in the interim).
|
||||||
|
// Note: This function may block if a connection is in progress (the move to connected will be rejected)
|
||||||
|
func (c *connectionStatus) ConnectionLost(willReconnect bool) (connectionLostHandledFn, error) {
|
||||||
|
c.Lock()
|
||||||
|
defer c.Unlock()
|
||||||
|
if c.status == disconnected {
|
||||||
|
return nil, errAlreadyDisconnected
|
||||||
|
}
|
||||||
|
if c.status == disconnecting { // its expected that connection lost will be called during the disconnection process
|
||||||
|
return nil, errDisconnectionInProgress
|
||||||
|
}
|
||||||
|
|
||||||
|
c.willReconnect = willReconnect
|
||||||
|
prevStatus := c.status
|
||||||
|
c.status = disconnecting
|
||||||
|
|
||||||
|
// There is a slight possibility that a connection attempt is in progress (connection up and goroutines started but
|
||||||
|
// status not yet changed). By changing the status we ensure that process will exit cleanly
|
||||||
|
if prevStatus == connecting || prevStatus == reconnecting {
|
||||||
|
connectDone := c.actionCompleted
|
||||||
|
c.Unlock() // Safe because the only way to leave the disconnecting status is via this function
|
||||||
|
<-connectDone
|
||||||
|
c.Lock()
|
||||||
|
if !willReconnect {
|
||||||
|
// In this case the connection will always be aborted so there is nothing more for us to do
|
||||||
|
return nil, errAlreadyDisconnected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.actionCompleted = make(chan struct{})
|
||||||
|
|
||||||
|
return c.getConnectionLostHandler(willReconnect), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// getConnectionLostHandler is an internal function. It returns the function to be returned by ConnectionLost
|
||||||
|
func (c *connectionStatus) getConnectionLostHandler(reconnectRequested bool) connectionLostHandledFn {
|
||||||
|
return func(proceed bool) (connCompletedFn, error) {
|
||||||
|
// Note that connCompletedFn will only be provided if both reconnectRequested and proceed are true
|
||||||
|
c.Lock()
|
||||||
|
defer c.Unlock()
|
||||||
|
|
||||||
|
// `Disconnecting()` may have been called while the disconnection was being processed (this makes it permanent!)
|
||||||
|
if !c.willReconnect || !proceed {
|
||||||
|
c.status = disconnected
|
||||||
|
close(c.actionCompleted) // Alert anything waiting on the connection process to complete
|
||||||
|
c.actionCompleted = nil
|
||||||
|
if !reconnectRequested || !proceed {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, errDisconnectionRequested
|
||||||
|
}
|
||||||
|
|
||||||
|
c.status = reconnecting
|
||||||
|
return c.connected, nil // Note that c.actionCompleted is still live and will be closed in connected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// forceConnectionStatus - forces the connection status to the specified value.
|
||||||
|
// This should only be used when there is no alternative (i.e. only in tests and to recover from situations that
|
||||||
|
// are unexpected)
|
||||||
|
func (c *connectionStatus) forceConnectionStatus(s status) {
|
||||||
|
c.Lock()
|
||||||
|
defer c.Unlock()
|
||||||
|
c.status = s
|
||||||
|
}
|
||||||
14
vendor/github.com/eclipse/paho.mqtt.golang/store.go
generated
vendored
14
vendor/github.com/eclipse/paho.mqtt.golang/store.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -45,7 +49,7 @@ type Store interface {
|
|||||||
// where X is 'i' or 'o'
|
// where X is 'i' or 'o'
|
||||||
func mIDFromKey(key string) uint16 {
|
func mIDFromKey(key string) uint16 {
|
||||||
s := key[2:]
|
s := key[2:]
|
||||||
i, err := strconv.Atoi(s)
|
i, err := strconv.ParseUint(s, 10, 16)
|
||||||
chkerr(err)
|
chkerr(err)
|
||||||
return uint16(i)
|
return uint16(i)
|
||||||
}
|
}
|
||||||
|
|||||||
66
vendor/github.com/eclipse/paho.mqtt.golang/token.go
generated
vendored
66
vendor/github.com/eclipse/paho.mqtt.golang/token.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2014 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Allan Stockdill-Mander
|
* Allan Stockdill-Mander
|
||||||
@@ -13,6 +17,7 @@
|
|||||||
package mqtt
|
package mqtt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -31,8 +36,24 @@ type PacketAndToken struct {
|
|||||||
// Token defines the interface for the tokens used to indicate when
|
// Token defines the interface for the tokens used to indicate when
|
||||||
// actions have completed.
|
// actions have completed.
|
||||||
type Token interface {
|
type Token interface {
|
||||||
|
// Wait will wait indefinitely for the Token to complete, ie the Publish
|
||||||
|
// to be sent and confirmed receipt from the broker.
|
||||||
Wait() bool
|
Wait() bool
|
||||||
|
|
||||||
|
// WaitTimeout takes a time.Duration to wait for the flow associated with the
|
||||||
|
// Token to complete, returns true if it returned before the timeout or
|
||||||
|
// returns false if the timeout occurred. In the case of a timeout the Token
|
||||||
|
// does not have an error set in case the caller wishes to wait again.
|
||||||
WaitTimeout(time.Duration) bool
|
WaitTimeout(time.Duration) bool
|
||||||
|
|
||||||
|
// Done returns a channel that is closed when the flow associated
|
||||||
|
// with the Token completes. Clients should call Error after the
|
||||||
|
// channel is closed to check if the flow completed successfully.
|
||||||
|
//
|
||||||
|
// Done is provided for use in select statements. Simple use cases may
|
||||||
|
// use Wait or WaitTimeout.
|
||||||
|
Done() <-chan struct{}
|
||||||
|
|
||||||
Error() error
|
Error() error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,21 +73,14 @@ type baseToken struct {
|
|||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait will wait indefinitely for the Token to complete, ie the Publish
|
// Wait implements the Token Wait method.
|
||||||
// to be sent and confirmed receipt from the broker
|
|
||||||
func (b *baseToken) Wait() bool {
|
func (b *baseToken) Wait() bool {
|
||||||
<-b.complete
|
<-b.complete
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// WaitTimeout takes a time.Duration to wait for the flow associated with the
|
// WaitTimeout implements the Token WaitTimeout method.
|
||||||
// Token to complete, returns true if it returned before the timeout or
|
|
||||||
// returns false if the timeout occurred. In the case of a timeout the Token
|
|
||||||
// does not have an error set in case the caller wishes to wait again
|
|
||||||
func (b *baseToken) WaitTimeout(d time.Duration) bool {
|
func (b *baseToken) WaitTimeout(d time.Duration) bool {
|
||||||
b.m.Lock()
|
|
||||||
defer b.m.Unlock()
|
|
||||||
|
|
||||||
timer := time.NewTimer(d)
|
timer := time.NewTimer(d)
|
||||||
select {
|
select {
|
||||||
case <-b.complete:
|
case <-b.complete:
|
||||||
@@ -80,6 +94,11 @@ func (b *baseToken) WaitTimeout(d time.Duration) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Done implements the Token Done method.
|
||||||
|
func (b *baseToken) Done() <-chan struct{} {
|
||||||
|
return b.complete
|
||||||
|
}
|
||||||
|
|
||||||
func (b *baseToken) flowComplete() {
|
func (b *baseToken) flowComplete() {
|
||||||
select {
|
select {
|
||||||
case <-b.complete:
|
case <-b.complete:
|
||||||
@@ -125,7 +144,7 @@ type ConnectToken struct {
|
|||||||
sessionPresent bool
|
sessionPresent bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReturnCode returns the acknowlegement code in the connack sent
|
// ReturnCode returns the acknowledgement code in the connack sent
|
||||||
// in response to a Connect()
|
// in response to a Connect()
|
||||||
func (c *ConnectToken) ReturnCode() byte {
|
func (c *ConnectToken) ReturnCode() byte {
|
||||||
c.m.RLock()
|
c.m.RLock()
|
||||||
@@ -160,6 +179,7 @@ type SubscribeToken struct {
|
|||||||
baseToken
|
baseToken
|
||||||
subs []string
|
subs []string
|
||||||
subResult map[string]byte
|
subResult map[string]byte
|
||||||
|
messageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
// Result returns a map of topics that were subscribed to along with
|
// Result returns a map of topics that were subscribed to along with
|
||||||
@@ -175,6 +195,7 @@ func (s *SubscribeToken) Result() map[string]byte {
|
|||||||
// required to provide information about calls to Unsubscribe()
|
// required to provide information about calls to Unsubscribe()
|
||||||
type UnsubscribeToken struct {
|
type UnsubscribeToken struct {
|
||||||
baseToken
|
baseToken
|
||||||
|
messageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
// DisconnectToken is an extension of Token containing the extra fields
|
// DisconnectToken is an extension of Token containing the extra fields
|
||||||
@@ -182,3 +203,20 @@ type UnsubscribeToken struct {
|
|||||||
type DisconnectToken struct {
|
type DisconnectToken struct {
|
||||||
baseToken
|
baseToken
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TimedOut is the error returned by WaitTimeout when the timeout expires
|
||||||
|
var TimedOut = errors.New("context canceled")
|
||||||
|
|
||||||
|
// WaitTokenTimeout is a utility function used to simplify the use of token.WaitTimeout
|
||||||
|
// token.WaitTimeout may return `false` due to time out but t.Error() still results
|
||||||
|
// in nil.
|
||||||
|
// `if t := client.X(); t.WaitTimeout(time.Second) && t.Error() != nil {` may evaluate
|
||||||
|
// to false even if the operation fails.
|
||||||
|
// It is important to note that if TimedOut is returned, then the operation may still be running
|
||||||
|
// and could eventually complete successfully.
|
||||||
|
func WaitTokenTimeout(t Token, d time.Duration) error {
|
||||||
|
if !t.WaitTimeout(d) {
|
||||||
|
return TimedOut
|
||||||
|
}
|
||||||
|
return t.Error()
|
||||||
|
}
|
||||||
|
|||||||
40
vendor/github.com/eclipse/paho.mqtt.golang/topic.go
generated
vendored
40
vendor/github.com/eclipse/paho.mqtt.golang/topic.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2014 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -19,18 +23,18 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
//ErrInvalidQos is the error returned when an packet is to be sent
|
// ErrInvalidQos is the error returned when an packet is to be sent
|
||||||
//with an invalid Qos value
|
// with an invalid Qos value
|
||||||
var ErrInvalidQos = errors.New("Invalid QoS")
|
var ErrInvalidQos = errors.New("invalid QoS")
|
||||||
|
|
||||||
//ErrInvalidTopicEmptyString is the error returned when a topic string
|
// ErrInvalidTopicEmptyString is the error returned when a topic string
|
||||||
//is passed in that is 0 length
|
// is passed in that is 0 length
|
||||||
var ErrInvalidTopicEmptyString = errors.New("Invalid Topic; empty string")
|
var ErrInvalidTopicEmptyString = errors.New("invalid Topic; empty string")
|
||||||
|
|
||||||
//ErrInvalidTopicMultilevel is the error returned when a topic string
|
// ErrInvalidTopicMultilevel is the error returned when a topic string
|
||||||
//is passed in that has the multi level wildcard in any position but
|
// is passed in that has the multi level wildcard in any position but
|
||||||
//the last
|
// the last
|
||||||
var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard must be last level")
|
var ErrInvalidTopicMultilevel = errors.New("invalid Topic; multi-level wildcard must be last level")
|
||||||
|
|
||||||
// Topic Names and Topic Filters
|
// Topic Names and Topic Filters
|
||||||
// The MQTT v3.1.1 spec clarifies a number of ambiguities with regard
|
// The MQTT v3.1.1 spec clarifies a number of ambiguities with regard
|
||||||
@@ -46,10 +50,14 @@ var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard
|
|||||||
// - A TopicName may not contain a wildcard.
|
// - A TopicName may not contain a wildcard.
|
||||||
// - A TopicFilter may only have a # (multi-level) wildcard as the last level.
|
// - A TopicFilter may only have a # (multi-level) wildcard as the last level.
|
||||||
// - A TopicFilter may contain any number of + (single-level) wildcards.
|
// - A TopicFilter may contain any number of + (single-level) wildcards.
|
||||||
// - A TopicFilter with a # will match the absense of a level
|
// - A TopicFilter with a # will match the absence of a level
|
||||||
// Example: a subscription to "foo/#" will match messages published to "foo".
|
// Example: a subscription to "foo/#" will match messages published to "foo".
|
||||||
|
|
||||||
func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error) {
|
func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error) {
|
||||||
|
if len(subs) == 0 {
|
||||||
|
return nil, nil, errors.New("invalid subscription; subscribe map must not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
var topics []string
|
var topics []string
|
||||||
var qoss []byte
|
var qoss []byte
|
||||||
for topic, qos := range subs {
|
for topic, qos := range subs {
|
||||||
@@ -75,7 +83,7 @@ func validateTopicAndQos(topic string, qos byte) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if qos < 0 || qos > 2 {
|
if qos > 2 {
|
||||||
return ErrInvalidQos
|
return ErrInvalidQos
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
14
vendor/github.com/eclipse/paho.mqtt.golang/trace.go
generated
vendored
14
vendor/github.com/eclipse/paho.mqtt.golang/trace.go
generated
vendored
@@ -1,10 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013 IBM Corp.
|
* Copyright (c) 2021 IBM Corp and others.
|
||||||
*
|
*
|
||||||
* All rights reserved. This program and the accompanying materials
|
* All rights reserved. This program and the accompanying materials
|
||||||
* are made available under the terms of the Eclipse Public License v1.0
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
* which accompanies this distribution, and is available at
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
* http://www.eclipse.org/legal/epl-v10.html
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
*
|
*
|
||||||
* Contributors:
|
* Contributors:
|
||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
@@ -27,7 +31,7 @@ type (
|
|||||||
NOOPLogger struct{}
|
NOOPLogger struct{}
|
||||||
)
|
)
|
||||||
|
|
||||||
func (NOOPLogger) Println(v ...interface{}) {}
|
func (NOOPLogger) Println(v ...interface{}) {}
|
||||||
func (NOOPLogger) Printf(format string, v ...interface{}) {}
|
func (NOOPLogger) Printf(format string, v ...interface{}) {}
|
||||||
|
|
||||||
// Internal levels of library output that are initialised to not print
|
// Internal levels of library output that are initialised to not print
|
||||||
|
|||||||
132
vendor/github.com/eclipse/paho.mqtt.golang/websocket.go
generated
vendored
Normal file
132
vendor/github.com/eclipse/paho.mqtt.golang/websocket.go
generated
vendored
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
/*
|
||||||
|
* This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v2.0
|
||||||
|
* and Eclipse Distribution License v1.0 which accompany this distribution.
|
||||||
|
*
|
||||||
|
* The Eclipse Public License is available at
|
||||||
|
* https://www.eclipse.org/legal/epl-2.0/
|
||||||
|
* and the Eclipse Distribution License is available at
|
||||||
|
* http://www.eclipse.org/org/documents/edl-v10.php.
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
*/
|
||||||
|
|
||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WebsocketOptions are config options for a websocket dialer
|
||||||
|
type WebsocketOptions struct {
|
||||||
|
ReadBufferSize int
|
||||||
|
WriteBufferSize int
|
||||||
|
Proxy ProxyFunction
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyFunction func(req *http.Request) (*url.URL, error)
|
||||||
|
|
||||||
|
// NewWebsocket returns a new websocket and returns a net.Conn compatible interface using the gorilla/websocket package
|
||||||
|
func NewWebsocket(host string, tlsc *tls.Config, timeout time.Duration, requestHeader http.Header, options *WebsocketOptions) (net.Conn, error) {
|
||||||
|
if timeout == 0 {
|
||||||
|
timeout = 10 * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
if options == nil {
|
||||||
|
// Apply default options
|
||||||
|
options = &WebsocketOptions{}
|
||||||
|
}
|
||||||
|
if options.Proxy == nil {
|
||||||
|
options.Proxy = http.ProxyFromEnvironment
|
||||||
|
}
|
||||||
|
dialer := &websocket.Dialer{
|
||||||
|
Proxy: options.Proxy,
|
||||||
|
HandshakeTimeout: timeout,
|
||||||
|
EnableCompression: false,
|
||||||
|
TLSClientConfig: tlsc,
|
||||||
|
Subprotocols: []string{"mqtt"},
|
||||||
|
ReadBufferSize: options.ReadBufferSize,
|
||||||
|
WriteBufferSize: options.WriteBufferSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
ws, resp, err := dialer.Dial(host, requestHeader)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if resp != nil {
|
||||||
|
WARN.Println(CLI, fmt.Sprintf("Websocket handshake failure. StatusCode: %d. Body: %s", resp.StatusCode, resp.Body))
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper := &websocketConnector{
|
||||||
|
Conn: ws,
|
||||||
|
}
|
||||||
|
return wrapper, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// websocketConnector is a websocket wrapper so it satisfies the net.Conn interface so it is a
|
||||||
|
// drop in replacement of the golang.org/x/net/websocket package.
|
||||||
|
// Implementation guide taken from https://github.com/gorilla/websocket/issues/282
|
||||||
|
type websocketConnector struct {
|
||||||
|
*websocket.Conn
|
||||||
|
r io.Reader
|
||||||
|
rio sync.Mutex
|
||||||
|
wio sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDeadline sets both the read and write deadlines
|
||||||
|
func (c *websocketConnector) SetDeadline(t time.Time) error {
|
||||||
|
if err := c.SetReadDeadline(t); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err := c.SetWriteDeadline(t)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes data to the websocket
|
||||||
|
func (c *websocketConnector) Write(p []byte) (int, error) {
|
||||||
|
c.wio.Lock()
|
||||||
|
defer c.wio.Unlock()
|
||||||
|
|
||||||
|
err := c.WriteMessage(websocket.BinaryMessage, p)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read reads the current websocket frame
|
||||||
|
func (c *websocketConnector) Read(p []byte) (int, error) {
|
||||||
|
c.rio.Lock()
|
||||||
|
defer c.rio.Unlock()
|
||||||
|
for {
|
||||||
|
if c.r == nil {
|
||||||
|
// Advance to next message.
|
||||||
|
var err error
|
||||||
|
_, c.r, err = c.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n, err := c.r.Read(p)
|
||||||
|
if err == io.EOF {
|
||||||
|
// At end of message.
|
||||||
|
c.r = nil
|
||||||
|
if n > 0 {
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
// No data read, continue to next message.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
}
|
||||||
3
vendor/github.com/golang/protobuf/AUTHORS
generated
vendored
3
vendor/github.com/golang/protobuf/AUTHORS
generated
vendored
@@ -1,3 +0,0 @@
|
|||||||
# This source code refers to The Go Authors for copyright purposes.
|
|
||||||
# The master list of authors is in the main Go distribution,
|
|
||||||
# visible at http://tip.golang.org/AUTHORS.
|
|
||||||
3
vendor/github.com/golang/protobuf/CONTRIBUTORS
generated
vendored
3
vendor/github.com/golang/protobuf/CONTRIBUTORS
generated
vendored
@@ -1,3 +0,0 @@
|
|||||||
# This source code was written by the Go contributors.
|
|
||||||
# The master list of contributors is in the main Go distribution,
|
|
||||||
# visible at http://tip.golang.org/CONTRIBUTORS.
|
|
||||||
253
vendor/github.com/golang/protobuf/proto/clone.go
generated
vendored
253
vendor/github.com/golang/protobuf/proto/clone.go
generated
vendored
@@ -1,253 +0,0 @@
|
|||||||
// Go support for Protocol Buffers - Google's data interchange format
|
|
||||||
//
|
|
||||||
// Copyright 2011 The Go Authors. All rights reserved.
|
|
||||||
// https://github.com/golang/protobuf
|
|
||||||
//
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are
|
|
||||||
// met:
|
|
||||||
//
|
|
||||||
// * Redistributions of source code must retain the above copyright
|
|
||||||
// notice, this list of conditions and the following disclaimer.
|
|
||||||
// * Redistributions in binary form must reproduce the above
|
|
||||||
// copyright notice, this list of conditions and the following disclaimer
|
|
||||||
// in the documentation and/or other materials provided with the
|
|
||||||
// distribution.
|
|
||||||
// * Neither the name of Google Inc. nor the names of its
|
|
||||||
// contributors may be used to endorse or promote products derived from
|
|
||||||
// this software without specific prior written permission.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
// Protocol buffer deep copy and merge.
|
|
||||||
// TODO: RawMessage.
|
|
||||||
|
|
||||||
package proto
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Clone returns a deep copy of a protocol buffer.
|
|
||||||
func Clone(src Message) Message {
|
|
||||||
in := reflect.ValueOf(src)
|
|
||||||
if in.IsNil() {
|
|
||||||
return src
|
|
||||||
}
|
|
||||||
out := reflect.New(in.Type().Elem())
|
|
||||||
dst := out.Interface().(Message)
|
|
||||||
Merge(dst, src)
|
|
||||||
return dst
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merger is the interface representing objects that can merge messages of the same type.
|
|
||||||
type Merger interface {
|
|
||||||
// Merge merges src into this message.
|
|
||||||
// Required and optional fields that are set in src will be set to that value in dst.
|
|
||||||
// Elements of repeated fields will be appended.
|
|
||||||
//
|
|
||||||
// Merge may panic if called with a different argument type than the receiver.
|
|
||||||
Merge(src Message)
|
|
||||||
}
|
|
||||||
|
|
||||||
// generatedMerger is the custom merge method that generated protos will have.
|
|
||||||
// We must add this method since a generate Merge method will conflict with
|
|
||||||
// many existing protos that have a Merge data field already defined.
|
|
||||||
type generatedMerger interface {
|
|
||||||
XXX_Merge(src Message)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge merges src into dst.
|
|
||||||
// Required and optional fields that are set in src will be set to that value in dst.
|
|
||||||
// Elements of repeated fields will be appended.
|
|
||||||
// Merge panics if src and dst are not the same type, or if dst is nil.
|
|
||||||
func Merge(dst, src Message) {
|
|
||||||
if m, ok := dst.(Merger); ok {
|
|
||||||
m.Merge(src)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
in := reflect.ValueOf(src)
|
|
||||||
out := reflect.ValueOf(dst)
|
|
||||||
if out.IsNil() {
|
|
||||||
panic("proto: nil destination")
|
|
||||||
}
|
|
||||||
if in.Type() != out.Type() {
|
|
||||||
panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
|
|
||||||
}
|
|
||||||
if in.IsNil() {
|
|
||||||
return // Merge from nil src is a noop
|
|
||||||
}
|
|
||||||
if m, ok := dst.(generatedMerger); ok {
|
|
||||||
m.XXX_Merge(src)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mergeStruct(out.Elem(), in.Elem())
|
|
||||||
}
|
|
||||||
|
|
||||||
func mergeStruct(out, in reflect.Value) {
|
|
||||||
sprop := GetProperties(in.Type())
|
|
||||||
for i := 0; i < in.NumField(); i++ {
|
|
||||||
f := in.Type().Field(i)
|
|
||||||
if strings.HasPrefix(f.Name, "XXX_") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
if emIn, err := extendable(in.Addr().Interface()); err == nil {
|
|
||||||
emOut, _ := extendable(out.Addr().Interface())
|
|
||||||
mIn, muIn := emIn.extensionsRead()
|
|
||||||
if mIn != nil {
|
|
||||||
mOut := emOut.extensionsWrite()
|
|
||||||
muIn.Lock()
|
|
||||||
mergeExtension(mOut, mIn)
|
|
||||||
muIn.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
uf := in.FieldByName("XXX_unrecognized")
|
|
||||||
if !uf.IsValid() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
uin := uf.Bytes()
|
|
||||||
if len(uin) > 0 {
|
|
||||||
out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// mergeAny performs a merge between two values of the same type.
|
|
||||||
// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
|
|
||||||
// prop is set if this is a struct field (it may be nil).
|
|
||||||
func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
|
|
||||||
if in.Type() == protoMessageType {
|
|
||||||
if !in.IsNil() {
|
|
||||||
if out.IsNil() {
|
|
||||||
out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
|
|
||||||
} else {
|
|
||||||
Merge(out.Interface().(Message), in.Interface().(Message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch in.Kind() {
|
|
||||||
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
|
|
||||||
reflect.String, reflect.Uint32, reflect.Uint64:
|
|
||||||
if !viaPtr && isProto3Zero(in) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
out.Set(in)
|
|
||||||
case reflect.Interface:
|
|
||||||
// Probably a oneof field; copy non-nil values.
|
|
||||||
if in.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Allocate destination if it is not set, or set to a different type.
|
|
||||||
// Otherwise we will merge as normal.
|
|
||||||
if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
|
|
||||||
out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
|
|
||||||
}
|
|
||||||
mergeAny(out.Elem(), in.Elem(), false, nil)
|
|
||||||
case reflect.Map:
|
|
||||||
if in.Len() == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if out.IsNil() {
|
|
||||||
out.Set(reflect.MakeMap(in.Type()))
|
|
||||||
}
|
|
||||||
// For maps with value types of *T or []byte we need to deep copy each value.
|
|
||||||
elemKind := in.Type().Elem().Kind()
|
|
||||||
for _, key := range in.MapKeys() {
|
|
||||||
var val reflect.Value
|
|
||||||
switch elemKind {
|
|
||||||
case reflect.Ptr:
|
|
||||||
val = reflect.New(in.Type().Elem().Elem())
|
|
||||||
mergeAny(val, in.MapIndex(key), false, nil)
|
|
||||||
case reflect.Slice:
|
|
||||||
val = in.MapIndex(key)
|
|
||||||
val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
|
|
||||||
default:
|
|
||||||
val = in.MapIndex(key)
|
|
||||||
}
|
|
||||||
out.SetMapIndex(key, val)
|
|
||||||
}
|
|
||||||
case reflect.Ptr:
|
|
||||||
if in.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if out.IsNil() {
|
|
||||||
out.Set(reflect.New(in.Elem().Type()))
|
|
||||||
}
|
|
||||||
mergeAny(out.Elem(), in.Elem(), true, nil)
|
|
||||||
case reflect.Slice:
|
|
||||||
if in.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if in.Type().Elem().Kind() == reflect.Uint8 {
|
|
||||||
// []byte is a scalar bytes field, not a repeated field.
|
|
||||||
|
|
||||||
// Edge case: if this is in a proto3 message, a zero length
|
|
||||||
// bytes field is considered the zero value, and should not
|
|
||||||
// be merged.
|
|
||||||
if prop != nil && prop.proto3 && in.Len() == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make a deep copy.
|
|
||||||
// Append to []byte{} instead of []byte(nil) so that we never end up
|
|
||||||
// with a nil result.
|
|
||||||
out.SetBytes(append([]byte{}, in.Bytes()...))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
n := in.Len()
|
|
||||||
if out.IsNil() {
|
|
||||||
out.Set(reflect.MakeSlice(in.Type(), 0, n))
|
|
||||||
}
|
|
||||||
switch in.Type().Elem().Kind() {
|
|
||||||
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
|
|
||||||
reflect.String, reflect.Uint32, reflect.Uint64:
|
|
||||||
out.Set(reflect.AppendSlice(out, in))
|
|
||||||
default:
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
x := reflect.Indirect(reflect.New(in.Type().Elem()))
|
|
||||||
mergeAny(x, in.Index(i), false, nil)
|
|
||||||
out.Set(reflect.Append(out, x))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case reflect.Struct:
|
|
||||||
mergeStruct(out, in)
|
|
||||||
default:
|
|
||||||
// unknown type, so not a protocol buffer
|
|
||||||
log.Printf("proto: don't know how to copy %v", in)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func mergeExtension(out, in map[int32]Extension) {
|
|
||||||
for extNum, eIn := range in {
|
|
||||||
eOut := Extension{desc: eIn.desc}
|
|
||||||
if eIn.value != nil {
|
|
||||||
v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
|
|
||||||
mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
|
|
||||||
eOut.value = v.Interface()
|
|
||||||
}
|
|
||||||
if eIn.enc != nil {
|
|
||||||
eOut.enc = make([]byte, len(eIn.enc))
|
|
||||||
copy(eOut.enc, eIn.enc)
|
|
||||||
}
|
|
||||||
|
|
||||||
out[extNum] = eOut
|
|
||||||
}
|
|
||||||
}
|
|
||||||
428
vendor/github.com/golang/protobuf/proto/decode.go
generated
vendored
428
vendor/github.com/golang/protobuf/proto/decode.go
generated
vendored
@@ -1,428 +0,0 @@
|
|||||||
// Go support for Protocol Buffers - Google's data interchange format
|
|
||||||
//
|
|
||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// https://github.com/golang/protobuf
|
|
||||||
//
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are
|
|
||||||
// met:
|
|
||||||
//
|
|
||||||
// * Redistributions of source code must retain the above copyright
|
|
||||||
// notice, this list of conditions and the following disclaimer.
|
|
||||||
// * Redistributions in binary form must reproduce the above
|
|
||||||
// copyright notice, this list of conditions and the following disclaimer
|
|
||||||
// in the documentation and/or other materials provided with the
|
|
||||||
// distribution.
|
|
||||||
// * Neither the name of Google Inc. nor the names of its
|
|
||||||
// contributors may be used to endorse or promote products derived from
|
|
||||||
// this software without specific prior written permission.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
package proto
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Routines for decoding protocol buffer data to construct in-memory representations.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
// errOverflow is returned when an integer is too large to be represented.
|
|
||||||
var errOverflow = errors.New("proto: integer overflow")
|
|
||||||
|
|
||||||
// ErrInternalBadWireType is returned by generated code when an incorrect
|
|
||||||
// wire type is encountered. It does not get returned to user code.
|
|
||||||
var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
|
|
||||||
|
|
||||||
// DecodeVarint reads a varint-encoded integer from the slice.
|
|
||||||
// It returns the integer and the number of bytes consumed, or
|
|
||||||
// zero if there is not enough.
|
|
||||||
// This is the format for the
|
|
||||||
// int32, int64, uint32, uint64, bool, and enum
|
|
||||||
// protocol buffer types.
|
|
||||||
func DecodeVarint(buf []byte) (x uint64, n int) {
|
|
||||||
for shift := uint(0); shift < 64; shift += 7 {
|
|
||||||
if n >= len(buf) {
|
|
||||||
return 0, 0
|
|
||||||
}
|
|
||||||
b := uint64(buf[n])
|
|
||||||
n++
|
|
||||||
x |= (b & 0x7F) << shift
|
|
||||||
if (b & 0x80) == 0 {
|
|
||||||
return x, n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The number is too large to represent in a 64-bit value.
|
|
||||||
return 0, 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
|
|
||||||
i := p.index
|
|
||||||
l := len(p.buf)
|
|
||||||
|
|
||||||
for shift := uint(0); shift < 64; shift += 7 {
|
|
||||||
if i >= l {
|
|
||||||
err = io.ErrUnexpectedEOF
|
|
||||||
return
|
|
||||||
}
|
|
||||||
b := p.buf[i]
|
|
||||||
i++
|
|
||||||
x |= (uint64(b) & 0x7F) << shift
|
|
||||||
if b < 0x80 {
|
|
||||||
p.index = i
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The number is too large to represent in a 64-bit value.
|
|
||||||
err = errOverflow
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeVarint reads a varint-encoded integer from the Buffer.
|
|
||||||
// This is the format for the
|
|
||||||
// int32, int64, uint32, uint64, bool, and enum
|
|
||||||
// protocol buffer types.
|
|
||||||
func (p *Buffer) DecodeVarint() (x uint64, err error) {
|
|
||||||
i := p.index
|
|
||||||
buf := p.buf
|
|
||||||
|
|
||||||
if i >= len(buf) {
|
|
||||||
return 0, io.ErrUnexpectedEOF
|
|
||||||
} else if buf[i] < 0x80 {
|
|
||||||
p.index++
|
|
||||||
return uint64(buf[i]), nil
|
|
||||||
} else if len(buf)-i < 10 {
|
|
||||||
return p.decodeVarintSlow()
|
|
||||||
}
|
|
||||||
|
|
||||||
var b uint64
|
|
||||||
// we already checked the first byte
|
|
||||||
x = uint64(buf[i]) - 0x80
|
|
||||||
i++
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 7
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 7
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 14
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 14
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 21
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 21
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 28
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 28
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 35
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 35
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 42
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 42
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 49
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 49
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 56
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
x -= 0x80 << 56
|
|
||||||
|
|
||||||
b = uint64(buf[i])
|
|
||||||
i++
|
|
||||||
x += b << 63
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
goto done
|
|
||||||
}
|
|
||||||
// x -= 0x80 << 63 // Always zero.
|
|
||||||
|
|
||||||
return 0, errOverflow
|
|
||||||
|
|
||||||
done:
|
|
||||||
p.index = i
|
|
||||||
return x, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeFixed64 reads a 64-bit integer from the Buffer.
|
|
||||||
// This is the format for the
|
|
||||||
// fixed64, sfixed64, and double protocol buffer types.
|
|
||||||
func (p *Buffer) DecodeFixed64() (x uint64, err error) {
|
|
||||||
// x, err already 0
|
|
||||||
i := p.index + 8
|
|
||||||
if i < 0 || i > len(p.buf) {
|
|
||||||
err = io.ErrUnexpectedEOF
|
|
||||||
return
|
|
||||||
}
|
|
||||||
p.index = i
|
|
||||||
|
|
||||||
x = uint64(p.buf[i-8])
|
|
||||||
x |= uint64(p.buf[i-7]) << 8
|
|
||||||
x |= uint64(p.buf[i-6]) << 16
|
|
||||||
x |= uint64(p.buf[i-5]) << 24
|
|
||||||
x |= uint64(p.buf[i-4]) << 32
|
|
||||||
x |= uint64(p.buf[i-3]) << 40
|
|
||||||
x |= uint64(p.buf[i-2]) << 48
|
|
||||||
x |= uint64(p.buf[i-1]) << 56
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeFixed32 reads a 32-bit integer from the Buffer.
|
|
||||||
// This is the format for the
|
|
||||||
// fixed32, sfixed32, and float protocol buffer types.
|
|
||||||
func (p *Buffer) DecodeFixed32() (x uint64, err error) {
|
|
||||||
// x, err already 0
|
|
||||||
i := p.index + 4
|
|
||||||
if i < 0 || i > len(p.buf) {
|
|
||||||
err = io.ErrUnexpectedEOF
|
|
||||||
return
|
|
||||||
}
|
|
||||||
p.index = i
|
|
||||||
|
|
||||||
x = uint64(p.buf[i-4])
|
|
||||||
x |= uint64(p.buf[i-3]) << 8
|
|
||||||
x |= uint64(p.buf[i-2]) << 16
|
|
||||||
x |= uint64(p.buf[i-1]) << 24
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
|
|
||||||
// from the Buffer.
|
|
||||||
// This is the format used for the sint64 protocol buffer type.
|
|
||||||
func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
|
|
||||||
x, err = p.DecodeVarint()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
|
|
||||||
// from the Buffer.
|
|
||||||
// This is the format used for the sint32 protocol buffer type.
|
|
||||||
func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
|
|
||||||
x, err = p.DecodeVarint()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
|
|
||||||
// This is the format used for the bytes protocol buffer
|
|
||||||
// type and for embedded messages.
|
|
||||||
func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
|
|
||||||
n, err := p.DecodeVarint()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
nb := int(n)
|
|
||||||
if nb < 0 {
|
|
||||||
return nil, fmt.Errorf("proto: bad byte length %d", nb)
|
|
||||||
}
|
|
||||||
end := p.index + nb
|
|
||||||
if end < p.index || end > len(p.buf) {
|
|
||||||
return nil, io.ErrUnexpectedEOF
|
|
||||||
}
|
|
||||||
|
|
||||||
if !alloc {
|
|
||||||
// todo: check if can get more uses of alloc=false
|
|
||||||
buf = p.buf[p.index:end]
|
|
||||||
p.index += nb
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
buf = make([]byte, nb)
|
|
||||||
copy(buf, p.buf[p.index:])
|
|
||||||
p.index += nb
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeStringBytes reads an encoded string from the Buffer.
|
|
||||||
// This is the format used for the proto2 string type.
|
|
||||||
func (p *Buffer) DecodeStringBytes() (s string, err error) {
|
|
||||||
buf, err := p.DecodeRawBytes(false)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return string(buf), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unmarshaler is the interface representing objects that can
|
|
||||||
// unmarshal themselves. The argument points to data that may be
|
|
||||||
// overwritten, so implementations should not keep references to the
|
|
||||||
// buffer.
|
|
||||||
// Unmarshal implementations should not clear the receiver.
|
|
||||||
// Any unmarshaled data should be merged into the receiver.
|
|
||||||
// Callers of Unmarshal that do not want to retain existing data
|
|
||||||
// should Reset the receiver before calling Unmarshal.
|
|
||||||
type Unmarshaler interface {
|
|
||||||
Unmarshal([]byte) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// newUnmarshaler is the interface representing objects that can
|
|
||||||
// unmarshal themselves. The semantics are identical to Unmarshaler.
|
|
||||||
//
|
|
||||||
// This exists to support protoc-gen-go generated messages.
|
|
||||||
// The proto package will stop type-asserting to this interface in the future.
|
|
||||||
//
|
|
||||||
// DO NOT DEPEND ON THIS.
|
|
||||||
type newUnmarshaler interface {
|
|
||||||
XXX_Unmarshal([]byte) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unmarshal parses the protocol buffer representation in buf and places the
|
|
||||||
// decoded result in pb. If the struct underlying pb does not match
|
|
||||||
// the data in buf, the results can be unpredictable.
|
|
||||||
//
|
|
||||||
// Unmarshal resets pb before starting to unmarshal, so any
|
|
||||||
// existing data in pb is always removed. Use UnmarshalMerge
|
|
||||||
// to preserve and append to existing data.
|
|
||||||
func Unmarshal(buf []byte, pb Message) error {
|
|
||||||
pb.Reset()
|
|
||||||
if u, ok := pb.(newUnmarshaler); ok {
|
|
||||||
return u.XXX_Unmarshal(buf)
|
|
||||||
}
|
|
||||||
if u, ok := pb.(Unmarshaler); ok {
|
|
||||||
return u.Unmarshal(buf)
|
|
||||||
}
|
|
||||||
return NewBuffer(buf).Unmarshal(pb)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalMerge parses the protocol buffer representation in buf and
|
|
||||||
// writes the decoded result to pb. If the struct underlying pb does not match
|
|
||||||
// the data in buf, the results can be unpredictable.
|
|
||||||
//
|
|
||||||
// UnmarshalMerge merges into existing data in pb.
|
|
||||||
// Most code should use Unmarshal instead.
|
|
||||||
func UnmarshalMerge(buf []byte, pb Message) error {
|
|
||||||
if u, ok := pb.(newUnmarshaler); ok {
|
|
||||||
return u.XXX_Unmarshal(buf)
|
|
||||||
}
|
|
||||||
if u, ok := pb.(Unmarshaler); ok {
|
|
||||||
// NOTE: The history of proto have unfortunately been inconsistent
|
|
||||||
// whether Unmarshaler should or should not implicitly clear itself.
|
|
||||||
// Some implementations do, most do not.
|
|
||||||
// Thus, calling this here may or may not do what people want.
|
|
||||||
//
|
|
||||||
// See https://github.com/golang/protobuf/issues/424
|
|
||||||
return u.Unmarshal(buf)
|
|
||||||
}
|
|
||||||
return NewBuffer(buf).Unmarshal(pb)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeMessage reads a count-delimited message from the Buffer.
|
|
||||||
func (p *Buffer) DecodeMessage(pb Message) error {
|
|
||||||
enc, err := p.DecodeRawBytes(false)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return NewBuffer(enc).Unmarshal(pb)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeGroup reads a tag-delimited group from the Buffer.
|
|
||||||
// StartGroup tag is already consumed. This function consumes
|
|
||||||
// EndGroup tag.
|
|
||||||
func (p *Buffer) DecodeGroup(pb Message) error {
|
|
||||||
b := p.buf[p.index:]
|
|
||||||
x, y := findEndGroup(b)
|
|
||||||
if x < 0 {
|
|
||||||
return io.ErrUnexpectedEOF
|
|
||||||
}
|
|
||||||
err := Unmarshal(b[:x], pb)
|
|
||||||
p.index += y
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unmarshal parses the protocol buffer representation in the
|
|
||||||
// Buffer and places the decoded result in pb. If the struct
|
|
||||||
// underlying pb does not match the data in the buffer, the results can be
|
|
||||||
// unpredictable.
|
|
||||||
//
|
|
||||||
// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
|
|
||||||
func (p *Buffer) Unmarshal(pb Message) error {
|
|
||||||
// If the object can unmarshal itself, let it.
|
|
||||||
if u, ok := pb.(newUnmarshaler); ok {
|
|
||||||
err := u.XXX_Unmarshal(p.buf[p.index:])
|
|
||||||
p.index = len(p.buf)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if u, ok := pb.(Unmarshaler); ok {
|
|
||||||
// NOTE: The history of proto have unfortunately been inconsistent
|
|
||||||
// whether Unmarshaler should or should not implicitly clear itself.
|
|
||||||
// Some implementations do, most do not.
|
|
||||||
// Thus, calling this here may or may not do what people want.
|
|
||||||
//
|
|
||||||
// See https://github.com/golang/protobuf/issues/424
|
|
||||||
err := u.Unmarshal(p.buf[p.index:])
|
|
||||||
p.index = len(p.buf)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Slow workaround for messages that aren't Unmarshalers.
|
|
||||||
// This includes some hand-coded .pb.go files and
|
|
||||||
// bootstrap protos.
|
|
||||||
// TODO: fix all of those and then add Unmarshal to
|
|
||||||
// the Message interface. Then:
|
|
||||||
// The cast above and code below can be deleted.
|
|
||||||
// The old unmarshaler can be deleted.
|
|
||||||
// Clients can call Unmarshal directly (can already do that, actually).
|
|
||||||
var info InternalMessageInfo
|
|
||||||
err := info.Unmarshal(pb, p.buf[p.index:])
|
|
||||||
p.index = len(p.buf)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
350
vendor/github.com/golang/protobuf/proto/discard.go
generated
vendored
350
vendor/github.com/golang/protobuf/proto/discard.go
generated
vendored
@@ -1,350 +0,0 @@
|
|||||||
// Go support for Protocol Buffers - Google's data interchange format
|
|
||||||
//
|
|
||||||
// Copyright 2017 The Go Authors. All rights reserved.
|
|
||||||
// https://github.com/golang/protobuf
|
|
||||||
//
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are
|
|
||||||
// met:
|
|
||||||
//
|
|
||||||
// * Redistributions of source code must retain the above copyright
|
|
||||||
// notice, this list of conditions and the following disclaimer.
|
|
||||||
// * Redistributions in binary form must reproduce the above
|
|
||||||
// copyright notice, this list of conditions and the following disclaimer
|
|
||||||
// in the documentation and/or other materials provided with the
|
|
||||||
// distribution.
|
|
||||||
// * Neither the name of Google Inc. nor the names of its
|
|
||||||
// contributors may be used to endorse or promote products derived from
|
|
||||||
// this software without specific prior written permission.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
package proto
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
)
|
|
||||||
|
|
||||||
type generatedDiscarder interface {
|
|
||||||
XXX_DiscardUnknown()
|
|
||||||
}
|
|
||||||
|
|
||||||
// DiscardUnknown recursively discards all unknown fields from this message
|
|
||||||
// and all embedded messages.
|
|
||||||
//
|
|
||||||
// When unmarshaling a message with unrecognized fields, the tags and values
|
|
||||||
// of such fields are preserved in the Message. This allows a later call to
|
|
||||||
// marshal to be able to produce a message that continues to have those
|
|
||||||
// unrecognized fields. To avoid this, DiscardUnknown is used to
|
|
||||||
// explicitly clear the unknown fields after unmarshaling.
|
|
||||||
//
|
|
||||||
// For proto2 messages, the unknown fields of message extensions are only
|
|
||||||
// discarded from messages that have been accessed via GetExtension.
|
|
||||||
func DiscardUnknown(m Message) {
|
|
||||||
if m, ok := m.(generatedDiscarder); ok {
|
|
||||||
m.XXX_DiscardUnknown()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// TODO: Dynamically populate a InternalMessageInfo for legacy messages,
|
|
||||||
// but the master branch has no implementation for InternalMessageInfo,
|
|
||||||
// so it would be more work to replicate that approach.
|
|
||||||
discardLegacy(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DiscardUnknown recursively discards all unknown fields.
|
|
||||||
func (a *InternalMessageInfo) DiscardUnknown(m Message) {
|
|
||||||
di := atomicLoadDiscardInfo(&a.discard)
|
|
||||||
if di == nil {
|
|
||||||
di = getDiscardInfo(reflect.TypeOf(m).Elem())
|
|
||||||
atomicStoreDiscardInfo(&a.discard, di)
|
|
||||||
}
|
|
||||||
di.discard(toPointer(&m))
|
|
||||||
}
|
|
||||||
|
|
||||||
type discardInfo struct {
|
|
||||||
typ reflect.Type
|
|
||||||
|
|
||||||
initialized int32 // 0: only typ is valid, 1: everything is valid
|
|
||||||
lock sync.Mutex
|
|
||||||
|
|
||||||
fields []discardFieldInfo
|
|
||||||
unrecognized field
|
|
||||||
}
|
|
||||||
|
|
||||||
type discardFieldInfo struct {
|
|
||||||
field field // Offset of field, guaranteed to be valid
|
|
||||||
discard func(src pointer)
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
discardInfoMap = map[reflect.Type]*discardInfo{}
|
|
||||||
discardInfoLock sync.Mutex
|
|
||||||
)
|
|
||||||
|
|
||||||
func getDiscardInfo(t reflect.Type) *discardInfo {
|
|
||||||
discardInfoLock.Lock()
|
|
||||||
defer discardInfoLock.Unlock()
|
|
||||||
di := discardInfoMap[t]
|
|
||||||
if di == nil {
|
|
||||||
di = &discardInfo{typ: t}
|
|
||||||
discardInfoMap[t] = di
|
|
||||||
}
|
|
||||||
return di
|
|
||||||
}
|
|
||||||
|
|
||||||
func (di *discardInfo) discard(src pointer) {
|
|
||||||
if src.isNil() {
|
|
||||||
return // Nothing to do.
|
|
||||||
}
|
|
||||||
|
|
||||||
if atomic.LoadInt32(&di.initialized) == 0 {
|
|
||||||
di.computeDiscardInfo()
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, fi := range di.fields {
|
|
||||||
sfp := src.offset(fi.field)
|
|
||||||
fi.discard(sfp)
|
|
||||||
}
|
|
||||||
|
|
||||||
// For proto2 messages, only discard unknown fields in message extensions
|
|
||||||
// that have been accessed via GetExtension.
|
|
||||||
if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
|
|
||||||
// Ignore lock since DiscardUnknown is not concurrency safe.
|
|
||||||
emm, _ := em.extensionsRead()
|
|
||||||
for _, mx := range emm {
|
|
||||||
if m, ok := mx.value.(Message); ok {
|
|
||||||
DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if di.unrecognized.IsValid() {
|
|
||||||
*src.offset(di.unrecognized).toBytes() = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (di *discardInfo) computeDiscardInfo() {
|
|
||||||
di.lock.Lock()
|
|
||||||
defer di.lock.Unlock()
|
|
||||||
if di.initialized != 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
t := di.typ
|
|
||||||
n := t.NumField()
|
|
||||||
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
f := t.Field(i)
|
|
||||||
if strings.HasPrefix(f.Name, "XXX_") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
dfi := discardFieldInfo{field: toField(&f)}
|
|
||||||
tf := f.Type
|
|
||||||
|
|
||||||
// Unwrap tf to get its most basic type.
|
|
||||||
var isPointer, isSlice bool
|
|
||||||
if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
|
|
||||||
isSlice = true
|
|
||||||
tf = tf.Elem()
|
|
||||||
}
|
|
||||||
if tf.Kind() == reflect.Ptr {
|
|
||||||
isPointer = true
|
|
||||||
tf = tf.Elem()
|
|
||||||
}
|
|
||||||
if isPointer && isSlice && tf.Kind() != reflect.Struct {
|
|
||||||
panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
|
|
||||||
}
|
|
||||||
|
|
||||||
switch tf.Kind() {
|
|
||||||
case reflect.Struct:
|
|
||||||
switch {
|
|
||||||
case !isPointer:
|
|
||||||
panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
|
|
||||||
case isSlice: // E.g., []*pb.T
|
|
||||||
di := getDiscardInfo(tf)
|
|
||||||
dfi.discard = func(src pointer) {
|
|
||||||
sps := src.getPointerSlice()
|
|
||||||
for _, sp := range sps {
|
|
||||||
if !sp.isNil() {
|
|
||||||
di.discard(sp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
default: // E.g., *pb.T
|
|
||||||
di := getDiscardInfo(tf)
|
|
||||||
dfi.discard = func(src pointer) {
|
|
||||||
sp := src.getPointer()
|
|
||||||
if !sp.isNil() {
|
|
||||||
di.discard(sp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case reflect.Map:
|
|
||||||
switch {
|
|
||||||
case isPointer || isSlice:
|
|
||||||
panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
|
|
||||||
default: // E.g., map[K]V
|
|
||||||
if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
|
|
||||||
dfi.discard = func(src pointer) {
|
|
||||||
sm := src.asPointerTo(tf).Elem()
|
|
||||||
if sm.Len() == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, key := range sm.MapKeys() {
|
|
||||||
val := sm.MapIndex(key)
|
|
||||||
DiscardUnknown(val.Interface().(Message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
dfi.discard = func(pointer) {} // Noop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case reflect.Interface:
|
|
||||||
// Must be oneof field.
|
|
||||||
switch {
|
|
||||||
case isPointer || isSlice:
|
|
||||||
panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
|
|
||||||
default: // E.g., interface{}
|
|
||||||
// TODO: Make this faster?
|
|
||||||
dfi.discard = func(src pointer) {
|
|
||||||
su := src.asPointerTo(tf).Elem()
|
|
||||||
if !su.IsNil() {
|
|
||||||
sv := su.Elem().Elem().Field(0)
|
|
||||||
if sv.Kind() == reflect.Ptr && sv.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch sv.Type().Kind() {
|
|
||||||
case reflect.Ptr: // Proto struct (e.g., *T)
|
|
||||||
DiscardUnknown(sv.Interface().(Message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
di.fields = append(di.fields, dfi)
|
|
||||||
}
|
|
||||||
|
|
||||||
di.unrecognized = invalidField
|
|
||||||
if f, ok := t.FieldByName("XXX_unrecognized"); ok {
|
|
||||||
if f.Type != reflect.TypeOf([]byte{}) {
|
|
||||||
panic("expected XXX_unrecognized to be of type []byte")
|
|
||||||
}
|
|
||||||
di.unrecognized = toField(&f)
|
|
||||||
}
|
|
||||||
|
|
||||||
atomic.StoreInt32(&di.initialized, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func discardLegacy(m Message) {
|
|
||||||
v := reflect.ValueOf(m)
|
|
||||||
if v.Kind() != reflect.Ptr || v.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
v = v.Elem()
|
|
||||||
if v.Kind() != reflect.Struct {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
t := v.Type()
|
|
||||||
|
|
||||||
for i := 0; i < v.NumField(); i++ {
|
|
||||||
f := t.Field(i)
|
|
||||||
if strings.HasPrefix(f.Name, "XXX_") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
vf := v.Field(i)
|
|
||||||
tf := f.Type
|
|
||||||
|
|
||||||
// Unwrap tf to get its most basic type.
|
|
||||||
var isPointer, isSlice bool
|
|
||||||
if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
|
|
||||||
isSlice = true
|
|
||||||
tf = tf.Elem()
|
|
||||||
}
|
|
||||||
if tf.Kind() == reflect.Ptr {
|
|
||||||
isPointer = true
|
|
||||||
tf = tf.Elem()
|
|
||||||
}
|
|
||||||
if isPointer && isSlice && tf.Kind() != reflect.Struct {
|
|
||||||
panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
|
|
||||||
}
|
|
||||||
|
|
||||||
switch tf.Kind() {
|
|
||||||
case reflect.Struct:
|
|
||||||
switch {
|
|
||||||
case !isPointer:
|
|
||||||
panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
|
|
||||||
case isSlice: // E.g., []*pb.T
|
|
||||||
for j := 0; j < vf.Len(); j++ {
|
|
||||||
discardLegacy(vf.Index(j).Interface().(Message))
|
|
||||||
}
|
|
||||||
default: // E.g., *pb.T
|
|
||||||
discardLegacy(vf.Interface().(Message))
|
|
||||||
}
|
|
||||||
case reflect.Map:
|
|
||||||
switch {
|
|
||||||
case isPointer || isSlice:
|
|
||||||
panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
|
|
||||||
default: // E.g., map[K]V
|
|
||||||
tv := vf.Type().Elem()
|
|
||||||
if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
|
|
||||||
for _, key := range vf.MapKeys() {
|
|
||||||
val := vf.MapIndex(key)
|
|
||||||
discardLegacy(val.Interface().(Message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case reflect.Interface:
|
|
||||||
// Must be oneof field.
|
|
||||||
switch {
|
|
||||||
case isPointer || isSlice:
|
|
||||||
panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
|
|
||||||
default: // E.g., test_proto.isCommunique_Union interface
|
|
||||||
if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
|
|
||||||
vf = vf.Elem() // E.g., *test_proto.Communique_Msg
|
|
||||||
if !vf.IsNil() {
|
|
||||||
vf = vf.Elem() // E.g., test_proto.Communique_Msg
|
|
||||||
vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
|
|
||||||
if vf.Kind() == reflect.Ptr {
|
|
||||||
discardLegacy(vf.Interface().(Message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
|
|
||||||
if vf.Type() != reflect.TypeOf([]byte{}) {
|
|
||||||
panic("expected XXX_unrecognized to be of type []byte")
|
|
||||||
}
|
|
||||||
vf.Set(reflect.ValueOf([]byte(nil)))
|
|
||||||
}
|
|
||||||
|
|
||||||
// For proto2 messages, only discard unknown fields in message extensions
|
|
||||||
// that have been accessed via GetExtension.
|
|
||||||
if em, err := extendable(m); err == nil {
|
|
||||||
// Ignore lock since discardLegacy is not concurrency safe.
|
|
||||||
emm, _ := em.extensionsRead()
|
|
||||||
for _, mx := range emm {
|
|
||||||
if m, ok := mx.value.(Message); ok {
|
|
||||||
discardLegacy(m)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
203
vendor/github.com/golang/protobuf/proto/encode.go
generated
vendored
203
vendor/github.com/golang/protobuf/proto/encode.go
generated
vendored
@@ -1,203 +0,0 @@
|
|||||||
// Go support for Protocol Buffers - Google's data interchange format
|
|
||||||
//
|
|
||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// https://github.com/golang/protobuf
|
|
||||||
//
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are
|
|
||||||
// met:
|
|
||||||
//
|
|
||||||
// * Redistributions of source code must retain the above copyright
|
|
||||||
// notice, this list of conditions and the following disclaimer.
|
|
||||||
// * Redistributions in binary form must reproduce the above
|
|
||||||
// copyright notice, this list of conditions and the following disclaimer
|
|
||||||
// in the documentation and/or other materials provided with the
|
|
||||||
// distribution.
|
|
||||||
// * Neither the name of Google Inc. nor the names of its
|
|
||||||
// contributors may be used to endorse or promote products derived from
|
|
||||||
// this software without specific prior written permission.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
package proto
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Routines for encoding data into the wire format for protocol buffers.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"reflect"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// errRepeatedHasNil is the error returned if Marshal is called with
|
|
||||||
// a struct with a repeated field containing a nil element.
|
|
||||||
errRepeatedHasNil = errors.New("proto: repeated field has nil element")
|
|
||||||
|
|
||||||
// errOneofHasNil is the error returned if Marshal is called with
|
|
||||||
// a struct with a oneof field containing a nil element.
|
|
||||||
errOneofHasNil = errors.New("proto: oneof field has nil value")
|
|
||||||
|
|
||||||
// ErrNil is the error returned if Marshal is called with nil.
|
|
||||||
ErrNil = errors.New("proto: Marshal called with nil")
|
|
||||||
|
|
||||||
// ErrTooLarge is the error returned if Marshal is called with a
|
|
||||||
// message that encodes to >2GB.
|
|
||||||
ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
|
|
||||||
)
|
|
||||||
|
|
||||||
// The fundamental encoders that put bytes on the wire.
|
|
||||||
// Those that take integer types all accept uint64 and are
|
|
||||||
// therefore of type valueEncoder.
|
|
||||||
|
|
||||||
const maxVarintBytes = 10 // maximum length of a varint
|
|
||||||
|
|
||||||
// EncodeVarint returns the varint encoding of x.
|
|
||||||
// This is the format for the
|
|
||||||
// int32, int64, uint32, uint64, bool, and enum
|
|
||||||
// protocol buffer types.
|
|
||||||
// Not used by the package itself, but helpful to clients
|
|
||||||
// wishing to use the same encoding.
|
|
||||||
func EncodeVarint(x uint64) []byte {
|
|
||||||
var buf [maxVarintBytes]byte
|
|
||||||
var n int
|
|
||||||
for n = 0; x > 127; n++ {
|
|
||||||
buf[n] = 0x80 | uint8(x&0x7F)
|
|
||||||
x >>= 7
|
|
||||||
}
|
|
||||||
buf[n] = uint8(x)
|
|
||||||
n++
|
|
||||||
return buf[0:n]
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeVarint writes a varint-encoded integer to the Buffer.
|
|
||||||
// This is the format for the
|
|
||||||
// int32, int64, uint32, uint64, bool, and enum
|
|
||||||
// protocol buffer types.
|
|
||||||
func (p *Buffer) EncodeVarint(x uint64) error {
|
|
||||||
for x >= 1<<7 {
|
|
||||||
p.buf = append(p.buf, uint8(x&0x7f|0x80))
|
|
||||||
x >>= 7
|
|
||||||
}
|
|
||||||
p.buf = append(p.buf, uint8(x))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SizeVarint returns the varint encoding size of an integer.
|
|
||||||
func SizeVarint(x uint64) int {
|
|
||||||
switch {
|
|
||||||
case x < 1<<7:
|
|
||||||
return 1
|
|
||||||
case x < 1<<14:
|
|
||||||
return 2
|
|
||||||
case x < 1<<21:
|
|
||||||
return 3
|
|
||||||
case x < 1<<28:
|
|
||||||
return 4
|
|
||||||
case x < 1<<35:
|
|
||||||
return 5
|
|
||||||
case x < 1<<42:
|
|
||||||
return 6
|
|
||||||
case x < 1<<49:
|
|
||||||
return 7
|
|
||||||
case x < 1<<56:
|
|
||||||
return 8
|
|
||||||
case x < 1<<63:
|
|
||||||
return 9
|
|
||||||
}
|
|
||||||
return 10
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeFixed64 writes a 64-bit integer to the Buffer.
|
|
||||||
// This is the format for the
|
|
||||||
// fixed64, sfixed64, and double protocol buffer types.
|
|
||||||
func (p *Buffer) EncodeFixed64(x uint64) error {
|
|
||||||
p.buf = append(p.buf,
|
|
||||||
uint8(x),
|
|
||||||
uint8(x>>8),
|
|
||||||
uint8(x>>16),
|
|
||||||
uint8(x>>24),
|
|
||||||
uint8(x>>32),
|
|
||||||
uint8(x>>40),
|
|
||||||
uint8(x>>48),
|
|
||||||
uint8(x>>56))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeFixed32 writes a 32-bit integer to the Buffer.
|
|
||||||
// This is the format for the
|
|
||||||
// fixed32, sfixed32, and float protocol buffer types.
|
|
||||||
func (p *Buffer) EncodeFixed32(x uint64) error {
|
|
||||||
p.buf = append(p.buf,
|
|
||||||
uint8(x),
|
|
||||||
uint8(x>>8),
|
|
||||||
uint8(x>>16),
|
|
||||||
uint8(x>>24))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
|
|
||||||
// to the Buffer.
|
|
||||||
// This is the format used for the sint64 protocol buffer type.
|
|
||||||
func (p *Buffer) EncodeZigzag64(x uint64) error {
|
|
||||||
// use signed number to get arithmetic right shift.
|
|
||||||
return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
|
|
||||||
// to the Buffer.
|
|
||||||
// This is the format used for the sint32 protocol buffer type.
|
|
||||||
func (p *Buffer) EncodeZigzag32(x uint64) error {
|
|
||||||
// use signed number to get arithmetic right shift.
|
|
||||||
return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
|
|
||||||
// This is the format used for the bytes protocol buffer
|
|
||||||
// type and for embedded messages.
|
|
||||||
func (p *Buffer) EncodeRawBytes(b []byte) error {
|
|
||||||
p.EncodeVarint(uint64(len(b)))
|
|
||||||
p.buf = append(p.buf, b...)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeStringBytes writes an encoded string to the Buffer.
|
|
||||||
// This is the format used for the proto2 string type.
|
|
||||||
func (p *Buffer) EncodeStringBytes(s string) error {
|
|
||||||
p.EncodeVarint(uint64(len(s)))
|
|
||||||
p.buf = append(p.buf, s...)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Marshaler is the interface representing objects that can marshal themselves.
|
|
||||||
type Marshaler interface {
|
|
||||||
Marshal() ([]byte, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeMessage writes the protocol buffer to the Buffer,
|
|
||||||
// prefixed by a varint-encoded length.
|
|
||||||
func (p *Buffer) EncodeMessage(pb Message) error {
|
|
||||||
siz := Size(pb)
|
|
||||||
p.EncodeVarint(uint64(siz))
|
|
||||||
return p.Marshal(pb)
|
|
||||||
}
|
|
||||||
|
|
||||||
// All protocol buffer fields are nillable, but be careful.
|
|
||||||
func isNil(v reflect.Value) bool {
|
|
||||||
switch v.Kind() {
|
|
||||||
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
|
|
||||||
return v.IsNil()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
300
vendor/github.com/golang/protobuf/proto/equal.go
generated
vendored
300
vendor/github.com/golang/protobuf/proto/equal.go
generated
vendored
@@ -1,300 +0,0 @@
|
|||||||
// Go support for Protocol Buffers - Google's data interchange format
|
|
||||||
//
|
|
||||||
// Copyright 2011 The Go Authors. All rights reserved.
|
|
||||||
// https://github.com/golang/protobuf
|
|
||||||
//
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are
|
|
||||||
// met:
|
|
||||||
//
|
|
||||||
// * Redistributions of source code must retain the above copyright
|
|
||||||
// notice, this list of conditions and the following disclaimer.
|
|
||||||
// * Redistributions in binary form must reproduce the above
|
|
||||||
// copyright notice, this list of conditions and the following disclaimer
|
|
||||||
// in the documentation and/or other materials provided with the
|
|
||||||
// distribution.
|
|
||||||
// * Neither the name of Google Inc. nor the names of its
|
|
||||||
// contributors may be used to endorse or promote products derived from
|
|
||||||
// this software without specific prior written permission.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
// Protocol buffer comparison.
|
|
||||||
|
|
||||||
package proto
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"log"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
/*
|
|
||||||
Equal returns true iff protocol buffers a and b are equal.
|
|
||||||
The arguments must both be pointers to protocol buffer structs.
|
|
||||||
|
|
||||||
Equality is defined in this way:
|
|
||||||
- Two messages are equal iff they are the same type,
|
|
||||||
corresponding fields are equal, unknown field sets
|
|
||||||
are equal, and extensions sets are equal.
|
|
||||||
- Two set scalar fields are equal iff their values are equal.
|
|
||||||
If the fields are of a floating-point type, remember that
|
|
||||||
NaN != x for all x, including NaN. If the message is defined
|
|
||||||
in a proto3 .proto file, fields are not "set"; specifically,
|
|
||||||
zero length proto3 "bytes" fields are equal (nil == {}).
|
|
||||||
- Two repeated fields are equal iff their lengths are the same,
|
|
||||||
and their corresponding elements are equal. Note a "bytes" field,
|
|
||||||
although represented by []byte, is not a repeated field and the
|
|
||||||
rule for the scalar fields described above applies.
|
|
||||||
- Two unset fields are equal.
|
|
||||||
- Two unknown field sets are equal if their current
|
|
||||||
encoded state is equal.
|
|
||||||
- Two extension sets are equal iff they have corresponding
|
|
||||||
elements that are pairwise equal.
|
|
||||||
- Two map fields are equal iff their lengths are the same,
|
|
||||||
and they contain the same set of elements. Zero-length map
|
|
||||||
fields are equal.
|
|
||||||
- Every other combination of things are not equal.
|
|
||||||
|
|
||||||
The return value is undefined if a and b are not protocol buffers.
|
|
||||||
*/
|
|
||||||
func Equal(a, b Message) bool {
|
|
||||||
if a == nil || b == nil {
|
|
||||||
return a == b
|
|
||||||
}
|
|
||||||
v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
|
|
||||||
if v1.Type() != v2.Type() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if v1.Kind() == reflect.Ptr {
|
|
||||||
if v1.IsNil() {
|
|
||||||
return v2.IsNil()
|
|
||||||
}
|
|
||||||
if v2.IsNil() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
v1, v2 = v1.Elem(), v2.Elem()
|
|
||||||
}
|
|
||||||
if v1.Kind() != reflect.Struct {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return equalStruct(v1, v2)
|
|
||||||
}
|
|
||||||
|
|
||||||
// v1 and v2 are known to have the same type.
|
|
||||||
func equalStruct(v1, v2 reflect.Value) bool {
|
|
||||||
sprop := GetProperties(v1.Type())
|
|
||||||
for i := 0; i < v1.NumField(); i++ {
|
|
||||||
f := v1.Type().Field(i)
|
|
||||||
if strings.HasPrefix(f.Name, "XXX_") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
f1, f2 := v1.Field(i), v2.Field(i)
|
|
||||||
if f.Type.Kind() == reflect.Ptr {
|
|
||||||
if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
|
|
||||||
// both unset
|
|
||||||
continue
|
|
||||||
} else if n1 != n2 {
|
|
||||||
// set/unset mismatch
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
f1, f2 = f1.Elem(), f2.Elem()
|
|
||||||
}
|
|
||||||
if !equalAny(f1, f2, sprop.Prop[i]) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
|
|
||||||
em2 := v2.FieldByName("XXX_InternalExtensions")
|
|
||||||
if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
|
|
||||||
em2 := v2.FieldByName("XXX_extensions")
|
|
||||||
if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
uf := v1.FieldByName("XXX_unrecognized")
|
|
||||||
if !uf.IsValid() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
u1 := uf.Bytes()
|
|
||||||
u2 := v2.FieldByName("XXX_unrecognized").Bytes()
|
|
||||||
return bytes.Equal(u1, u2)
|
|
||||||
}
|
|
||||||
|
|
||||||
// v1 and v2 are known to have the same type.
|
|
||||||
// prop may be nil.
|
|
||||||
func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
|
|
||||||
if v1.Type() == protoMessageType {
|
|
||||||
m1, _ := v1.Interface().(Message)
|
|
||||||
m2, _ := v2.Interface().(Message)
|
|
||||||
return Equal(m1, m2)
|
|
||||||
}
|
|
||||||
switch v1.Kind() {
|
|
||||||
case reflect.Bool:
|
|
||||||
return v1.Bool() == v2.Bool()
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return v1.Float() == v2.Float()
|
|
||||||
case reflect.Int32, reflect.Int64:
|
|
||||||
return v1.Int() == v2.Int()
|
|
||||||
case reflect.Interface:
|
|
||||||
// Probably a oneof field; compare the inner values.
|
|
||||||
n1, n2 := v1.IsNil(), v2.IsNil()
|
|
||||||
if n1 || n2 {
|
|
||||||
return n1 == n2
|
|
||||||
}
|
|
||||||
e1, e2 := v1.Elem(), v2.Elem()
|
|
||||||
if e1.Type() != e2.Type() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return equalAny(e1, e2, nil)
|
|
||||||
case reflect.Map:
|
|
||||||
if v1.Len() != v2.Len() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, key := range v1.MapKeys() {
|
|
||||||
val2 := v2.MapIndex(key)
|
|
||||||
if !val2.IsValid() {
|
|
||||||
// This key was not found in the second map.
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !equalAny(v1.MapIndex(key), val2, nil) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
case reflect.Ptr:
|
|
||||||
// Maps may have nil values in them, so check for nil.
|
|
||||||
if v1.IsNil() && v2.IsNil() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if v1.IsNil() != v2.IsNil() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return equalAny(v1.Elem(), v2.Elem(), prop)
|
|
||||||
case reflect.Slice:
|
|
||||||
if v1.Type().Elem().Kind() == reflect.Uint8 {
|
|
||||||
// short circuit: []byte
|
|
||||||
|
|
||||||
// Edge case: if this is in a proto3 message, a zero length
|
|
||||||
// bytes field is considered the zero value.
|
|
||||||
if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if v1.IsNil() != v2.IsNil() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
|
|
||||||
}
|
|
||||||
|
|
||||||
if v1.Len() != v2.Len() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for i := 0; i < v1.Len(); i++ {
|
|
||||||
if !equalAny(v1.Index(i), v2.Index(i), prop) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
case reflect.String:
|
|
||||||
return v1.Interface().(string) == v2.Interface().(string)
|
|
||||||
case reflect.Struct:
|
|
||||||
return equalStruct(v1, v2)
|
|
||||||
case reflect.Uint32, reflect.Uint64:
|
|
||||||
return v1.Uint() == v2.Uint()
|
|
||||||
}
|
|
||||||
|
|
||||||
// unknown type, so not a protocol buffer
|
|
||||||
log.Printf("proto: don't know how to compare %v", v1)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// base is the struct type that the extensions are based on.
|
|
||||||
// x1 and x2 are InternalExtensions.
|
|
||||||
func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
|
|
||||||
em1, _ := x1.extensionsRead()
|
|
||||||
em2, _ := x2.extensionsRead()
|
|
||||||
return equalExtMap(base, em1, em2)
|
|
||||||
}
|
|
||||||
|
|
||||||
func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
|
|
||||||
if len(em1) != len(em2) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
for extNum, e1 := range em1 {
|
|
||||||
e2, ok := em2[extNum]
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
m1, m2 := e1.value, e2.value
|
|
||||||
|
|
||||||
if m1 == nil && m2 == nil {
|
|
||||||
// Both have only encoded form.
|
|
||||||
if bytes.Equal(e1.enc, e2.enc) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// The bytes are different, but the extensions might still be
|
|
||||||
// equal. We need to decode them to compare.
|
|
||||||
}
|
|
||||||
|
|
||||||
if m1 != nil && m2 != nil {
|
|
||||||
// Both are unencoded.
|
|
||||||
if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// At least one is encoded. To do a semantically correct comparison
|
|
||||||
// we need to unmarshal them first.
|
|
||||||
var desc *ExtensionDesc
|
|
||||||
if m := extensionMaps[base]; m != nil {
|
|
||||||
desc = m[extNum]
|
|
||||||
}
|
|
||||||
if desc == nil {
|
|
||||||
// If both have only encoded form and the bytes are the same,
|
|
||||||
// it is handled above. We get here when the bytes are different.
|
|
||||||
// We don't know how to decode it, so just compare them as byte
|
|
||||||
// slices.
|
|
||||||
log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
if m1 == nil {
|
|
||||||
m1, err = decodeExtension(e1.enc, desc)
|
|
||||||
}
|
|
||||||
if m2 == nil && err == nil {
|
|
||||||
m2, err = decodeExtension(e2.enc, desc)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
// The encoded form is invalid.
|
|
||||||
log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
543
vendor/github.com/golang/protobuf/proto/extensions.go
generated
vendored
543
vendor/github.com/golang/protobuf/proto/extensions.go
generated
vendored
@@ -1,543 +0,0 @@
|
|||||||
// Go support for Protocol Buffers - Google's data interchange format
|
|
||||||
//
|
|
||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// https://github.com/golang/protobuf
|
|
||||||
//
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are
|
|
||||||
// met:
|
|
||||||
//
|
|
||||||
// * Redistributions of source code must retain the above copyright
|
|
||||||
// notice, this list of conditions and the following disclaimer.
|
|
||||||
// * Redistributions in binary form must reproduce the above
|
|
||||||
// copyright notice, this list of conditions and the following disclaimer
|
|
||||||
// in the documentation and/or other materials provided with the
|
|
||||||
// distribution.
|
|
||||||
// * Neither the name of Google Inc. nor the names of its
|
|
||||||
// contributors may be used to endorse or promote products derived from
|
|
||||||
// this software without specific prior written permission.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
package proto
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Types and routines for supporting protocol buffer extensions.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"reflect"
|
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
|
|
||||||
var ErrMissingExtension = errors.New("proto: missing extension")
|
|
||||||
|
|
||||||
// ExtensionRange represents a range of message extensions for a protocol buffer.
|
|
||||||
// Used in code generated by the protocol compiler.
|
|
||||||
type ExtensionRange struct {
|
|
||||||
Start, End int32 // both inclusive
|
|
||||||
}
|
|
||||||
|
|
||||||
// extendableProto is an interface implemented by any protocol buffer generated by the current
|
|
||||||
// proto compiler that may be extended.
|
|
||||||
type extendableProto interface {
|
|
||||||
Message
|
|
||||||
ExtensionRangeArray() []ExtensionRange
|
|
||||||
extensionsWrite() map[int32]Extension
|
|
||||||
extensionsRead() (map[int32]Extension, sync.Locker)
|
|
||||||
}
|
|
||||||
|
|
||||||
// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
|
|
||||||
// version of the proto compiler that may be extended.
|
|
||||||
type extendableProtoV1 interface {
|
|
||||||
Message
|
|
||||||
ExtensionRangeArray() []ExtensionRange
|
|
||||||
ExtensionMap() map[int32]Extension
|
|
||||||
}
|
|
||||||
|
|
||||||
// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
|
|
||||||
type extensionAdapter struct {
|
|
||||||
extendableProtoV1
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e extensionAdapter) extensionsWrite() map[int32]Extension {
|
|
||||||
return e.ExtensionMap()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
|
|
||||||
return e.ExtensionMap(), notLocker{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
|
|
||||||
type notLocker struct{}
|
|
||||||
|
|
||||||
func (n notLocker) Lock() {}
|
|
||||||
func (n notLocker) Unlock() {}
|
|
||||||
|
|
||||||
// extendable returns the extendableProto interface for the given generated proto message.
|
|
||||||
// If the proto message has the old extension format, it returns a wrapper that implements
|
|
||||||
// the extendableProto interface.
|
|
||||||
func extendable(p interface{}) (extendableProto, error) {
|
|
||||||
switch p := p.(type) {
|
|
||||||
case extendableProto:
|
|
||||||
if isNilPtr(p) {
|
|
||||||
return nil, fmt.Errorf("proto: nil %T is not extendable", p)
|
|
||||||
}
|
|
||||||
return p, nil
|
|
||||||
case extendableProtoV1:
|
|
||||||
if isNilPtr(p) {
|
|
||||||
return nil, fmt.Errorf("proto: nil %T is not extendable", p)
|
|
||||||
}
|
|
||||||
return extensionAdapter{p}, nil
|
|
||||||
}
|
|
||||||
// Don't allocate a specific error containing %T:
|
|
||||||
// this is the hot path for Clone and MarshalText.
|
|
||||||
return nil, errNotExtendable
|
|
||||||
}
|
|
||||||
|
|
||||||
var errNotExtendable = errors.New("proto: not an extendable proto.Message")
|
|
||||||
|
|
||||||
func isNilPtr(x interface{}) bool {
|
|
||||||
v := reflect.ValueOf(x)
|
|
||||||
return v.Kind() == reflect.Ptr && v.IsNil()
|
|
||||||
}
|
|
||||||
|
|
||||||
// XXX_InternalExtensions is an internal representation of proto extensions.
|
|
||||||
//
|
|
||||||
// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
|
|
||||||
// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
|
|
||||||
//
|
|
||||||
// The methods of XXX_InternalExtensions are not concurrency safe in general,
|
|
||||||
// but calls to logically read-only methods such as has and get may be executed concurrently.
|
|
||||||
type XXX_InternalExtensions struct {
|
|
||||||
// The struct must be indirect so that if a user inadvertently copies a
|
|
||||||
// generated message and its embedded XXX_InternalExtensions, they
|
|
||||||
// avoid the mayhem of a copied mutex.
|
|
||||||
//
|
|
||||||
// The mutex serializes all logically read-only operations to p.extensionMap.
|
|
||||||
// It is up to the client to ensure that write operations to p.extensionMap are
|
|
||||||
// mutually exclusive with other accesses.
|
|
||||||
p *struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
extensionMap map[int32]Extension
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// extensionsWrite returns the extension map, creating it on first use.
|
|
||||||
func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
|
|
||||||
if e.p == nil {
|
|
||||||
e.p = new(struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
extensionMap map[int32]Extension
|
|
||||||
})
|
|
||||||
e.p.extensionMap = make(map[int32]Extension)
|
|
||||||
}
|
|
||||||
return e.p.extensionMap
|
|
||||||
}
|
|
||||||
|
|
||||||
// extensionsRead returns the extensions map for read-only use. It may be nil.
|
|
||||||
// The caller must hold the returned mutex's lock when accessing Elements within the map.
|
|
||||||
func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
|
|
||||||
if e.p == nil {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return e.p.extensionMap, &e.p.mu
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExtensionDesc represents an extension specification.
|
|
||||||
// Used in generated code from the protocol compiler.
|
|
||||||
type ExtensionDesc struct {
|
|
||||||
ExtendedType Message // nil pointer to the type that is being extended
|
|
||||||
ExtensionType interface{} // nil pointer to the extension type
|
|
||||||
Field int32 // field number
|
|
||||||
Name string // fully-qualified name of extension, for text formatting
|
|
||||||
Tag string // protobuf tag style
|
|
||||||
Filename string // name of the file in which the extension is defined
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ed *ExtensionDesc) repeated() bool {
|
|
||||||
t := reflect.TypeOf(ed.ExtensionType)
|
|
||||||
return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extension represents an extension in a message.
|
|
||||||
type Extension struct {
|
|
||||||
// When an extension is stored in a message using SetExtension
|
|
||||||
// only desc and value are set. When the message is marshaled
|
|
||||||
// enc will be set to the encoded form of the message.
|
|
||||||
//
|
|
||||||
// When a message is unmarshaled and contains extensions, each
|
|
||||||
// extension will have only enc set. When such an extension is
|
|
||||||
// accessed using GetExtension (or GetExtensions) desc and value
|
|
||||||
// will be set.
|
|
||||||
desc *ExtensionDesc
|
|
||||||
value interface{}
|
|
||||||
enc []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetRawExtension is for testing only.
|
|
||||||
func SetRawExtension(base Message, id int32, b []byte) {
|
|
||||||
epb, err := extendable(base)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
extmap := epb.extensionsWrite()
|
|
||||||
extmap[id] = Extension{enc: b}
|
|
||||||
}
|
|
||||||
|
|
||||||
// isExtensionField returns true iff the given field number is in an extension range.
|
|
||||||
func isExtensionField(pb extendableProto, field int32) bool {
|
|
||||||
for _, er := range pb.ExtensionRangeArray() {
|
|
||||||
if er.Start <= field && field <= er.End {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// checkExtensionTypes checks that the given extension is valid for pb.
|
|
||||||
func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
|
|
||||||
var pbi interface{} = pb
|
|
||||||
// Check the extended type.
|
|
||||||
if ea, ok := pbi.(extensionAdapter); ok {
|
|
||||||
pbi = ea.extendableProtoV1
|
|
||||||
}
|
|
||||||
if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
|
|
||||||
return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a)
|
|
||||||
}
|
|
||||||
// Check the range.
|
|
||||||
if !isExtensionField(pb, extension.Field) {
|
|
||||||
return errors.New("proto: bad extension number; not in declared ranges")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// extPropKey is sufficient to uniquely identify an extension.
|
|
||||||
type extPropKey struct {
|
|
||||||
base reflect.Type
|
|
||||||
field int32
|
|
||||||
}
|
|
||||||
|
|
||||||
var extProp = struct {
|
|
||||||
sync.RWMutex
|
|
||||||
m map[extPropKey]*Properties
|
|
||||||
}{
|
|
||||||
m: make(map[extPropKey]*Properties),
|
|
||||||
}
|
|
||||||
|
|
||||||
func extensionProperties(ed *ExtensionDesc) *Properties {
|
|
||||||
key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
|
|
||||||
|
|
||||||
extProp.RLock()
|
|
||||||
if prop, ok := extProp.m[key]; ok {
|
|
||||||
extProp.RUnlock()
|
|
||||||
return prop
|
|
||||||
}
|
|
||||||
extProp.RUnlock()
|
|
||||||
|
|
||||||
extProp.Lock()
|
|
||||||
defer extProp.Unlock()
|
|
||||||
// Check again.
|
|
||||||
if prop, ok := extProp.m[key]; ok {
|
|
||||||
return prop
|
|
||||||
}
|
|
||||||
|
|
||||||
prop := new(Properties)
|
|
||||||
prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
|
|
||||||
extProp.m[key] = prop
|
|
||||||
return prop
|
|
||||||
}
|
|
||||||
|
|
||||||
// HasExtension returns whether the given extension is present in pb.
|
|
||||||
func HasExtension(pb Message, extension *ExtensionDesc) bool {
|
|
||||||
// TODO: Check types, field numbers, etc.?
|
|
||||||
epb, err := extendable(pb)
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
extmap, mu := epb.extensionsRead()
|
|
||||||
if extmap == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
mu.Lock()
|
|
||||||
_, ok := extmap[extension.Field]
|
|
||||||
mu.Unlock()
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearExtension removes the given extension from pb.
|
|
||||||
func ClearExtension(pb Message, extension *ExtensionDesc) {
|
|
||||||
epb, err := extendable(pb)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// TODO: Check types, field numbers, etc.?
|
|
||||||
extmap := epb.extensionsWrite()
|
|
||||||
delete(extmap, extension.Field)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetExtension retrieves a proto2 extended field from pb.
|
|
||||||
//
|
|
||||||
// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil),
|
|
||||||
// then GetExtension parses the encoded field and returns a Go value of the specified type.
|
|
||||||
// If the field is not present, then the default value is returned (if one is specified),
|
|
||||||
// otherwise ErrMissingExtension is reported.
|
|
||||||
//
|
|
||||||
// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil),
|
|
||||||
// then GetExtension returns the raw encoded bytes of the field extension.
|
|
||||||
func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
|
|
||||||
epb, err := extendable(pb)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if extension.ExtendedType != nil {
|
|
||||||
// can only check type if this is a complete descriptor
|
|
||||||
if err := checkExtensionTypes(epb, extension); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
emap, mu := epb.extensionsRead()
|
|
||||||
if emap == nil {
|
|
||||||
return defaultExtensionValue(extension)
|
|
||||||
}
|
|
||||||
mu.Lock()
|
|
||||||
defer mu.Unlock()
|
|
||||||
e, ok := emap[extension.Field]
|
|
||||||
if !ok {
|
|
||||||
// defaultExtensionValue returns the default value or
|
|
||||||
// ErrMissingExtension if there is no default.
|
|
||||||
return defaultExtensionValue(extension)
|
|
||||||
}
|
|
||||||
|
|
||||||
if e.value != nil {
|
|
||||||
// Already decoded. Check the descriptor, though.
|
|
||||||
if e.desc != extension {
|
|
||||||
// This shouldn't happen. If it does, it means that
|
|
||||||
// GetExtension was called twice with two different
|
|
||||||
// descriptors with the same field number.
|
|
||||||
return nil, errors.New("proto: descriptor conflict")
|
|
||||||
}
|
|
||||||
return e.value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if extension.ExtensionType == nil {
|
|
||||||
// incomplete descriptor
|
|
||||||
return e.enc, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
v, err := decodeExtension(e.enc, extension)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remember the decoded version and drop the encoded version.
|
|
||||||
// That way it is safe to mutate what we return.
|
|
||||||
e.value = v
|
|
||||||
e.desc = extension
|
|
||||||
e.enc = nil
|
|
||||||
emap[extension.Field] = e
|
|
||||||
return e.value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// defaultExtensionValue returns the default value for extension.
|
|
||||||
// If no default for an extension is defined ErrMissingExtension is returned.
|
|
||||||
func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
|
|
||||||
if extension.ExtensionType == nil {
|
|
||||||
// incomplete descriptor, so no default
|
|
||||||
return nil, ErrMissingExtension
|
|
||||||
}
|
|
||||||
|
|
||||||
t := reflect.TypeOf(extension.ExtensionType)
|
|
||||||
props := extensionProperties(extension)
|
|
||||||
|
|
||||||
sf, _, err := fieldDefault(t, props)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if sf == nil || sf.value == nil {
|
|
||||||
// There is no default value.
|
|
||||||
return nil, ErrMissingExtension
|
|
||||||
}
|
|
||||||
|
|
||||||
if t.Kind() != reflect.Ptr {
|
|
||||||
// We do not need to return a Ptr, we can directly return sf.value.
|
|
||||||
return sf.value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// We need to return an interface{} that is a pointer to sf.value.
|
|
||||||
value := reflect.New(t).Elem()
|
|
||||||
value.Set(reflect.New(value.Type().Elem()))
|
|
||||||
if sf.kind == reflect.Int32 {
|
|
||||||
// We may have an int32 or an enum, but the underlying data is int32.
|
|
||||||
// Since we can't set an int32 into a non int32 reflect.value directly
|
|
||||||
// set it as a int32.
|
|
||||||
value.Elem().SetInt(int64(sf.value.(int32)))
|
|
||||||
} else {
|
|
||||||
value.Elem().Set(reflect.ValueOf(sf.value))
|
|
||||||
}
|
|
||||||
return value.Interface(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// decodeExtension decodes an extension encoded in b.
|
|
||||||
func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
|
|
||||||
t := reflect.TypeOf(extension.ExtensionType)
|
|
||||||
unmarshal := typeUnmarshaler(t, extension.Tag)
|
|
||||||
|
|
||||||
// t is a pointer to a struct, pointer to basic type or a slice.
|
|
||||||
// Allocate space to store the pointer/slice.
|
|
||||||
value := reflect.New(t).Elem()
|
|
||||||
|
|
||||||
var err error
|
|
||||||
for {
|
|
||||||
x, n := decodeVarint(b)
|
|
||||||
if n == 0 {
|
|
||||||
return nil, io.ErrUnexpectedEOF
|
|
||||||
}
|
|
||||||
b = b[n:]
|
|
||||||
wire := int(x) & 7
|
|
||||||
|
|
||||||
b, err = unmarshal(b, valToPointer(value.Addr()), wire)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(b) == 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return value.Interface(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
|
|
||||||
// The returned slice has the same length as es; missing extensions will appear as nil elements.
|
|
||||||
func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
|
|
||||||
epb, err := extendable(pb)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
extensions = make([]interface{}, len(es))
|
|
||||||
for i, e := range es {
|
|
||||||
extensions[i], err = GetExtension(epb, e)
|
|
||||||
if err == ErrMissingExtension {
|
|
||||||
err = nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
|
|
||||||
// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
|
|
||||||
// just the Field field, which defines the extension's field number.
|
|
||||||
func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
|
|
||||||
epb, err := extendable(pb)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
registeredExtensions := RegisteredExtensions(pb)
|
|
||||||
|
|
||||||
emap, mu := epb.extensionsRead()
|
|
||||||
if emap == nil {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
mu.Lock()
|
|
||||||
defer mu.Unlock()
|
|
||||||
extensions := make([]*ExtensionDesc, 0, len(emap))
|
|
||||||
for extid, e := range emap {
|
|
||||||
desc := e.desc
|
|
||||||
if desc == nil {
|
|
||||||
desc = registeredExtensions[extid]
|
|
||||||
if desc == nil {
|
|
||||||
desc = &ExtensionDesc{Field: extid}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extensions = append(extensions, desc)
|
|
||||||
}
|
|
||||||
return extensions, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetExtension sets the specified extension of pb to the specified value.
|
|
||||||
func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
|
|
||||||
epb, err := extendable(pb)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := checkExtensionTypes(epb, extension); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
typ := reflect.TypeOf(extension.ExtensionType)
|
|
||||||
if typ != reflect.TypeOf(value) {
|
|
||||||
return errors.New("proto: bad extension value type")
|
|
||||||
}
|
|
||||||
// nil extension values need to be caught early, because the
|
|
||||||
// encoder can't distinguish an ErrNil due to a nil extension
|
|
||||||
// from an ErrNil due to a missing field. Extensions are
|
|
||||||
// always optional, so the encoder would just swallow the error
|
|
||||||
// and drop all the extensions from the encoded message.
|
|
||||||
if reflect.ValueOf(value).IsNil() {
|
|
||||||
return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
|
|
||||||
}
|
|
||||||
|
|
||||||
extmap := epb.extensionsWrite()
|
|
||||||
extmap[extension.Field] = Extension{desc: extension, value: value}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearAllExtensions clears all extensions from pb.
|
|
||||||
func ClearAllExtensions(pb Message) {
|
|
||||||
epb, err := extendable(pb)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
m := epb.extensionsWrite()
|
|
||||||
for k := range m {
|
|
||||||
delete(m, k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A global registry of extensions.
|
|
||||||
// The generated code will register the generated descriptors by calling RegisterExtension.
|
|
||||||
|
|
||||||
var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
|
|
||||||
|
|
||||||
// RegisterExtension is called from the generated code.
|
|
||||||
func RegisterExtension(desc *ExtensionDesc) {
|
|
||||||
st := reflect.TypeOf(desc.ExtendedType).Elem()
|
|
||||||
m := extensionMaps[st]
|
|
||||||
if m == nil {
|
|
||||||
m = make(map[int32]*ExtensionDesc)
|
|
||||||
extensionMaps[st] = m
|
|
||||||
}
|
|
||||||
if _, ok := m[desc.Field]; ok {
|
|
||||||
panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
|
|
||||||
}
|
|
||||||
m[desc.Field] = desc
|
|
||||||
}
|
|
||||||
|
|
||||||
// RegisteredExtensions returns a map of the registered extensions of a
|
|
||||||
// protocol buffer struct, indexed by the extension number.
|
|
||||||
// The argument pb should be a nil pointer to the struct type.
|
|
||||||
func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
|
|
||||||
return extensionMaps[reflect.TypeOf(pb).Elem()]
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user