Skip to content
Open
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
45 changes: 44 additions & 1 deletion hems-core/src/api/ha/entity.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use std::env;

use actix_web::web::Json;
use serde::Serialize;
use serde::Deserialize;
use serde_json::Value;

use super::{init, init_load_map, ApiError, EntityState, BASE_URL, CLIENT, LOAD_MAP};

#[allow(dead_code)]
#[derive(Serialize, Deserialize, Debug)]
pub struct EntityServiceRequest {
pub entity_id: String,
}

pub async fn get_entity_consumption(entity_id: &str) -> Result<EntityState, ApiError> {
let client = CLIENT.get_or_init(init);
let url = format!("{}/api/states/{}", *BASE_URL, entity_id);
Expand Down Expand Up @@ -93,3 +100,39 @@ pub async fn get_entity_state(entity_id: &str) -> Result<Value, ApiError> {

Ok(response_body)
}

pub async fn toggle_entity_state(entity_id: &str, entity_state: bool) -> Result<Value, ApiError> {
let client = CLIENT.get_or_init(init);
let url = format!("{}/api/services/{}/{}",
*BASE_URL,
entity_id.split(".").next().unwrap_or_default(),
if entity_state { "turn_on" } else { "turn_off" }
);
let ha_token = env::var("HA_TOKEN").expect("HA_TOKEN must be set");

let request = EntityServiceRequest {
entity_id: entity_id.to_string(),
};

let response = client
.post(url)
.json(&request)
.bearer_auth(ha_token)
.send()
.await?;

if !response.status().is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(ApiError::HomeAssistantError(format!(
"Failed to set entity state: {}",
error_text
)));
}

let response_body = response.json().await?;

Ok(response_body)
}
26 changes: 26 additions & 0 deletions hems-core/src/resources/devices/ha_entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ pub fn configure(cfg: &mut utoipa_actix_web::service_config::ServiceConfig) {
cfg.service(
scope::scope("/entity")
.service(get_entity_consumption)
.service(get_entity_state)
.service(set_entity_state)
.service(toggle)
.service(add_entity),
);
}
Expand Down Expand Up @@ -109,3 +112,26 @@ async fn add_entity(request: web::Json<EntityRequest>) -> impl Responder {
Err(e) => HttpResponse::InternalServerError().body(format!("Failed to add entity, :{}", e)),
}
}

#[utoipa::path(
get,
tag = "Entity",
description = "Set entity state",
responses(
(status = 200, description = "Entity state set successfully"),
(status = 500, description = "Failed to set entity state"),
),
params(
("house_id" = u32, description = "House ID"),
("entity_name" = String, description = "Name of the entity"),
("state" = bool, description = "State to toggle to"),
),
)]
#[get("/{entity_name}/toggle/{state}")]
async fn toggle(id: web::Path<(u32, String, bool)>) -> impl Responder {
let (_house_id, entity_name, state) = id.into_inner();
match entity::toggle_entity_state(&entity_name, state).await {
Ok(entity_states) => HttpResponse::Ok().json(entity_states),
Err(e) => HttpResponse::InternalServerError().body(format!("Failed to toggle device state: {}", e)),
}
}
3 changes: 3 additions & 0 deletions hems_application/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[*]
indent_style = space
indent_size = 2
56 changes: 56 additions & 0 deletions hems_application/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/

# IntelliJ related
*.iml
*.ipr
*.iws
.idea/

# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/

# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
lib/l10n/app_localizations.dart
lib/l10n/app_localizations_*.dart

# Symbolication related
app.*.symbols

# Obfuscation related
app.*.map.json

# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release

# Auto Generated Files
/windows/flutter/generated*
/linux/flutter/generated*
/macos/Flutter/Generated*

# Editor specific folders
/.vscode
android/build/reports/problems/problems-report.html
89 changes: 89 additions & 0 deletions hems_application/.gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Copyright (c) 2011-present GitLab Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

spec:
inputs:
hems-url:
default: http://localhost:8080
description: The URL for the HEMS backend

---

image: "ghcr.io/cirruslabs/flutter:3.32.1"

variables:
DOCUMENTATION_URL: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/documentation/${CI_COMMIT_TAG}/documentation-${CI_COMMIT_TAG}.zip
APK_URL: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/android-apk/${CI_COMMIT_TAG}/hems_application-${CI_COMMIT_TAG}.apk

test:
stage: test
before_script:
- flutter pub get
- flutter gen-l10n
- flutter pub global activate junitreport
- export PATH="$HOME/.pub-cache/bin:$PATH"
script:
- flutter test --machine --coverage | tojunit -o report.xml
- lcov --summary coverage/lcov.info
- genhtml coverage/lcov.info --output=coverage
coverage: '/lines\.*: \d+\.\d+\%/'
artifacts:
name: coverage
paths:
- $CI_PROJECT_DIR/coverage
reports:
junit: report.xml

build:
stage: build
rules:
- if: $CI_COMMIT_TAG
before_script:
- flutter pub get
- flutter gen-l10n
script:
- flutter build apk --dart-define=HEMS_URL=$[[ inputs.hems-url ]]
- dart doc .
- zip -r documentation.zip doc
- |
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
--upload-file build/app/outputs/apk/release/app-release.apk \
$APK_URL
- |
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
--upload-file documentation.zip \
$DOCUMENTATION_URL

release:
stage: deploy
image: registry.gitlab.com/gitlab-org/release-cli:v0.24.0
rules:
- if: $CI_COMMIT_TAG
script:
- echo "running release"
release:
tag_name: '$CI_COMMIT_TAG'
description: 'Release $CI_COMMIT_TAG, with "$[[ inputs.hems-url ]]" as the HEMS server URL.'
assets:
links:
- name: 'HEMS application apk'
url: $APK_URL
- name: 'Documentation'
url: $DOCUMENTATION_URL
45 changes: 45 additions & 0 deletions hems_application/.metadata
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.

version:
revision: "archlinuxaur0000000000000000000000000000"
channel: ""

project_type: app

# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: archlinuxaur0000000000000000000000000000
base_revision: archlinuxaur0000000000000000000000000000
- platform: android
create_revision: archlinuxaur0000000000000000000000000000
base_revision: archlinuxaur0000000000000000000000000000
- platform: ios
create_revision: archlinuxaur0000000000000000000000000000
base_revision: archlinuxaur0000000000000000000000000000
- platform: linux
create_revision: archlinuxaur0000000000000000000000000000
base_revision: archlinuxaur0000000000000000000000000000
- platform: macos
create_revision: archlinuxaur0000000000000000000000000000
base_revision: archlinuxaur0000000000000000000000000000
- platform: web
create_revision: archlinuxaur0000000000000000000000000000
base_revision: archlinuxaur0000000000000000000000000000
- platform: windows
create_revision: archlinuxaur0000000000000000000000000000
base_revision: archlinuxaur0000000000000000000000000000

# User provided section

# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
7 changes: 7 additions & 0 deletions hems_application/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2025 Zev Comvalius, Daniel Dumitru, İlker Kılıç, Ipshit Raychaudhuri, Mert Yılmaz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Loading