Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create docker-publish.yml #1

Merged
merged 5 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/cargo_fmt.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
on: [push]

name: Cargo

jobs:
check:
name: Rust project
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install latest stable
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
components: rustfmt

- name: Run cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: --check
96 changes: 96 additions & 0 deletions .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
name: Docker

# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

on:
push:
branches: [ "main" ]
# Publish semver tags as releases.
tags: [ 'v*.*.*' ]
pull_request:
branches: [ "main" ]

env:
# Use docker.io for Docker Hub if empty
REGISTRY: ghcr.io
# github.repository as <account>/<repo>
IMAGE_NAME: ${{ github.repository }}


jobs:
build:

runs-on: ubuntu-latest
permissions:
contents: read
packages: write
# This is used to complete the identity challenge
# with sigstore/fulcio when running outside of PRs.
id-token: write

steps:
- name: Checkout repository
uses: actions/checkout@v3

# Install the cosign tool except on PR
# https://github.com/sigstore/cosign-installer
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@6e04d228eb30da1757ee4e1dd75a0ec73a653e06 #v3.1.1
with:
cosign-release: 'v2.1.1'

# Set up BuildKit Docker container builder to be able to build
# multi-platform images and export cache
# https://github.com/docker/setup-buildx-action
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0

# Login against a Docker registry except on PR
# https://github.com/docker/login-action
- name: Log into registry ${{ env.REGISTRY }}
if: github.event_name != 'pull_request'
uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

# Extract metadata (tags, labels) for Docker
# https://github.com/docker/metadata-action
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

# Build and push Docker image with Buildx (don't push on PR)
# https://github.com/docker/build-push-action
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

# Sign the resulting Docker image digest except on PRs.
# This will only write to the public Rekor transparency log when the Docker
# repository is public to avoid leaking data. If you would like to publish
# transparency data even for private images, pass --force to cosign below.
# https://github.com/sigstore/cosign
- name: Sign the published Docker image
if: ${{ github.event_name != 'pull_request' }}
env:
# https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
TAGS: ${{ steps.meta.outputs.tags }}
DIGEST: ${{ steps.build-and-push.outputs.digest }}
# This step uses the identity token to provision an ephemeral certificate
# against the sigstore community Fulcio instance.
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "shellyplug-exporter-rs"
version = "0.1.1"
version = "0.1.2"
edition = "2021"

[profile.release]
Expand Down
134 changes: 103 additions & 31 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use std::env;
use std::time::{Duration, SystemTime};

use prometheus_exporter::{
self,
prometheus::register_gauge,
prometheus::register_gauge_vec,
};
use prometheus_exporter::{self, prometheus::register_gauge, prometheus::register_gauge_vec};
use reqwest::Client;
use serde::Deserialize;
use serde_json::from_str;
Expand Down Expand Up @@ -54,7 +50,6 @@ struct ShellyplugResponse {
sys: Sys,
}


async fn get_data(client: &Client, url: &String) -> Result<ShellyplugResponse, reqwest::Error> {
let response = client.get(url).send().await?;
let json = response.json::<ShellyplugResponse>().await?;
Expand All @@ -63,53 +58,130 @@ async fn get_data(client: &Client, url: &String) -> Result<ShellyplugResponse, r

#[tokio::main]
async fn main() {
let port = env::var("PORT").or::<String>(Ok("9185".to_string())).unwrap();
let period = Duration::from_secs(from_str::<u64>(&env::var("PERIOD").or::<String>(Ok("60".to_string())).unwrap()).unwrap());
let port = env::var("PORT")
.or::<String>(Ok("9185".to_string()))
.unwrap();
let period = Duration::from_secs(
from_str::<u64>(
&env::var("PERIOD")
.or::<String>(Ok("60".to_string()))
.unwrap(),
)
.unwrap(),
);
let binding = format!("0.0.0.0:{}", port).parse().unwrap();
println!("Listening on {}", binding);
println!("Updating every {:?}", period);
let exporter = prometheus_exporter::start(binding).unwrap();

let client = Client::new();
let url = format!("{}/rpc/Shelly.GetStatus", env::var("SHELLYPLUG_URL").expect("SHELLYPLUG_URL not set"));
let url = format!(
"{}/rpc/Shelly.GetStatus",
env::var("SHELLYPLUG_URL").expect("SHELLYPLUG_URL not set")
);

let a_power = register_gauge_vec!("shellyplug_apower", "Instantaneous power in W", &["mac"]).unwrap();
let voltage_shelly = register_gauge_vec!("shellyplug_voltage", "Voltage in V", &["mac"]).unwrap();
let current_shelly = register_gauge_vec!("shellyplug_current", "Current in A", &["mac"]).unwrap();
let a_energy_total_shelly = register_gauge_vec!("shellyplug_aenergy_total", "Total energy so far in Wh", &["mac"]).unwrap();
let temperature_shelly = register_gauge_vec!("shellyplug_temperature", "Temperature of Shellyplug in °C", &["mac"]).unwrap();
let output_shelly = register_gauge_vec!("shellyplug_output", "true if output channel is currently on, false otherwise", &["mac"]).unwrap();
let available_updates_shelly = register_gauge_vec!("shellyplug_available_updates_info", "Information about available updates", &["mac", "version"]).unwrap();
let last_updated_shelly = register_gauge_vec!("shellyplug_last_updated", "Last update of Shellyplug", &["mac"]).unwrap();
let process_start_time = register_gauge!("process_start_time_seconds", "Start time of the process").unwrap();
let a_power =
register_gauge_vec!("shellyplug_apower", "Instantaneous power in W", &["mac"]).unwrap();
let voltage_shelly =
register_gauge_vec!("shellyplug_voltage", "Voltage in V", &["mac"]).unwrap();
let current_shelly =
register_gauge_vec!("shellyplug_current", "Current in A", &["mac"]).unwrap();
let a_energy_total_shelly = register_gauge_vec!(
"shellyplug_aenergy_total",
"Total energy so far in Wh",
&["mac"]
)
.unwrap();
let temperature_shelly = register_gauge_vec!(
"shellyplug_temperature",
"Temperature of Shellyplug in °C",
&["mac"]
)
.unwrap();
let output_shelly = register_gauge_vec!(
"shellyplug_output",
"true if output channel is currently on, false otherwise",
&["mac"]
)
.unwrap();
let available_updates_shelly = register_gauge_vec!(
"shellyplug_available_updates_info",
"Information about available updates",
&["mac", "version"]
)
.unwrap();
let last_updated_shelly = register_gauge_vec!(
"shellyplug_last_updated",
"Last update of Shellyplug",
&["mac"]
)
.unwrap();
let process_start_time =
register_gauge!("process_start_time_seconds", "Start time of the process").unwrap();

let mut now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
let mut now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
process_start_time.set(now as f64);

loop {
match get_data(&client, &url).await {
Ok(data) => {
// println!("{:?}", data);
now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
let mac = data.sys.mac;
a_power.get_metric_with_label_values(&[&mac]).unwrap().set(data.switch0.apower);
voltage_shelly.get_metric_with_label_values(&[&mac]).unwrap().set(data.switch0.voltage);
current_shelly.get_metric_with_label_values(&[&mac]).unwrap().set(data.switch0.current);
a_energy_total_shelly.get_metric_with_label_values(&[&mac]).unwrap().set(data.switch0.aenergy.total);
temperature_shelly.get_metric_with_label_values(&[&mac]).unwrap().set(data.switch0.temperature.t_c);
a_power
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(data.switch0.apower);
voltage_shelly
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(data.switch0.voltage);
current_shelly
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(data.switch0.current);
a_energy_total_shelly
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(data.switch0.aenergy.total);
temperature_shelly
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(data.switch0.temperature.t_c);
if data.switch0.output {
output_shelly.get_metric_with_label_values(&[&mac]).unwrap().set(1.);
output_shelly
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(1.);
} else {
output_shelly.get_metric_with_label_values(&[&mac]).unwrap().set(0.);
output_shelly
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(0.);
}
available_updates_shelly.reset();
match data.sys.available_updates.stable {
Some(v) => available_updates_shelly.get_metric_with_label_values(&[&mac, &v.version]).unwrap().set(1.),
None => available_updates_shelly.get_metric_with_label_values(&[&mac, "current"]).unwrap().set(1.)
Some(v) => available_updates_shelly
.get_metric_with_label_values(&[&mac, &v.version])
.unwrap()
.set(1.),
None => available_updates_shelly
.get_metric_with_label_values(&[&mac, "current"])
.unwrap()
.set(1.),
}
last_updated_shelly.get_metric_with_label_values(&[&mac]).unwrap().set(now as f64);
last_updated_shelly
.get_metric_with_label_values(&[&mac])
.unwrap()
.set(now as f64);
}
Err(err) => eprintln!("{}", err)
Err(err) => eprintln!("{}", err),
}
let _guard = exporter.wait_duration(period);
}
Expand Down
Loading