diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 000000000..3206d8a70 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,36 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Java CI with Maven and Deploy + +on: + push: + branches: [ master ] + +permissions: + contents: write + packages: write + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: '11' + architecture: x64 + - name: Setup git profile + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + - name: Publish Snapshot to GitHub Packages + run: mvn deploy -B + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Publish site + run: mvn -B site-deploy -Dusername=github-actions -Dpassword=${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 000000000..6f597043c --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,24 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Java CI with Maven + +on: + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: '11' + architecture: x64 + - name: Build with Maven + run: mvn -B package --file pom.xml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..29bfe0e59 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,38 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Stage Release on Master Branch + +on: + workflow_dispatch: + inputs: + releaseVersion: + description: Version to release + required: true + +permissions: + contents: write + packages: write + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: git-actions/set-user@v1 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: '11' + architecture: x64 + - name: Setup git profile + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + - name: Maven release + run: mvn release:prepare release:perform -B -DreleaseVersion=${{ github.event.inputs.releaseVersion }} -Dgoals=deploy + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index f14d2e2b9..000000000 --- a/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: java -jdk: openjdk8 -after_success: -- openssl aes-256-cbc -pass pass:$ENCRYPTION_PASSWORD -in deploy/pubring.gpg.enc -out - deploy/pubring.gpg -d -- openssl aes-256-cbc -pass pass:$ENCRYPTION_PASSWORD -in deploy/secring.gpg.enc -out - deploy/secring.gpg -d -- deploy/publish.sh -env: - global: - - secure: f/Ka8GVA6NnyUktn+TtBhdjVuM1wQI24ANxKsinfm4ldjfC6jueONgt3bog40fQ+ud5gVtJBAhven/qRicx9hT8bnrNUBSbeSD74KfuaZ6ICUmFyG64mNgbfkbc/pRzSbUf5WVAHPtgCo/p5P2Kt5/4l6/+DKmxLEPQ6K8bMz3nQCv0VtsbuGWh+QRxewA3AYLXF/O3nmP5YbP/X081C+TLiQQoibaL9UUGGWmcdEdsupgNdivvPfoYSji+gw3Dj6dn/gFZC1Y3tdcciyA4WOcspCuhZ4OVHZrencHr7PvvCjwjTQQ9bOQZi3l2zcWMGtnZlwlREdzTjUDP6sc2sjDJYy4FL1I87LRAhkiCO+Bo/SznQxAlljtng5R7eqYplt7ByLDpA6GJZQbchn6O+3YqqC9bScgQlyGQiHpbNGAzY5RQRFmvOosYIFTJm6KxMNMO2jogwID72e/+iU/nn5VaUA1btTziTdshb4en2g6f2jLLKURFHKEcXKmZgEOUV1ajqTUh4e4I++drhM8Nq+7vSYpuXbmnVleNbqbq4fWmH6Y0JlMSTn9Hk/K2tq2zw+Jz1oFWeaE39JCkK5gf3IsyGoOSy+dXqI0f9LtG7bPV0dDQGaE3Dh8P1gsXIqTo1E8fD8C1CvZjFgTV4rHukRTk5nfiNxItyWqRIQiLfBqU= - - secure: wHq7ZQPVYVuHrxnQj5bE4KZscBWr9pYL6U1YO1n/P/obkUz4ni6wG9KgLSOk+v9zj69of/HNRtBuo794tup76QREwEYBdKZsBg7cf9Fe14M44WJjY0O9FXJnUbuRfRqTQ+WhbugwiYPVaNZkrBM3FNj/kt0VP/0CtFqB180vrzv9Gokh0ZUYEuqrA9DGV2OszCt27FUQKAGUxDvVdV7d+9D+2FugkeMRg4CLqpFFx5E0THvnQnoKGCLiMZKnv8DN5BGUedzXHFHZtldJNCve2XNYCVNp8xKlCslsR1bwNYsHNM1nuG4kPjWYQfGAIBzbratTpMUcUTIC4l3liG9PkRvg5MBxi2HEoB+FlH4r3X1Pzj5QBDvNP6/+hZjgJQhhKHEdgau1qcC/fVT6Rf/Hmc3EwPSYOKRobzxXJcSG2TDxijAQD4QO41ekMqQJ+FXHIMR7xL+hK//xZSPJJxvjaKgC081/L1GP5mNvXuuo5FjG+1dr4yCpRtpqAShvmcybGK9VHaRdh+MRG+Ec81PdXm2lqGAjHWkfZnDo79WeyEVkqcjTnv1+lgBrRC5SL1WLy3fErLGMJG1HjM41G2O8B6wVIm0nMM8ejoTocHNw3k1l1rSicM7s8wamk8hlU4QhF6wpfgY1LKs0hSkfqlaIdGLHldCsyKakTQSPSgq/TA0= - - secure: hknjOefKy9U3A9PLrrf+s3uUaD9Is2XnkKr4X4o5mT79iWBjHbNbGllK+o/lrh8oV+SNKs5l+mp+FVtB0JBJK1bPGb7r7nR8zJcCUNrfJlOYePAmRhlc6fyGcclPQ81LLrBvbgn1PXFOfcttjWjZH8uIVMc4uEgobYQeS1l6jPPL2w471PtBgajeF1MSpy1/pwnZEdAFVSAB8RMNnqR/s7KjwG+qhkFgLEr5nz3AhIj3JSXlBQRiUjDH+qlxIt8SOunQZVtt6nYAVDBGp89v6SYk6w2CrEri1aUu8/9I7OT/X9+jSD2ksVFvoWW1hXNHhf7FCWqhbQzO7fGOg90ZM/lmgOVbnA+dihtT60GfBfSET52bInqG1QjDnig+/kggVcupUjThVI7VFIl8SGJXfhQtlnwlCWG2OYq+JBXoy0xUpEdvUnbnJv/8i4uvFpGZ/cgqPazw3arrURL+Shd82l+aRFBhHAa+qTvWdmcxBF1TvkWIodfaEPa95PS4mmao709/2bo7rf+FwaTRFtikiW2Asw7xSNlWmRBl90cS+B62xFiie8H6OeeOFcSKTN07MfuYaCdWKfViHaBU/W7Dfp2Sc7isPEEuBiJYDHucH2dsw0qBk6DyWlnWMaxo297/9QGyopiQNocgG+efKd+x7/cENLKUEVUXKEiyD1aebXY= - - secure: r5CcVp0fSkOunI63uI0Y0LETKeWMGStDOJayKzHsSmUg5t0GlH/8Zd8YrItbppCW/WNOjZ2c3XHAnFf55N4hcOvaHIMLJQaPh4LrMEe1uhFXQFfF8RFte4Ek1KBD0l//MeZQZMqykyz+O/5q4dsAvOi6B617OW2bmpUaF8hs+x+/+6C7hWxYaOU/zHpRrb+LC4YpnHqwfVMgpUdKxo83uysMTPcJDjjBvn+MTiXQvxBBAz1k+3fLQxJSUur+pdc22D/i0VZFpkQ9UpQRosfu8hAjZo4NzTLt/PeKbLvIx4kPRBlJqsU89iRcBE8QKUi3Y/Kelif2e30SdDUhoDSHN66mRe2fx/QmsP29yM7myC3dtxRUedXYNw9nTyx+Gmj23nL/U4IzifNVizWZgoHNheAt0E7+Z0WVhGKTtrYyy/2ffn1DCa80A9jO5DS/nDHkqukaW0cwHFq2EbdKv1UQBacM0QFzgHTiH1qkOzAQ1dh5ekViAyUIQ8qR05M06yZzIEeCxY/p5x6fs/yzSoOI37t5t5V1qWW7QaJYDAGGQ/u+tNNieq9y2/w2umDPRHvcPS7jA6ElNlK/XIlwkJA8n9xOANRYVLI4AgaXm7dYBopK/bs88cMJ7l6rZt3TMJ78gafL1XA3E3qNoceuoSHYIdu5m3oBvKvqfgcrPt8QrKI= - - secure: cMqrDc1B+hsAQOguaJUWNDSb9Jdo51CiRBPXDP5dBhgf+oErOPED9obSmKiCPaDfaWjdZWENpBs5CPjm+drNF4xEPIoYKaLI4che16wxko+To6I7k+/aCDT+thzgi1qIoWTn7KTq0ZB73tRLDktyugND0fwetgKYMqBOn5laCazWQeLpdIq3r4zWG/dX30lOB4kdnsY2X4Yb+9OPZi9+ZEr8AAiI+FomEGCv22tKAUyA/SYqPA/XXg6XJ2hyDdkTfLrmuz+dJDasglIDj2Js4p/my0vsFtlvGIubdzfnbqCPmtFjECSfVmQz92947/Rb36zK5wrQH8UDsNWRqFmd/WDYbGX7Eg2hSrWpHGO8ury6yyZRvPL4R2XiOQ4/T1yTOosc57M/wG8+wLavKlULXiH+yDWwXJPTGbKbaXxfVxnu9t1VAoLx6f9dSUEd+NP5TdDVOyp0dyvjs/dAsTedCooMiuJw/Y2+bktmhr14I3XWs8+w1jFDLO6/GhH1QOoNf9wi3ywEKnYGfY5YXiFp8meBm7koZ5DvU21uxUG2OBrOYgYrt1KatmN9A0og7JR6QeHJ1yawT0wM3L14JbqOjktG2e3MNBCqNyP+hWDqD7RDRm1pITbTr5oz7gjXeAI1E00okQ3y2/SdbHEPOUu/tSc2YYsrPCfriRz1AHpedr0= diff --git a/CHANGES.md b/CHANGES.md index 143958172..ab4bb1202 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,90 @@ +# HAP-Java 2.0.10 +* Add constructors with custom min/max to the window covering tilt angle characteristics [#162](https://github.com/hap-java/HAP-Java/issues/162) +* Add optional Mute characteristic to Doorbell service +* Fix leak of mDNS instances and shutdown hooks when stopping `HomekitRoot` +* Updated netty to 4.1.139.Final + +# HAP-Java 2.0.9 +* Fix Set Duration and Remaining Duration characteristics to advertise format `uint32` instead of `int` [#202](https://github.com/hap-java/HAP-Java/issues/202) +* Stop logging the SRP shared secret, derived key and M5 message data during pairing at DEBUG level +* Fix splitting of encrypted frames when several frames of different length arrive in one read, or when a read ends after the first length byte + +# HAP-Java 2.0.8 +* Updated bouncy castle to 1.83 +* Updated netty to 4.1.126.Final + +# HAP-Java 2.0.7 +* Add overloads to characteristics so that the username can be passed through. + +# HAP-Java 2.0.6 +* Several methods allowing library users to manipulate characteristics themselves +* Allow library users to provider their own implementation of AccessoryInformationService +* Fix ProgrammableSwitchEventEnum that has an incorrect value + +# HAP-Java 2.0.5 +* Implement List-Pairings method. Compatibility with new Home infrastructure from iOS 16.2? + +# HAP-Java 2.0.3 +* Avoid unnecessary forced disconnects. Library users should be updating the configuration index anyway. + +# HAP-Java 2.0.2 + * Various minor stability issues for after an accessory has been removed. + +# HAP-Java 2.0.1 +## Fixes +* Log accessory names instead of futures. [#150](https://github.com/hap-java/HAP-Java/issues/150) +* Fix rotation speed data type (BREAKING API CHANGE). According to HAP specification it must be float +* Close JsonWriters [#149](https://github.com/hap-java/HAP-Java/issues/149) +* Fix UUID of HAP Version characteristic +* Add Mute characteristic to Doorbell service + +## New +* New characteristics: + * Identifier + * Input Device Type + * Input Source Type + * Configured Name + * Current Visibility State + * Target Visibility State + * Sleep Discovery Mode + * Active Identifier + * Closed Captions + * Current Media State + * Target Media State + * Picture Mode + * Power Mode + * Remote Key + * Volume Control Type + * Volume Selector + * AirPlay Enable + +* New services + * Input Source + * Television + * Television Speaker + * Smart Speaker + +# HAP-Java 2.0.0 +* major refactoring to support optional characteristics +* structure and names adapted to HAP spec structure and naming. +* structure is following + * `accessory` package include basis accessory as the listed in HAP spec, plus interfaces for optional characteristics. clients should extend the accessory classes. e.g. `WindowCoveringAccessory` or `AccessoryWithBrightness` + * `characteristics` package consists of all characteristics, optional and mandatory. e.g. `TargetHorizontalTiltAngleCharacteristic`. The naming is done in accordance to HAP spec. + * `services` package consists of services, which grouping characteristics. e.g. `WindowCoveringService` defines mandatory and optional characteristics for a window covering service as it is defined in HAP spec. + * `server` package consists classes to run HomeKit server and handle communication +* the process is following: client, e.g. openHAB bindings, extends accessory classes, e.g. `WindowCoveringAccessory` and implements all required methods. WindowCoveringAccessory is linked already to WindowCoveringService, that in turn is link to single characteristics. +* linked service support + +## New and improved + +* Valid values are supported for enum characteristics instead of min and max values +* Supported valid states for Thermostat, SecuritySystem, HeaterCooler and HumidifierDehumidifier [#108] [#120](https://github.com/hap-java/HAP-Java/pull/120) +* Support for FilterMaintenance. Can be used as a linked service for an Air Purifier [#124](https://github.com/hap-java/HAP-Java/pull/124) + +## Fixes + +* Fix for re-advertising service when using alternative jMDNS implementations. + # HAP-Java 1.1.5 ## Fixes @@ -11,6 +98,7 @@ * Fix various spec violations and optimize communications to improve performance [#65](https://github.com/hap-java/HAP-Java/pull/65) * Fix a pairing issue in which HAP-Java could listen on a different interface than that which it advertises [#67](https://github.com/hap-java/HAP-Java/pull/67) * Allow window covering to be used without optional characteristics. The inclusion of `HoldPositionCharacteristic` did terrible things, and we're still not sure why. Addressed [#56](https://github.com/hap-java/HAP-Java/pull/56) +* Air Purifier didn't support rotation speed characteristics. [#124](https://github.com/hap-java/HAP-Java/pull/124) ## New and improved diff --git a/README.md b/README.md index 2d3a5ba53..6d1f88458 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,83 @@ HAP-Java ========= -HAP-Java is a Java implementation of the Homekit Accessory Protocol. +[![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.hap-java/hap/badge.svg)](https://search.maven.org/search?q=g:io.github.hap-java%20a:hap) +[![MIT License](https://img.shields.io/github/license/hap-java/HAP-Java)](https://github.com/hap-java/HAP-Java/blob/master/LICENSE) +![Maven Build Status](https://github.com/andylintner/HAP-Java/actions/workflows/maven.yml/badge.svg) -Using this library, you can create your own Homekit Accessory or Homekit Accessory Bridge. +HAP-Java is a Java implementation of the HomeKit Accessory Protocol. -Because the MFi Specification is closed to individual developers, and this implementation was made without access to that specification, it may not be complete. iOS devices do recognize and are able to interact with accessories exposed via this library however. +Using this library, you can create your own HomeKit Accessory or HomeKit Accessory Bridge. This library would not have been possible without [Tian Zhang](https://github.com/KhaosT) who did a lot of the hard work of figuring out how the protocol works in his NodeJS implementation. Usage ========= Include HAP-Java in your project using maven: + ``` io.github.hap-java hap - 1.2.0-SNAPSHOT + 2.0.1-SNAPSHOT ``` -After that, read the [Javadoc](http://beowulfe.github.io/HAP-Java/apidocs/) and check out the [Sample](https://github.com/beowulfe/HAP-Java/tree/sample). \ No newline at end of file +After that, check out the [Sample](https://github.com/hap-java/HAP-Java/tree/sample) and +read the [Javadoc](https://hap-java.github.io/HAP-Java/apidocs/index.html) + +Supported HomeKit Accessories +========= + +Current implementation fully supports 42 HomeKit accessory/services. + +| HomeKit Accessory & Service type | Supported by Java-HAP | +|--------------------|--------------------| +| Accessory Information | :white_check_mark: | +| Air Purifier | :white_check_mark: | +| Air Quality Sensor | :white_check_mark: | +| Audio Stream Management | :x: | +| Battery Service | :white_check_mark: | +| Camera RTP Stream Management | :x: | +| Carbon Dioxide Sensor | :white_check_mark: | +| Carbon Monoxide Sensor | :white_check_mark: | +| Contact Sensor | :white_check_mark: | +| Data Stream Transport Management | :x: | +| Door | :white_check_mark: | +| Doorbell | :white_check_mark: | +| Fan | :white_check_mark: | +| Faucet | :white_check_mark: | +| Filter Maintenance | :white_check_mark: | +| Garage Door Opener | :white_check_mark: | +| HAP Protocol Information | :white_check_mark: | +| Heater Cooler | :white_check_mark: | +| Humidifier Dehumidifier | :white_check_mark: | +| Humidity Sensor | :white_check_mark: | +| Input Source | :white_check_mark: | +| Irrigation System | :white_check_mark: | +| Leak Sensor | :white_check_mark: | +| Light Bulb | :white_check_mark: | +| Light Sensor | :white_check_mark: | +| Lock Management | :x: | +| Lock Mechanism | :white_check_mark: | +| Microphone | :white_check_mark: | +| Motion Sensor | :white_check_mark: | +| Occupancy Sensor | :white_check_mark: | +| Outlet | :white_check_mark: | +| Security System | :white_check_mark: | +| Service Label | :white_check_mark: | +| Siri | :x: | +| Slat | :white_check_mark: | +| Smart Speaker | :white_check_mark: | +| Smoke Sensor | :white_check_mark: | +| Speaker | :white_check_mark: | +| Stateless Programmable Switch | :white_check_mark: | +| Switch | :white_check_mark: | +| Target Control | :x: | +| Target Control Management | :x: | +| Television | :white_check_mark: | +| Television Speaker | :white_check_mark: | +| Temperature Sensor | :white_check_mark: | +| Thermostat | :white_check_mark: | +| Valve | :white_check_mark: | +| Window | :white_check_mark: | +| Window Covering | :white_check_mark: | \ No newline at end of file diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 000000000..6dd790693 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,7 @@ +# How to release HAP-Java + +These actions can only be performed by someone with maintainer level access to the repository. + +1. Run the [Stage Release on Master Branch](https://github.com/hap-java/HAP-Java/actions/workflows/release.yml) Action with a version such as `2.0.2` +2. After this completes, find the release on the [Releases page](https://github.com/hap-java/HAP-Java/releases) +3. Edit the release to include the changelog details diff --git a/deploy/distribution.xml b/deploy/distribution.xml deleted file mode 100644 index a2cf6d668..000000000 --- a/deploy/distribution.xml +++ /dev/null @@ -1,18 +0,0 @@ - - dir-with-dependencies - - dir - - false - - - / - true - false - ${artifact.groupId}.${artifact.artifactId}-${artifact.version}${dashClassifier?}.jar - runtime - - - \ No newline at end of file diff --git a/deploy/publish.sh b/deploy/publish.sh deleted file mode 100755 index 1fb261646..000000000 --- a/deploy/publish.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -if [[ ( $TRAVIS_PULL_REQUEST == "false" && $TRAVIS_BRANCH == "master" ) ]]; then - mvn deploy --settings deploy/settings.xml -DperformRelease=true -DskipTests=true - exit $? -fi diff --git a/deploy/pubring.gpg.enc b/deploy/pubring.gpg.enc deleted file mode 100644 index 1361f5a9f..000000000 Binary files a/deploy/pubring.gpg.enc and /dev/null differ diff --git a/deploy/secring.gpg.enc b/deploy/secring.gpg.enc deleted file mode 100644 index 1f1c31049..000000000 Binary files a/deploy/secring.gpg.enc and /dev/null differ diff --git a/deploy/settings.xml b/deploy/settings.xml deleted file mode 100644 index f08c008c0..000000000 --- a/deploy/settings.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - ossrh - ${env.SONATYPE_USERNAME} - ${env.SONATYPE_PASSWORD} - - - diff --git a/pom.xml b/pom.xml index d5709647c..7bbbb9021 100644 --- a/pom.xml +++ b/pom.xml @@ -5,13 +5,14 @@ hap hap-java Homekit Accessory Protocol for Java - 1.2.0-snapshot + 2.0.10-SNAPSHOT jar https://github.com/hap-java/HAP-Java UTF-8 - + 4.1.139.Final + @@ -23,7 +24,7 @@ scm:git:https://github.com/hap-java/HAP-Java.git - scm:git:git@github.com:hap-java/HAP-Java.git + scm:git:https://github.com/hap-java/HAP-Java.git https://github.com/hap-java/HAP-Java.git HEAD @@ -56,8 +57,44 @@ io.netty - netty-all - 4.0.32.Final + netty-common + ${netty.version} + + + + io.netty + netty-buffer + ${netty.version} + + + + io.netty + netty-transport + ${netty.version} + + + + io.netty + netty-handler + ${netty.version} + + + + io.netty + netty-codec + ${netty.version} + + + + io.netty + netty-codec-http + ${netty.version} + + + + io.netty + netty-resolver + ${netty.version} @@ -68,10 +105,16 @@ org.bouncycastle - bcprov-jdk15on - 1.51 + bcpkix-jdk18on + 1.83 + + org.bouncycastle + bctls-jdk18on + 1.82 + + net.vrallev.ecc ecc-25519-java @@ -97,28 +140,29 @@ - javax.jmdns + org.jmdns jmdns - 3.4.1 - - - - commons-io - commons-io - 2.4 + 3.5.6 junit junit - 4.12 + 4.13.1 test org.mockito - mockito-all - 1.10.19 + mockito-core + 3.8.0 + test + + + + org.assertj + assertj-core + 3.27.7 test @@ -163,9 +207,10 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.0.1 + 3.2.0 - io.github.hapjava.impl + io.github.hapjava.server.impl + 8 @@ -176,28 +221,10 @@ - - maven-assembly-plugin - 3.1.0 - - - deploy/distribution.xml - - - - - make-assembly - package - - single - - - - org.apache.maven.plugins maven-scm-publish-plugin - 3.0.0 + 3.1.0 scm-publish @@ -206,7 +233,7 @@ publish-scm - scm:git:git@github.com:hap-java/HAP-Java.git + scm:git:https://github.com/hap-java/HAP-Java.git gh-pages @@ -251,12 +278,12 @@ https://hap-java.github.io/ - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ + github + https://maven.pkg.github.com/hap-java/HAP-Java - ossrh - https://oss.sonatype.org/content/repositories/snapshots + github + https://maven.pkg.github.com/hap-java/HAP-Java @@ -272,7 +299,9 @@ maven-javadoc-plugin 3.0.1 - io.github.hapjava.impl + io.github.hapjava.server.impl + 8 + false @@ -293,20 +322,6 @@ ossrh - - gpg - ${env.GPG_KEYNAME} - ${env.GPG_PASSPHRASE} - false - deploy/pubring.gpg - deploy/secring.gpg - - - - performRelease - true - - @@ -322,6 +337,13 @@ + + HAP-Java + + --pinentry-mode + loopback + + org.sonatype.plugins @@ -330,17 +352,12 @@ true ossrh - https://oss.sonatype.org/ + https://s01.oss.sonatype.org/ true - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - + diff --git a/src/main/java/io/github/hapjava/HomekitStandaloneAccessoryServer.java b/src/main/java/io/github/hapjava/HomekitStandaloneAccessoryServer.java deleted file mode 100644 index 6df6fb603..000000000 --- a/src/main/java/io/github/hapjava/HomekitStandaloneAccessoryServer.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.github.hapjava; - -import io.github.hapjava.impl.HomekitWebHandler; -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * A server for exposing standalone Homekit accessory (as opposed to a Bridge accessory which - * contains multiple accessories). Each standalone accessory will have its own pairing information, - * port, and pin. Instantiate this class via {@link - * HomekitServer#createStandaloneAccessory(HomekitAuthInfo, HomekitAccessory)}. - * - * @author Andy Lintner - */ -public class HomekitStandaloneAccessoryServer { - - private final HomekitRoot root; - - HomekitStandaloneAccessoryServer( - HomekitAccessory accessory, - HomekitWebHandler webHandler, - InetAddress localhost, - HomekitAuthInfo authInfo) - throws UnknownHostException, IOException { - root = new HomekitRoot(accessory.getLabel(), webHandler, localhost, authInfo); - root.addAccessory(accessory); - } - - /** Begins advertising and handling requests for this accessory. */ - public void start() { - root.start(); - } -} diff --git a/src/main/java/io/github/hapjava/accessories/AirPurifierAccessory.java b/src/main/java/io/github/hapjava/accessories/AirPurifierAccessory.java new file mode 100644 index 000000000..3766f75a1 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/AirPurifierAccessory.java @@ -0,0 +1,86 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airpurifier.CurrentAirPurifierStateEnum; +import io.github.hapjava.characteristics.impl.airpurifier.TargetAirPurifierStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.AirPurifierService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** An air purifier. */ +public interface AirPurifierAccessory extends HomekitAccessory { + /** + * Mandatory: Retrieves the current active state of the fan'. + * + * @return a future that will contain the binary state + */ + CompletableFuture isActive(); + + /** + * Sets the active state of the fan + * + * @param state the binary state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setActive(boolean state) throws Exception; + + /** + * Subscribes to changes in the active state of the fan. + * + * @param callback the function to call when the direction changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state of the fan. */ + void unsubscribeActive(); + + /** + * Retrieves the current state of the air purifier + * + * @return a future that will contain the state + */ + CompletableFuture getCurrentState(); + + /** + * Subscribes to changes in the state of the air purifier. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the state of the air purifier. */ + void unsubscribeCurrentState(); + + /** + * Retrieves the air purifier target state. + * + * @return a future that will contain the air purifier target state . + */ + CompletableFuture getTargetState(); + + /** + * set target state the air purifier target state. + * + * @param state air purifier target state + * @return a future that completes when the change is made + */ + CompletableFuture setTargetState(TargetAirPurifierStateEnum state); + + /** + * Subscribes to changes in the target state of the air purifier. + * + * @param callback the function to call when the target state changes. + */ + void subscribeTargetState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the target state of the air purifier. */ + void unsubscribeTargetState(); + + @Override + default Collection getServices() { + return Collections.singleton(new AirPurifierService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/AirQualityAccessory.java b/src/main/java/io/github/hapjava/accessories/AirQualityAccessory.java new file mode 100644 index 000000000..309fb486e --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/AirQualityAccessory.java @@ -0,0 +1,35 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airquality.AirQualityEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.AirQualityService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** An air quality accessory which can include several sensors. */ +public interface AirQualityAccessory extends HomekitAccessory { + + /** + * Retrieves the state of the air quality + * + * @return a future that will contain the state + */ + CompletableFuture getAirQuality(); + + /** + * Subscribes to changes in the air quality + * + * @param callback the function to call when the air quality changes. + */ + void subscribeAirQuality(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the air quality. */ + void unsubscribeAirQuality(); + + @Override + default Collection getServices() { + return Collections.singleton(new AirQualityService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/BasicFanAccessory.java b/src/main/java/io/github/hapjava/accessories/BasicFanAccessory.java new file mode 100644 index 000000000..98c4bf497 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/BasicFanAccessory.java @@ -0,0 +1,46 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.BasicFanService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** + * A fan with mandatory characteristics. + * + * @author Andy Lintner + */ +public interface BasicFanAccessory extends HomekitAccessory { + /** + * Mandatory: Retrieves the current power state of the fan. + * + * @return a future that will contain the binary state + */ + CompletableFuture isOn(); + + /** + * Sets the active state of the fan + * + * @param state the binary state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setOn(boolean state) throws Exception; + + /** + * Subscribes to changes in the active state of the fan. + * + * @param callback the function to call when the active state changes. + */ + void subscribeOn(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state of the fan. */ + void unsubscribeOn(); + + @Override + default Collection getServices() { + return Collections.singleton(new BasicFanService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/BatteryAccessory.java b/src/main/java/io/github/hapjava/accessories/BatteryAccessory.java index 88c424a32..d3724bc50 100644 --- a/src/main/java/io/github/hapjava/accessories/BatteryAccessory.java +++ b/src/main/java/io/github/hapjava/accessories/BatteryAccessory.java @@ -1,30 +1,74 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.battery.ChargingStateEnum; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.BatteryService; +import java.util.Collection; +import java.util.Collections; import java.util.concurrent.CompletableFuture; /** - * Do not use. Devices that have battery levels should implement LowBatteryStatusAccessory. + * Devices with battery . * * @author Gaston Dombiak */ -@Deprecated -public interface BatteryAccessory { +public interface BatteryAccessory extends HomekitAccessory { /** * Retrieves the battery level of the accessory. * * @return a future that will contain the accessory's battery state */ - CompletableFuture getBatteryLevelState(); + CompletableFuture getBatteryLevel(); + + /** + * Queries if the device battery level is low; returning a value of true will cause a low-battery + * status to appear in Home for the device. + * + * @return a future that will contain the accessory's low battery state + */ + CompletableFuture getLowBatteryState(); + + /** + * Retriece the battery charging state. + * + * @return a future that will contain the battery charging state + */ + CompletableFuture getChargingState(); /** * Subscribes to changes in the battery level. * * @param callback the function to call when battery level changes. */ - void subscribeBatteryLevelState(HomekitCharacteristicChangeCallback callback); + void subscribeBatteryLevel(HomekitCharacteristicChangeCallback callback); + /** + * Subscribes to changes in the battery level. + * + * @param callback the function to call when low battery state changes. + */ + void subscribeLowBatteryState(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the battery level. + * + * @param callback the function to call when low battery state changes. + */ + void subscribeBatteryChargingState(HomekitCharacteristicChangeCallback callback); /** Unsubscribes from changes in the battery level. */ - void unsubscribeBatteryLevelState(); + void unsubscribeBatteryLevel(); + + /** Unsubscribes from changes in the low battery state. */ + void unsubscribeLowBatteryState(); + + /** Unsubscribes from changes in the low battery state. */ + void unsubscribeBatteryChargingState(); + + @Override + default Collection getServices() { + return Collections.singleton(new BatteryService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/BatteryStatusAccessory.java b/src/main/java/io/github/hapjava/accessories/BatteryStatusAccessory.java deleted file mode 100644 index b8c6ba201..000000000 --- a/src/main/java/io/github/hapjava/accessories/BatteryStatusAccessory.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import java.util.concurrent.CompletableFuture; - -/** - * An accessory that runs on batteries. Accessories that run on batteries are able to report battery - * level. - * - * @author Tim Harper - */ -public interface BatteryStatusAccessory { - - /** - * Queries if the device battery level is low; returning a value of true will cause a low-battery - * status to appear in Home for the device. - * - * @return a future that will contain the accessory's low battery state - */ - CompletableFuture getLowBatteryState(); - - /** - * Subscribes to changes in the battery level. - * - * @param callback the function to call when low battery state changes. - */ - void subscribeLowBatteryState(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the low battery state. */ - void unsubscribeLowBatteryState(); -} diff --git a/src/main/java/io/github/hapjava/impl/accessories/Bridge.java b/src/main/java/io/github/hapjava/accessories/Bridge.java similarity index 52% rename from src/main/java/io/github/hapjava/impl/accessories/Bridge.java rename to src/main/java/io/github/hapjava/accessories/Bridge.java index 024693823..e53c427f2 100644 --- a/src/main/java/io/github/hapjava/impl/accessories/Bridge.java +++ b/src/main/java/io/github/hapjava/accessories/Bridge.java @@ -1,7 +1,6 @@ -package io.github.hapjava.impl.accessories; - -import io.github.hapjava.HomekitAccessory; +package io.github.hapjava.accessories; +/** HomeKit bridge service. */ public interface Bridge extends HomekitAccessory { @Override diff --git a/src/main/java/io/github/hapjava/accessories/CarbonDioxideSensorAccessory.java b/src/main/java/io/github/hapjava/accessories/CarbonDioxideSensorAccessory.java new file mode 100644 index 000000000..185aedd13 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/CarbonDioxideSensorAccessory.java @@ -0,0 +1,35 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.carbondioxidesensor.CarbonDioxideDetectedEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.CarbonDioxideSensorService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** A carbon dioxide sensor reports carbon dioxide level. */ +public interface CarbonDioxideSensorAccessory extends HomekitAccessory { + + /** + * Retrieves the state of the sensor that indicates if carbon dioxide has been detected. + * + * @return a future that will contain the carbon dioxide sensor's state + */ + CompletableFuture getCarbonDioxideDetectedState(); + + /** + * Subscribes to changes in the carbon dioxide's state. + * + * @param callback the function to call when the state changes. + */ + void subscribeCarbonDioxideDetectedState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the carbon dioxide's state. */ + void unsubscribeCarbonDioxideDetectedState(); + + @Override + default Collection getServices() { + return Collections.singleton(new CarbonDioxideSensorService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/CarbonMonoxideSensor.java b/src/main/java/io/github/hapjava/accessories/CarbonMonoxideSensorAccessory.java similarity index 62% rename from src/main/java/io/github/hapjava/accessories/CarbonMonoxideSensor.java rename to src/main/java/io/github/hapjava/accessories/CarbonMonoxideSensorAccessory.java index fd9ed9fef..93cfebbd6 100644 --- a/src/main/java/io/github/hapjava/accessories/CarbonMonoxideSensor.java +++ b/src/main/java/io/github/hapjava/accessories/CarbonMonoxideSensorAccessory.java @@ -1,10 +1,9 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.properties.CarbonMonoxideDetectedState; -import io.github.hapjava.impl.services.CarbonMonoxideSensorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.carbonmonoxidesensor.CarbonMonoxideDetectedEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.CarbonMonoxideSensorService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -12,24 +11,16 @@ /** * A carbon monoxide sensor reports whether carbon monoxide has been detected or not. * - *

Carbon monoxide sensors that run on batteries will need to implement this interface and also - * implement {@link BatteryStatusAccessory}. - * * @author Gaston Dombiak */ -public interface CarbonMonoxideSensor extends HomekitAccessory { +public interface CarbonMonoxideSensorAccessory extends HomekitAccessory { /** * Retrieves the state of the sensor that indicates if carbon monoxide has been detected. * * @return a future that will contain the carbon monoxide sensor's state */ - CompletableFuture getCarbonMonoxideDetectedState(); - - @Override - default Collection getServices() { - return Collections.singleton(new CarbonMonoxideSensorService(this)); - } + CompletableFuture getCarbonMonoxideDetectedState(); /** * Subscribes to changes in the carbon monoxide's state. @@ -40,4 +31,9 @@ default Collection getServices() { /** Unsubscribes from changes in the carbon monoxide's state. */ void unsubscribeCarbonMonoxideDetectedState(); + + @Override + default Collection getServices() { + return Collections.singleton(new CarbonMonoxideSensorService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/ContactSensor.java b/src/main/java/io/github/hapjava/accessories/ContactSensorAccessory.java similarity index 66% rename from src/main/java/io/github/hapjava/accessories/ContactSensor.java rename to src/main/java/io/github/hapjava/accessories/ContactSensorAccessory.java index af85760db..754f6981b 100644 --- a/src/main/java/io/github/hapjava/accessories/ContactSensor.java +++ b/src/main/java/io/github/hapjava/accessories/ContactSensorAccessory.java @@ -1,10 +1,9 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.properties.ContactState; -import io.github.hapjava.impl.services.ContactSensorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.contactsensor.ContactStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.ContactSensorService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -13,12 +12,9 @@ * A contact sensor that reports whether contact is detected or not. Typical contact sensors are * window/door sensors. When contact is detected it means that the door/window is closed. * - *

Contact sensors that run on batteries will need to implement this interface and also implement - * {@link BatteryStatusAccessory}. - * * @author Gaston Dombiak */ -public interface ContactSensor extends HomekitAccessory { +public interface ContactSensorAccessory extends HomekitAccessory { /** * Retrieves the state of the contact. This is whether the contact is detected or not. Detected @@ -26,12 +22,7 @@ public interface ContactSensor extends HomekitAccessory { * * @return a future that will contain the contact's state */ - CompletableFuture getCurrentState(); - - @Override - default Collection getServices() { - return Collections.singleton(new ContactSensorService(this)); - } + CompletableFuture getCurrentState(); /** * Subscribes to changes in the contact state. @@ -42,4 +33,9 @@ default Collection getServices() { /** Unsubscribes from changes in the contact state. */ void unsubscribeContactState(); + + @Override + default Collection getServices() { + return Collections.singleton(new ContactSensorService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/DoorAccessory.java b/src/main/java/io/github/hapjava/accessories/DoorAccessory.java new file mode 100644 index 000000000..1049c7686 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/DoorAccessory.java @@ -0,0 +1,78 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.windowcovering.PositionStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.DoorService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** A motorized door with current and target position. */ +public interface DoorAccessory extends HomekitAccessory { + + /** + * Retrieves the position state of the door + * + * @return a future which will contain the door's position state + */ + CompletableFuture getPositionState(); + + /** + * Retrieves the current position of the door + * + * @return a future which will contain the door's current position + */ + CompletableFuture getCurrentPosition(); + + /** + * Retrieves the target position of the door + * + * @return a future which will contain the door's target position + */ + CompletableFuture getTargetPosition(); + + /** + * Sets the targeted state of the door. + * + * @param position the targeted position + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setTargetPosition(Integer position) throws Exception; + + /** + * Subscribes to changes in the door's position state + * + * @param callback the function to call when the state changes + */ + void subscribePositionState(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the door's current position + * + * @param callback the function to call when the current position changes + */ + void subscribeCurrentPosition(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the door's target position + * + * @param callback the function to call when the target position changes + */ + void subscribeTargetPosition(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the door's state */ + void unsubscribePositionState(); + + /** Unsubscribes from changes in the door's current position */ + void unsubscribeCurrentPosition(); + + /** Unsubscribes from changes in the door's target position */ + void unsubscribeTargetPosition(); + + @Override + default Collection getServices() { + return Collections.singleton(new DoorService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/DoorbellAccessory.java b/src/main/java/io/github/hapjava/accessories/DoorbellAccessory.java new file mode 100644 index 000000000..d46d4a00e --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/DoorbellAccessory.java @@ -0,0 +1,36 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.ProgrammableSwitchEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.DoorbellService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** doorbell accessory with a switch (button push) event. */ +public interface DoorbellAccessory extends HomekitAccessory { + + /** + * Retrieves the last states of the doorbell. Bluetooth device should return the last event, the + * IP device should always return null + * + * @return state of the door bell event + */ + CompletableFuture getSwitchEvent(); + + /** + * Subscribes to changes in doorbell switch event, i.e. pressing on the door bell button. + * + * @param callback the function to call when the state changes. + */ + void subscribeSwitchEvent(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in doorbell switch event. */ + void unsubscribeSwitchEvent(); + + @Override + default Collection getServices() { + return Collections.singleton(new DoorbellService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/Fan.java b/src/main/java/io/github/hapjava/accessories/Fan.java deleted file mode 100644 index 9d5ac4276..000000000 --- a/src/main/java/io/github/hapjava/accessories/Fan.java +++ /dev/null @@ -1,99 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.*; -import io.github.hapjava.accessories.properties.RotationDirection; -import io.github.hapjava.impl.services.FanService; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.CompletableFuture; - -/** - * A fan, with power and rotational characteristics. - * - * @author Andy Lintner - */ -public interface Fan extends HomekitAccessory { - - /** - * Retrieves the current binary state of the fan's power. - * - * @return a future that will contain the binary state - */ - CompletableFuture getFanPower(); - - /** - * Retrieves the current rotation direction of the fan. - * - * @return a future that will contain the direction - */ - CompletableFuture getRotationDirection(); - - /** - * Retrieves the current speed of the fan's rotation - * - * @return a future that will contain the speed, expressed as an integer between 0 and 100. - */ - CompletableFuture getRotationSpeed(); - - /** - * Sets the binary state of the fan's power - * - * @param state the binary state to set - * @return a future that completes when the change is made - * @throws Exception when the change cannot be made - */ - CompletableFuture setFanPower(boolean state) throws Exception; - - /** - * Sets the rotation direction of the fan - * - * @param direction the direction to set - * @return a future that completes when the change is made - * @throws Exception when the change cannot be made - */ - CompletableFuture setRotationDirection(RotationDirection direction) throws Exception; - - /** - * Sets the speed of the fan's rotation - * - * @param speed the speed to set, expressed as an integer between 0 and 100. - * @return a future that completes when the change is made - * @throws Exception when the change cannot be made - */ - CompletableFuture setRotationSpeed(Integer speed) throws Exception; - - @Override - default Collection getServices() { - return Collections.singleton(new FanService(this)); - } - - /** - * Subscribes to changes in the binary state of the fan's power. - * - * @param callback the function to call when the state changes. - */ - void subscribeFanPower(HomekitCharacteristicChangeCallback callback); - - /** - * Subscribes to changes in the rotation direction of the fan. - * - * @param callback the function to call when the direction changes. - */ - void subscribeRotationDirection(HomekitCharacteristicChangeCallback callback); - - /** - * Subscribes to changes in the rotation speed of the fan. - * - * @param callback the function to call when the speed changes. - */ - void subscribeRotationSpeed(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the binary state of the fan's power. */ - void unsubscribeFanPower(); - - /** Unsubscribes from changes in the rotation direction of the fan. */ - void unsubscribeRotationDirection(); - - /** Unsubscribes from changes in the fan's rotation speed. */ - void unsubscribeRotationSpeed(); -} diff --git a/src/main/java/io/github/hapjava/accessories/FanAccessory.java b/src/main/java/io/github/hapjava/accessories/FanAccessory.java new file mode 100644 index 000000000..641214e76 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/FanAccessory.java @@ -0,0 +1,46 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.FanService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** + * A fan with mandatory characteristics. + * + * @author Andy Lintner + */ +public interface FanAccessory extends HomekitAccessory { + /** + * Mandatory: Retrieves the current active state of the fan'. + * + * @return a future that will contain the binary state + */ + CompletableFuture isActive(); + + /** + * Sets the active state of the fan + * + * @param state the binary state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setActive(boolean state) throws Exception; + + /** + * Subscribes to changes in the active state of the fan. + * + * @param callback the function to call when the active state changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state of the fan. */ + void unsubscribeActive(); + + @Override + default Collection getServices() { + return Collections.singleton(new FanService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/FaucetAccessory.java b/src/main/java/io/github/hapjava/accessories/FaucetAccessory.java new file mode 100644 index 000000000..7a000fcec --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/FaucetAccessory.java @@ -0,0 +1,42 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.FaucetService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Faucets or shower heads accessory. */ +public interface FaucetAccessory extends HomekitAccessory { + /** + * Mandatory: Retrieves the current active state of the faucet. + * + * @return a future that will contain the binary state + */ + CompletableFuture isActive(); + + /** + * Sets the active state of the faucet + * + * @param state the binary state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setActive(boolean state) throws Exception; + + /** + * Subscribes to changes in the active state of the faucet. + * + * @param callback the function to call when the active state changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state of the faucet. */ + void unsubscribeActive(); + + @Override + default Collection getServices() { + return Collections.singleton(new FaucetService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/FilterMaintenanceAccessory.java b/src/main/java/io/github/hapjava/accessories/FilterMaintenanceAccessory.java new file mode 100644 index 000000000..2ebee5495 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/FilterMaintenanceAccessory.java @@ -0,0 +1,40 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.filtermaintenance.FilterChangeIndicationEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.FilterMaintenanceService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** + * A Filter maintenance with mandatory characteristics. + * + *

The HomeKit app doesn't support a separate FilterMaintenance, but as a linked service to + * AirPurifier. + */ +public interface FilterMaintenanceAccessory extends HomekitAccessory { + + /** + * The filter change indictaion. It's either yes or no. + * + * @return FilterChangeIndicationEnum + */ + CompletableFuture getFilterChangeIndication(); + + /** + * Subscribes to changes in the filter change indication. + * + * @param callback the function to call when the state changes. + */ + void subscribeFilterChangeIndication(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the filter change indication. */ + void unsubscribeFilterChangeIndication(); + + @Override + default Collection getServices() { + return Collections.singleton(new FilterMaintenanceService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/GarageDoor.java b/src/main/java/io/github/hapjava/accessories/GarageDoorOpenerAccessory.java similarity index 71% rename from src/main/java/io/github/hapjava/accessories/GarageDoor.java rename to src/main/java/io/github/hapjava/accessories/GarageDoorOpenerAccessory.java index d94c1d071..37bd8a063 100644 --- a/src/main/java/io/github/hapjava/accessories/GarageDoor.java +++ b/src/main/java/io/github/hapjava/accessories/GarageDoorOpenerAccessory.java @@ -1,32 +1,34 @@ package io.github.hapjava.accessories; -import io.github.hapjava.*; -import io.github.hapjava.accessories.properties.DoorState; -import io.github.hapjava.impl.services.GarageDoorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.garagedoor.CurrentDoorStateEnum; +import io.github.hapjava.characteristics.impl.garagedoor.TargetDoorStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.GarageDoorOpenerService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; /** - * A garage door opener, with control and status of a garage door + * garage door opener accessory with control and status of a garage door * * @author Andy Lintner */ -public interface GarageDoor extends HomekitAccessory { +public interface GarageDoorOpenerAccessory extends HomekitAccessory { /** * Retrieves the current state of the door * * @return a future which will contain the door's state */ - CompletableFuture getCurrentDoorState(); + CompletableFuture getCurrentDoorState(); /** * Retrieves the targeted state of the door * * @return a future which will contain the door's targeted state */ - CompletableFuture getTargetDoorState(); + CompletableFuture getTargetDoorState(); /** * Retrieves an indicator of an obstruction detected by the door @@ -42,7 +44,7 @@ public interface GarageDoor extends HomekitAccessory { * @return a future that completes when the change is made * @throws Exception when the change cannot be made */ - CompletableFuture setTargetDoorState(DoorState state) throws Exception; + CompletableFuture setTargetDoorState(TargetDoorStateEnum state) throws Exception; /** * Subscribes to changes in the door's state @@ -76,6 +78,6 @@ public interface GarageDoor extends HomekitAccessory { @Override default Collection getServices() { - return Collections.singleton(new GarageDoorService(this)); + return Collections.singleton(new GarageDoorOpenerService(this)); } } diff --git a/src/main/java/io/github/hapjava/accessories/HeaterCoolerAccessory.java b/src/main/java/io/github/hapjava/accessories/HeaterCoolerAccessory.java new file mode 100644 index 000000000..d72af203a --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/HeaterCoolerAccessory.java @@ -0,0 +1,121 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.heatercooler.CurrentHeaterCoolerStateEnum; +import io.github.hapjava.characteristics.impl.heatercooler.TargetHeaterCoolerStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.HeaterCoolerService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Heater Cooler accessory */ +public interface HeaterCoolerAccessory extends HomekitAccessory { + /** + * Retrieves the current temperature, in celsius degrees. + * + * @return a future that will contain the temperature. + */ + CompletableFuture getCurrentTemperature(); + + /** + * Mandatory: Retrieves the current active state of the Heater Cooler. + * + * @return a future that will contain the binary state + */ + CompletableFuture isActive(); + + /** + * Sets the active state of the Heater Cooler + * + * @param state the binary state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setActive(boolean state) throws Exception; + + /** + * Retrieves the heater /cooler current state. + * + * @return a future that will contain the heater cooler current state . + */ + CompletableFuture getCurrentHeaterCoolerState(); + + /** + * Retrieves the heater cooler target state. + * + * @return a future that will contain the heater cooler target state . + */ + CompletableFuture getTargetHeaterCoolerState(); + + /** + * set heater cooler target state the lock target state. + * + * @param state heater cooler target state + * @return a future that completes when the change is made + */ + CompletableFuture setTargetHeaterCoolerState(TargetHeaterCoolerStateEnum state); + + /** + * Subscribes to changes in the heater cooler current state. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentHeaterCoolerState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in heater cooler current state. */ + void unsubscribeCurrentHeaterCoolerState(); + + /** + * Subscribes to changes in the heater cooler target state. + * + * @param callback the function to call when the state changes. + */ + void subscribeTargetHeaterCoolerState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in heater cooler target state. */ + void unsubscribeTargetHeaterCoolerState(); + + /** + * Subscribes to changes in the active state of the heater cooler . + * + * @param callback the function to call when the active state changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state of the heater cooler . */ + void unsubscribeActive(); + + /** + * Subscribes to changes in the current temperature. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentTemperature(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current temperature. */ + void unsubscribeCurrentTemperature(); + + /** + * Valid values for current state. + * + * @return array of valid current states + */ + default CurrentHeaterCoolerStateEnum[] getCurrentHeaterCoolerStateValidValues() { + return CurrentHeaterCoolerStateEnum.values(); + } + + /** + * Valid values for target state. + * + * @return array of valid target states + */ + default TargetHeaterCoolerStateEnum[] getTargetHeaterCoolerStateValidValues() { + return TargetHeaterCoolerStateEnum.values(); + } + + @Override + default Collection getServices() { + return Collections.singleton(new HeaterCoolerService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/HomekitAccessory.java b/src/main/java/io/github/hapjava/accessories/HomekitAccessory.java similarity index 55% rename from src/main/java/io/github/hapjava/HomekitAccessory.java rename to src/main/java/io/github/hapjava/accessories/HomekitAccessory.java index beb08eac3..64c406492 100644 --- a/src/main/java/io/github/hapjava/HomekitAccessory.java +++ b/src/main/java/io/github/hapjava/accessories/HomekitAccessory.java @@ -1,9 +1,14 @@ -package io.github.hapjava; +package io.github.hapjava.accessories; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.AccessoryInformationService; import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.concurrent.CompletableFuture; /** - * Base interface for all Homekit Accessories. You can implement this interface directly, but most + * Base interface for all HomeKit Accessories. You can implement this interface directly, but most * users will prefer to use the more full featured interfaces in {@link * io.github.hapjava.accessories} which include a default implementation of {@link #getServices()}. * @@ -21,11 +26,11 @@ public interface HomekitAccessory { int getId(); /** - * Returns a label to display in iOS. + * Returns a name to display in iOS. * * @return the label. */ - String getLabel(); + CompletableFuture getName(); /** * Performs an operation that can be used to identify the accessory. This action can be performed @@ -38,25 +43,32 @@ public interface HomekitAccessory { * * @return the serial number, or null. */ - String getSerialNumber(); + CompletableFuture getSerialNumber(); /** * Returns a model name to display in iOS. * * @return the model name, or null. */ - String getModel(); + CompletableFuture getModel(); /** * Returns a manufacturer to display in iOS. * * @return the manufacturer, or null. */ - String getManufacturer(); + CompletableFuture getManufacturer(); + + /** + * Returns a firmware revision to display in iOS. + * + * @return the firmware revision, or null. + */ + CompletableFuture getFirmwareRevision(); /** * The collection of Services this accessory supports. Services are the primary way to interact - * with the accessory via Homekit. Besides the Services offered here, the accessory will + * with the accessory via HomeKit. Besides the Services offered here, the accessory will * automatically include the required information service. * *

This method will only be useful if you're implementing your own accessory type. For the @@ -65,5 +77,23 @@ public interface HomekitAccessory { * * @return the collection of services. */ - Collection getServices(); + default Collection getServices() { + return Collections.singleton(new AccessoryInformationService(this)); + }; + + /** + * default implementation which is sufficient if accessory has only one service + * + * @return primary service + */ + default Service getPrimaryService() { + Iterator iterator = getServices().iterator(); + while (iterator.hasNext()) { + Service service = iterator.next(); + if (!(service instanceof AccessoryInformationService)) { + return service; + } + } + return null; + }; } diff --git a/src/main/java/io/github/hapjava/accessories/HumidifierDehumidifierAccessory.java b/src/main/java/io/github/hapjava/accessories/HumidifierDehumidifierAccessory.java new file mode 100644 index 000000000..63a460526 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/HumidifierDehumidifierAccessory.java @@ -0,0 +1,114 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.humidifier.CurrentHumidifierDehumidifierStateEnum; +import io.github.hapjava.characteristics.impl.humidifier.TargetHumidifierDehumidifierStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.HumidifierDehumidifierService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Humidifier/Dehumidifier accessory */ +public interface HumidifierDehumidifierAccessory extends HomekitAccessory { + /** + * Retrieves the current relative humidity. + * + * @return a future that will contain the humidity as a value between 0 and 100. + */ + CompletableFuture getCurrentHumidity(); + + /** + * Mandatory: Retrieves the current active state of the humidifier/dehumidifier. + * + * @return a future that will contain the binary state + */ + CompletableFuture isActive(); + + /** + * Sets the active state of the humidifier/dehumidifier + * + * @param state the binary state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setActive(boolean state) throws Exception; + + /** + * Retrieves the humidifier/dehumidifier current state. + * + * @return a future that will contain the humidifier/dehumidifier current state . + */ + CompletableFuture getCurrentHumidifierDehumidifierState(); + + /** + * Retrieves the humidifier/dehumidifier target state. + * + * @return a future that will contain the humidifier/dehumidifier target state . + */ + CompletableFuture getTargetHumidifierDehumidifierState(); + + /** + * set humidifier/dehumidifier target state the lock target state. + * + * @param state humidifier/dehumidifier target state + * @return a future that completes when the change is made + */ + CompletableFuture setTargetHumidifierDehumidifierState( + TargetHumidifierDehumidifierStateEnum state); + + /** + * Valid values for target state. + * + * @return array of valid target states. + */ + default TargetHumidifierDehumidifierStateEnum[] + getTargetHumidifierDehumidifierStateValidValues() { + return TargetHumidifierDehumidifierStateEnum.values(); + } + + /** + * Subscribes to changes in the humidifier/dehumidifier current state. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentHumidifierDehumidifierState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in humidifier/dehumidifier current state. */ + void unsubscribeCurrentHumidifierDehumidifierState(); + + /** + * Subscribes to changes in the humidifier/dehumidifier target state. + * + * @param callback the function to call when the state changes. + */ + void subscribeTargetHumidifierDehumidifierState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in humidifier/dehumidifier target state. */ + void unsubscribeTargetHumidifierDehumidifierState(); + + /** + * Subscribes to changes in the active state of the humidifier/dehumidifier . + * + * @param callback the function to call when the active state changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state of the humidifier/dehumidifier . */ + void unsubscribeActive(); + + /** + * Subscribes to changes in the current humidity. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentHumidity(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current humidity. */ + void unsubscribeCurrentHumidity(); + + @Override + default Collection getServices() { + return Collections.singleton(new HumidifierDehumidifierService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/HumiditySensor.java b/src/main/java/io/github/hapjava/accessories/HumiditySensorAccessory.java similarity index 78% rename from src/main/java/io/github/hapjava/accessories/HumiditySensor.java rename to src/main/java/io/github/hapjava/accessories/HumiditySensorAccessory.java index dd7335635..07c24be58 100644 --- a/src/main/java/io/github/hapjava/accessories/HumiditySensor.java +++ b/src/main/java/io/github/hapjava/accessories/HumiditySensorAccessory.java @@ -1,7 +1,8 @@ package io.github.hapjava.accessories; -import io.github.hapjava.*; -import io.github.hapjava.impl.services.HumiditySensorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.HumiditySensorService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -11,7 +12,7 @@ * * @author Andy Lintner */ -public interface HumiditySensor extends HomekitAccessory { +public interface HumiditySensorAccessory extends HomekitAccessory { /** * Retrieves the current relative humidity. @@ -20,11 +21,6 @@ public interface HumiditySensor extends HomekitAccessory { */ CompletableFuture getCurrentRelativeHumidity(); - @Override - default Collection getServices() { - return Collections.singleton(new HumiditySensorService(this)); - } - /** * Subscribes to changes in the current relative humidity. * @@ -34,4 +30,9 @@ default Collection getServices() { /** Unsubscribes from changes in the current relative humidity. */ void unsubscribeCurrentRelativeHumidity(); + + @Override + default Collection getServices() { + return Collections.singleton(new HumiditySensorService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/InputSourceAccessory.java b/src/main/java/io/github/hapjava/accessories/InputSourceAccessory.java new file mode 100644 index 000000000..cfa5ae3d6 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/InputSourceAccessory.java @@ -0,0 +1,104 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.IsConfiguredEnum; +import io.github.hapjava.characteristics.impl.inputsource.CurrentVisibilityStateEnum; +import io.github.hapjava.characteristics.impl.inputsource.InputSourceTypeEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.InputSourceService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Input Source accessory. */ +public interface InputSourceAccessory extends HomekitAccessory { + + /** + * Retrieves configured name of input source. + * + * @return configured name of input source + */ + CompletableFuture getConfiguredName(); + + /** + * Sets the configured name. + * + * @param name configured name + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setConfiguredName(String name) throws Exception; + + /** + * Subscribes to changes in configured name. + * + * @param callback the function to call when the configured name changes. + */ + void subscribeConfiguredName(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the configured name. */ + void unsubscribeConfiguredName(); + + /** + * Retrieves the flag whether input source is configured. + * + * @return a future that will contain the flag . + */ + CompletableFuture isConfigured(); + /** + * set the flag whether input source is configured. + * + * @param state is configured state + * @return a future that completes when the change is made + */ + CompletableFuture setIsConfigured(IsConfiguredEnum state); + + /** + * Subscribes to changes in isConfigured. + * + * @param callback the function to call when the state changes. + */ + void subscribeIsConfigured(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in isConfigured. */ + void unsubscribeIsConfigured(); + + /** + * Retrieves the input source type. + * + * @return a future that will contain the input source type. + */ + CompletableFuture getInputSourceType(); + + /** + * Subscribes to changes in input source type. + * + * @param callback the function to call when the type changes. + */ + void subscribeInputSourceType(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the input source type. */ + void unsubscribeInputSourceType(); + + /** + * Retrieves the current visibility state. + * + * @return a future that will contain the current visibility state. + */ + CompletableFuture getCurrentVisibilityState(); + + /** + * Subscribes to changes in current visibility state. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentVisibilityState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current visibility state. */ + void unsubscribeCurrentVisibilityState(); + + @Override + default Collection getServices() { + return Collections.singleton(new InputSourceService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/IrrigationSystemAccessory.java b/src/main/java/io/github/hapjava/accessories/IrrigationSystemAccessory.java new file mode 100644 index 000000000..dffa2e00b --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/IrrigationSystemAccessory.java @@ -0,0 +1,82 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.InUseEnum; +import io.github.hapjava.characteristics.impl.common.ProgramModeEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.IrrigationSystemService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** irrigation system accessory that controls several valves. */ +public interface IrrigationSystemAccessory extends HomekitAccessory { + + /** + * An irrigation system is set to Active when the system is enabled. When one of the valves is set + * to In Use, the irrigation system must be set to in use. + * + * @return a future that will contain the binary state + */ + CompletableFuture getActive(); + + /** + * Sets the irrigation active state + * + * @param active the binary state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setActive(ActiveEnum active) throws Exception; + + /** + * Retrieves the program mode status + * + * @return a future that will contain the valve type. + */ + CompletableFuture getProgramMode(); + + /** + * Retrieves the current inUse state of the irrigation; InUse means one of the valves is set to In + * Use. + * + * @return a future that will contain the binary state + */ + CompletableFuture getInUse(); + + /** + * Subscribes to changes in the inUse state. + * + * @param callback the function to call when the state changes. + */ + void subscribeInUse(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the inUse state. */ + void unsubscribeInUse(); + + /** + * Subscribes to changes in the active state of the irrigation. + * + * @param callback the function to call when the state changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the irrigation active state. */ + void unsubscribeActive(); + + /** + * Subscribes to changes in the program mode of the irrigation system. + * + * @param callback the function to call when the state changes. + */ + void subscribeProgramMode(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the program mode. */ + void unsubscribeProgramMode(); + + @Override + default Collection getServices() { + return Collections.singleton(new IrrigationSystemService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/LeakSensor.java b/src/main/java/io/github/hapjava/accessories/LeakSensorAccessory.java similarity index 65% rename from src/main/java/io/github/hapjava/accessories/LeakSensor.java rename to src/main/java/io/github/hapjava/accessories/LeakSensorAccessory.java index aad2266e9..c36ce278c 100644 --- a/src/main/java/io/github/hapjava/accessories/LeakSensor.java +++ b/src/main/java/io/github/hapjava/accessories/LeakSensorAccessory.java @@ -1,9 +1,9 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.impl.services.LeakSensorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.leaksensor.LeakDetectedStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.LeakSensorService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -11,24 +11,16 @@ /** * A leak sensor that reports whether a leak has been detected. * - *

Leak sensors that run on batteries will need to implement this interface and also implement - * {@link BatteryStatusAccessory}. - * * @author Tim Harper */ -public interface LeakSensor extends HomekitAccessory { +public interface LeakSensorAccessory extends HomekitAccessory { /** * Retrieves the state of the leak sensor. If true then leak has been detected. * * @return a future that will contain the leak sensor's state */ - CompletableFuture getLeakDetected(); - - @Override - default Collection getServices() { - return Collections.singleton(new LeakSensorService(this)); - } + CompletableFuture getLeakDetected(); /** * Subscribes to changes in the leak sensor. @@ -39,4 +31,9 @@ default Collection getServices() { /** Unsubscribes from changes in the leak sensor. */ void unsubscribeLeakDetected(); + + @Override + default Collection getServices() { + return Collections.singleton(new LeakSensorService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/LightSensor.java b/src/main/java/io/github/hapjava/accessories/LightSensor.java deleted file mode 100644 index 12b2e05d3..000000000 --- a/src/main/java/io/github/hapjava/accessories/LightSensor.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.impl.services.LightSensorService; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.CompletableFuture; - -/** - * A light sensor that reports current ambient light level. - * - * @author Gaston Dombiak - */ -public interface LightSensor extends HomekitAccessory { - - /** - * Retrieves the current ambient light level. - * - * @return a future that will contain the luminance level expressed in LUX. - */ - CompletableFuture getCurrentAmbientLightLevel(); - - @Override - default Collection getServices() { - return Collections.singleton(new LightSensorService(this)); - } - - /** - * Subscribes to changes in the current ambient light level. - * - * @param callback the function to call when the state changes. - */ - void subscribeCurrentAmbientLightLevel(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the current ambient light level. */ - void unsubscribeCurrentAmbientLightLevel(); -} diff --git a/src/main/java/io/github/hapjava/accessories/LightSensorAccessory.java b/src/main/java/io/github/hapjava/accessories/LightSensorAccessory.java new file mode 100644 index 000000000..2087b1e99 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/LightSensorAccessory.java @@ -0,0 +1,69 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.lightsensor.CurrentAmbientLightLevelCharacteristic; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.LightSensorService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** + * A light sensor that reports current ambient light level. + * + * @author Gaston Dombiak + */ +public interface LightSensorAccessory extends HomekitAccessory { + + /** + * Retrieves the current ambient light level. + * + * @return a future that will contain the luminance level expressed in LUX. + */ + CompletableFuture getCurrentAmbientLightLevel(); + + /** + * Subscribes to changes in the current ambient light level. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentAmbientLightLevel(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current ambient light level. */ + void unsubscribeCurrentAmbientLightLevel(); + + /** + * return the min value for current ambient light level. overwrite if you want to change the + * default value. + * + * @return min current ambient light level + */ + default double getMinCurrentAmbientLightLevel() { + return CurrentAmbientLightLevelCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for current ambient light level. overwrite if you want to change the + * default value. + * + * @return max current ambient light level + */ + default double getMaxCurrentAmbientLightLevel() { + return CurrentAmbientLightLevelCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for current ambient light level. overwrite if you want to change the + * default value. + * + * @return min step current ambient light level + */ + default double getMinStepCurrentAmbientLightLevel() { + return CurrentAmbientLightLevelCharacteristic.DEFAULT_STEP; + } + + @Override + default Collection getServices() { + return Collections.singleton(new LightSensorService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/Lightbulb.java b/src/main/java/io/github/hapjava/accessories/LightbulbAccessory.java similarity index 83% rename from src/main/java/io/github/hapjava/accessories/Lightbulb.java rename to src/main/java/io/github/hapjava/accessories/LightbulbAccessory.java index c39b659eb..8a6caaed8 100644 --- a/src/main/java/io/github/hapjava/accessories/Lightbulb.java +++ b/src/main/java/io/github/hapjava/accessories/LightbulbAccessory.java @@ -1,7 +1,8 @@ package io.github.hapjava.accessories; -import io.github.hapjava.*; -import io.github.hapjava.impl.services.LightbulbService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.LightbulbService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -11,7 +12,7 @@ * * @author Andy Lintner */ -public interface Lightbulb extends HomekitAccessory { +public interface LightbulbAccessory extends HomekitAccessory { /** * Retrieves the current binary state of the light. @@ -29,11 +30,6 @@ public interface Lightbulb extends HomekitAccessory { */ CompletableFuture setLightbulbPowerState(boolean powerState) throws Exception; - @Override - default Collection getServices() { - return Collections.singleton(new LightbulbService(this)); - } - /** * Subscribes to changes in the binary state of the light. * @@ -43,4 +39,9 @@ default Collection getServices() { /** Unsubscribes from changes in the binary state of the light. */ void unsubscribeLightbulbPowerState(); + + @Override + default Collection getServices() { + return Collections.singleton(new LightbulbService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/LockMechanism.java b/src/main/java/io/github/hapjava/accessories/LockMechanism.java deleted file mode 100644 index f1eb051e7..000000000 --- a/src/main/java/io/github/hapjava/accessories/LockMechanism.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.properties.LockMechanismState; -import io.github.hapjava.impl.services.LockMechanismService; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.CompletableFuture; - -/** - * A lock capable of exposing its binary locked state. For a lock that can be locked/unlocked, use - * {@link LockableLockMechanism}. - * - *

Locks that run on batteries will need to implement this interface and also implement {@link - * BatteryStatusAccessory}. - * - * @author Andy Lintner - */ -public interface LockMechanism extends HomekitAccessory { - - /** - * Retrieves the current binary state of the lock. - * - * @return a future that will contain the binary state. - */ - CompletableFuture getCurrentMechanismState(); - - /** - * Subscribes to changes in the binary state of the lock. - * - * @param callback the function to call when the state changes. - */ - void subscribeCurrentMechanismState(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the binary state of the lock. */ - void unsubscribeCurrentMechanismState(); - - @Override - default Collection getServices() { - return Collections.singleton(new LockMechanismService(this)); - } -} diff --git a/src/main/java/io/github/hapjava/accessories/LockMechanismAccessory.java b/src/main/java/io/github/hapjava/accessories/LockMechanismAccessory.java new file mode 100644 index 000000000..f12f3e286 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/LockMechanismAccessory.java @@ -0,0 +1,61 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.lock.LockCurrentStateEnum; +import io.github.hapjava.characteristics.impl.lock.LockTargetStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.LockMechanismService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Lock mechanism with current and target state. */ +public interface LockMechanismAccessory extends HomekitAccessory { + + /** + * Retrieves the lock current state. + * + * @return a future that will contain the lock current state . + */ + CompletableFuture getLockCurrentState(); + + /** + * Retrieves the lock target state. + * + * @return a future that will contain the lock target state . + */ + CompletableFuture getLockTargetState(); + + /** + * set lock target state the lock target state. + * + * @param state lock target state + * @return a future that completes when the change is made + */ + CompletableFuture setLockTargetState(LockTargetStateEnum state); + + /** + * Subscribes to changes in the lock current state. + * + * @param callback the function to call when the state changes. + */ + void subscribeLockCurrentState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in lock current state. */ + void unsubscribeLockCurrentState(); + + /** + * Subscribes to changes in the lock target state. + * + * @param callback the function to call when the state changes. + */ + void subscribeLockTargetState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in lock target state. */ + void unsubscribeLockTargetState(); + + @Override + default Collection getServices() { + return Collections.singleton(new LockMechanismService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/LockableLockMechanism.java b/src/main/java/io/github/hapjava/accessories/LockableLockMechanism.java deleted file mode 100644 index 474c8abd6..000000000 --- a/src/main/java/io/github/hapjava/accessories/LockableLockMechanism.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.properties.LockMechanismState; -import java.util.concurrent.CompletableFuture; - -/** - * Extends {@link LockMechanism} with the ability to lock and unlock the mechanism. - * - * @author Andy Lintner - */ -public interface LockableLockMechanism extends LockMechanism { - - /** - * Sets the binary state of the lock mechanism. - * - * @param state true for a locked mechanism, false for unlocked. - * @throws Exception when the change cannot be made. - */ - void setTargetMechanismState(LockMechanismState state) throws Exception; - - /** - * Retrieves the pending, but not yet completed, state of the lock mechanism. - * - * @return the binary state - */ - CompletableFuture getTargetMechanismState(); - - /** - * Subscribes to changes in the pending, but not yet completed, binary state. - * - * @param callback the function to call when the state changes. - */ - void subscribeTargetMechanismState(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the pending, but not yet completed, binary state. */ - void unsubscribeTargetMechanismState(); -} diff --git a/src/main/java/io/github/hapjava/accessories/MicrophoneAccessory.java b/src/main/java/io/github/hapjava/accessories/MicrophoneAccessory.java new file mode 100644 index 000000000..f63f8b70c --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/MicrophoneAccessory.java @@ -0,0 +1,43 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.MicrophoneService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Microphone accessory with mute state. */ +public interface MicrophoneAccessory extends HomekitAccessory { + + /** + * Retrieves mute status. + * + * @return true if accessory is muted + */ + CompletableFuture isMuted(); + + /** + * Sets the mute status + * + * @param mute true if accessory should be muted + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setMute(boolean mute) throws Exception; + + /** + * Subscribes to changes in mute state. + * + * @param callback the function to call when the state changes. + */ + void subscribeMuteState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the mute state. */ + void unsubscribeMuteState(); + + @Override + default Collection getServices() { + return Collections.singleton(new MicrophoneService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/MotionSensor.java b/src/main/java/io/github/hapjava/accessories/MotionSensorAccessory.java similarity index 69% rename from src/main/java/io/github/hapjava/accessories/MotionSensor.java rename to src/main/java/io/github/hapjava/accessories/MotionSensorAccessory.java index dc424625b..e843068b1 100644 --- a/src/main/java/io/github/hapjava/accessories/MotionSensor.java +++ b/src/main/java/io/github/hapjava/accessories/MotionSensorAccessory.java @@ -1,9 +1,8 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.impl.services.MotionSensorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.MotionSensorService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -11,12 +10,9 @@ /** * A motion sensor that reports whether motion has been detected. * - *

Motion sensors that run on batteries will need to implement this interface and also implement - * {@link BatteryStatusAccessory}. - * * @author Gaston Dombiak */ -public interface MotionSensor extends HomekitAccessory { +public interface MotionSensorAccessory extends HomekitAccessory { /** * Retrieves the state of the motion sensor. If true then motion has been detected. @@ -25,11 +21,6 @@ public interface MotionSensor extends HomekitAccessory { */ CompletableFuture getMotionDetected(); - @Override - default Collection getServices() { - return Collections.singleton(new MotionSensorService(this)); - } - /** * Subscribes to changes in the motion sensor. * @@ -39,4 +30,9 @@ default Collection getServices() { /** Unsubscribes from changes in the motion sensor. */ void unsubscribeMotionDetected(); + + @Override + default Collection getServices() { + return Collections.singleton(new MotionSensorService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/OccupancySensor.java b/src/main/java/io/github/hapjava/accessories/OccupancySensorAccessory.java similarity index 65% rename from src/main/java/io/github/hapjava/accessories/OccupancySensor.java rename to src/main/java/io/github/hapjava/accessories/OccupancySensorAccessory.java index 0148a6f9f..5fc3cff1e 100644 --- a/src/main/java/io/github/hapjava/accessories/OccupancySensor.java +++ b/src/main/java/io/github/hapjava/accessories/OccupancySensorAccessory.java @@ -1,9 +1,9 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.impl.services.OccupancySensorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.occupancysensor.OccupancyDetectedEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.OccupancySensorService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -11,23 +11,15 @@ /** * An occupancy sensor that reports whether occupancy has been detected. * - *

Occupancy sensors that run on batteries will need to implement this interface and also - * implement {@link BatteryStatusAccessory}. - * * @author Tim Harper */ -public interface OccupancySensor extends HomekitAccessory { +public interface OccupancySensorAccessory extends HomekitAccessory { /** * Retrieves the state of the occupancy sensor. If true then occupancy has been detected. * * @return a future that will contain the occupancy sensor's state */ - CompletableFuture getOccupancyDetected(); - - @Override - default Collection getServices() { - return Collections.singleton(new OccupancySensorService(this)); - } + CompletableFuture getOccupancyDetected(); /** * Subscribes to changes in the occupancy sensor. @@ -38,4 +30,9 @@ default Collection getServices() { /** Unsubscribes from changes in the occupancy sensor. */ void unsubscribeOccupancyDetected(); + + @Override + default Collection getServices() { + return Collections.singleton(new OccupancySensorService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/Outlet.java b/src/main/java/io/github/hapjava/accessories/OutletAccessory.java similarity index 88% rename from src/main/java/io/github/hapjava/accessories/Outlet.java rename to src/main/java/io/github/hapjava/accessories/OutletAccessory.java index 4578bfea4..213f673b7 100644 --- a/src/main/java/io/github/hapjava/accessories/Outlet.java +++ b/src/main/java/io/github/hapjava/accessories/OutletAccessory.java @@ -1,7 +1,8 @@ package io.github.hapjava.accessories; -import io.github.hapjava.*; -import io.github.hapjava.impl.services.OutletService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.OutletService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -11,12 +12,7 @@ * * @author Andy Lintner */ -public interface Outlet extends HomekitAccessory { - - @Override - default Collection getServices() { - return Collections.singleton(new OutletService(this)); - } +public interface OutletAccessory extends HomekitAccessory { /** * Retrieves the current binary state of the outlet's power. @@ -60,4 +56,9 @@ default Collection getServices() { /** Unsubscribes from changes in the binary state indicating whether hte outlet is in use. */ void unsubscribeOutletInUse(); + + @Override + default Collection getServices() { + return Collections.singleton(new OutletService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/SecuritySystem.java b/src/main/java/io/github/hapjava/accessories/SecuritySystemAccessory.java similarity index 60% rename from src/main/java/io/github/hapjava/accessories/SecuritySystem.java rename to src/main/java/io/github/hapjava/accessories/SecuritySystemAccessory.java index fcf1d1f6f..43c12acd2 100644 --- a/src/main/java/io/github/hapjava/accessories/SecuritySystem.java +++ b/src/main/java/io/github/hapjava/accessories/SecuritySystemAccessory.java @@ -1,12 +1,10 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.properties.CurrentSecuritySystemState; -import io.github.hapjava.accessories.properties.SecuritySystemAlarmType; -import io.github.hapjava.accessories.properties.TargetSecuritySystemState; -import io.github.hapjava.impl.services.SecuritySystemService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.securitysystem.CurrentSecuritySystemStateEnum; +import io.github.hapjava.characteristics.impl.securitysystem.TargetSecuritySystemStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.SecuritySystemService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -14,11 +12,11 @@ /** * A security system that can be armed so that when a contact sensor is opened or a motion sensor * detects movement, then a siren could be fired off. There are different modes for arming the - * system. See {@link TargetSecuritySystemState} for more information. + * system. See {@link TargetSecuritySystemStateEnum} for more information. * * @author Gaston Dombiak */ -public interface SecuritySystem extends HomekitAccessory { +public interface SecuritySystemAccessory extends HomekitAccessory { /** * Retrieves the current state of the security system. The state describes if the system is armed @@ -26,7 +24,7 @@ public interface SecuritySystem extends HomekitAccessory { * * @return current state of the security system. */ - CompletableFuture getCurrentSecuritySystemState(); + CompletableFuture getCurrentSecuritySystemState(); /** * Subscribes to changes to the state of the security system. @@ -45,14 +43,14 @@ public interface SecuritySystem extends HomekitAccessory { * @param state target state of the security system. * @throws Exception when the change cannot be made. */ - void setTargetSecuritySystemState(TargetSecuritySystemState state) throws Exception; + void setTargetSecuritySystemState(TargetSecuritySystemStateEnum state) throws Exception; /** * Retrieves the pending, but not yet completed, state of the security system. * * @return target state of the security system. */ - CompletableFuture getTargetSecuritySystemState(); + CompletableFuture getTargetSecuritySystemState(); /** * Subscribes to changes in the pending, but not yet completed, state of the security system. @@ -67,21 +65,22 @@ public interface SecuritySystem extends HomekitAccessory { void unsubscribeTargetSecuritySystemState(); /** - * Retrieves the alarm type of the security system. + * Valid values for current state. * - * @return alarm type of the security system. + * @return array of valid current states. */ - CompletableFuture getAlarmTypeState(); + default CurrentSecuritySystemStateEnum[] getCurrentSecuritySystemStateValidValues() { + return CurrentSecuritySystemStateEnum.values(); + } /** - * Subscribes to changes to the alarm type of the security system. + * Valid values for target state. * - * @param callback the function to call when the alarm type changes. + * @return array of valid targe states. */ - void subscribeAlarmTypeState(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the alarm type of the security system. */ - void unsubscribeAlarmTypeState(); + default TargetSecuritySystemStateEnum[] getTargetSecuritySystemStateValidValues() { + return TargetSecuritySystemStateEnum.values(); + } @Override default Collection getServices() { diff --git a/src/main/java/io/github/hapjava/accessories/SlatAccessory.java b/src/main/java/io/github/hapjava/accessories/SlatAccessory.java new file mode 100644 index 000000000..62888ab60 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/SlatAccessory.java @@ -0,0 +1,43 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.slat.CurrentSlatStateEnum; +import io.github.hapjava.characteristics.impl.slat.SlatTypeEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.SlatService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** A slat accessory which tilts on a vertical or a horizontal axis. */ +public interface SlatAccessory extends HomekitAccessory { + + /** + * Retrieves the current state of the slat + * + * @return a future that will contain the state + */ + CompletableFuture getSlatState(); + + /** + * Subscribes to changes in the state of the slat. + * + * @param callback the function to call when the state changes. + */ + void subscribeSlatState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the state of the slat. */ + void unsubscribeSlatState(); + + /** + * Retrieves the slat type. + * + * @return a future that will slat type. + */ + CompletableFuture getSlatType(); + + @Override + default Collection getServices() { + return Collections.singleton(new SlatService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/SmartSpeakerAccessory.java b/src/main/java/io/github/hapjava/accessories/SmartSpeakerAccessory.java new file mode 100644 index 000000000..9f70af2be --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/SmartSpeakerAccessory.java @@ -0,0 +1,62 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.television.CurrentMediaStateEnum; +import io.github.hapjava.characteristics.impl.television.TargetMediaStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.SmartSpeakerService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Smart Speaker accessory. */ +public interface SmartSpeakerAccessory extends HomekitAccessory { + + /** + * Retrieves the current media state (see {@link + * io.github.hapjava.characteristics.impl.television.CurrentMediaStateEnum} for supported values). + * + * @return a future that will contain the current media state + */ + CompletableFuture getCurrentMediaState(); + + /** + * Subscribes to changes in the current media state. + * + * @param callback the function to call when the current media state changes. + */ + void subscribeCurrentMediaState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current media state. */ + void unsubscribeCurrentMediaState(); + + /** + * Retrieves the target media state (see {@link TargetMediaStateEnum} for supported values). + * + * @return a future that will contain the target media state + */ + CompletableFuture getTargetMediaState(); + + /** + * Set the target media state (see {@link TargetMediaStateEnum} for supported values). + * + * @param targetMediaState target media state + * @return a future that completes when the change is made + */ + CompletableFuture setTargetMediaState(TargetMediaStateEnum targetMediaState); + + /** + * Subscribes to changes in the target media state. + * + * @param callback the function to call when the target media state changes. + */ + void subscribeTargetMediaState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the target media state. */ + void unsubscribeTargetMediaState(); + + @Override + default Collection getServices() { + return Collections.singleton(new SmartSpeakerService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/SmokeSensor.java b/src/main/java/io/github/hapjava/accessories/SmokeSensorAccessory.java similarity index 62% rename from src/main/java/io/github/hapjava/accessories/SmokeSensor.java rename to src/main/java/io/github/hapjava/accessories/SmokeSensorAccessory.java index 68f43d1a7..b6a8b1054 100644 --- a/src/main/java/io/github/hapjava/accessories/SmokeSensor.java +++ b/src/main/java/io/github/hapjava/accessories/SmokeSensorAccessory.java @@ -1,10 +1,9 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.properties.SmokeDetectedState; -import io.github.hapjava.impl.services.SmokeSensorService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.smokesensor.SmokeDetectedStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.SmokeSensorService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -12,24 +11,16 @@ /** * A smoke sensor reports whether smoke has been detected or not. * - *

Smoke sensors that run on batteries will need to implement this interface and also implement - * {@link BatteryStatusAccessory}. - * * @author Gaston Dombiak */ -public interface SmokeSensor extends HomekitAccessory { +public interface SmokeSensorAccessory extends HomekitAccessory { /** * Retrieves the state of the smoke sensor. This is whether smoke has been detected or not. * * @return a future that will contain the smoke sensor's state */ - CompletableFuture getSmokeDetectedState(); - - @Override - default Collection getServices() { - return Collections.singleton(new SmokeSensorService(this)); - } + CompletableFuture getSmokeDetectedState(); /** * Subscribes to changes in the smoke sensor's state. @@ -40,4 +31,9 @@ default Collection getServices() { /** Unsubscribes from changes in the smoke sensor's state. */ void unsubscribeSmokeDetectedState(); + + @Override + default Collection getServices() { + return Collections.singleton(new SmokeSensorService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/SpeakerAccessory.java b/src/main/java/io/github/hapjava/accessories/SpeakerAccessory.java new file mode 100644 index 000000000..661607a30 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/SpeakerAccessory.java @@ -0,0 +1,43 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.SpeakerService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Speaker accessory. */ +public interface SpeakerAccessory extends HomekitAccessory { + + /** + * Retrieves mute status. + * + * @return true if accessory is muted + */ + CompletableFuture isMuted(); + + /** + * Sets the mute status + * + * @param mute true if accessory should be muted + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setMute(boolean mute) throws Exception; + + /** + * Subscribes to changes in mute state. + * + * @param callback the function to call when the state changes. + */ + void subscribeMuteState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the mute state. */ + void unsubscribeMuteState(); + + @Override + default Collection getServices() { + return Collections.singleton(new SpeakerService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/StatelessProgrammableSwitchAccessory.java b/src/main/java/io/github/hapjava/accessories/StatelessProgrammableSwitchAccessory.java new file mode 100644 index 000000000..354c36587 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/StatelessProgrammableSwitchAccessory.java @@ -0,0 +1,36 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.ProgrammableSwitchEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.StatelessProgrammableSwitchService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** The Stateless Programmable Switch accessory */ +public interface StatelessProgrammableSwitchAccessory extends HomekitAccessory { + + /** + * Retrieves the last states of the switch. Bluetooth device should return the last event, the IP + * device should always return null + * + * @return state of the switch event + */ + CompletableFuture getSwitchEvent(); + + /** + * Subscribes to changes in switch event, i.e. pressing on the button. + * + * @param callback the function to call when the state changes. + */ + void subscribeSwitchEvent(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in switch event. */ + void unsubscribeSwitchEvent(); + + @Override + default Collection getServices() { + return Collections.singleton(new StatelessProgrammableSwitchService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/Switch.java b/src/main/java/io/github/hapjava/accessories/SwitchAccessory.java similarity index 82% rename from src/main/java/io/github/hapjava/accessories/Switch.java rename to src/main/java/io/github/hapjava/accessories/SwitchAccessory.java index 682d758c2..aae442f90 100644 --- a/src/main/java/io/github/hapjava/accessories/Switch.java +++ b/src/main/java/io/github/hapjava/accessories/SwitchAccessory.java @@ -1,7 +1,8 @@ package io.github.hapjava.accessories; -import io.github.hapjava.*; -import io.github.hapjava.impl.services.SwitchService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.SwitchService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -11,7 +12,7 @@ * * @author Andy Lintner */ -public interface Switch extends HomekitAccessory { +public interface SwitchAccessory extends HomekitAccessory { /** * Retrieves the current binary state of the switch. @@ -29,11 +30,6 @@ public interface Switch extends HomekitAccessory { */ CompletableFuture setSwitchState(boolean state) throws Exception; - @Override - default Collection getServices() { - return Collections.singleton(new SwitchService(this)); - } - /** * Subscribes to changes in the binary state of the switch. * @@ -43,4 +39,9 @@ default Collection getServices() { /** Unsubscribes from changes in the binary state of the switch. */ void unsubscribeSwitchState(); + + @Override + default Collection getServices() { + return Collections.singleton(new SwitchService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/TelevisionAccessory.java b/src/main/java/io/github/hapjava/accessories/TelevisionAccessory.java new file mode 100644 index 000000000..b51efe319 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/TelevisionAccessory.java @@ -0,0 +1,123 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.television.RemoteKeyEnum; +import io.github.hapjava.characteristics.impl.television.SleepDiscoveryModeEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.TelevisionService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Television accessory. */ +public interface TelevisionAccessory extends HomekitAccessory { + + /** + * Retrieves the current active state of the TV. + * + * @return a future that will contain the state + */ + CompletableFuture isActive(); + + /** + * Sets the active state of the TV + * + * @param state the state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setActive(boolean state) throws Exception; + + /** + * Subscribes to changes in the active state of the TV . + * + * @param callback the function to call when the active state changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state of the TV. */ + void unsubscribeActive(); + + /** + * Retrieves the active identifier + * + * @return a future that will contain the active identifier. + */ + CompletableFuture getActiveIdentifier(); + + /** + * Sets the active identifier + * + * @param identifier the active identifier + * @return a future that completes when the active identifier is changed + * @throws Exception when the active identifier cannot be set + */ + CompletableFuture setActiveIdentifier(Integer identifier) throws Exception; + + /** + * Subscribes to changes in the active identifier. + * + * @param callback the function to call when the active identifier changes. + */ + void subscribeActiveIdentifier(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active identifier. */ + void unsubscribeActiveIdentifier(); + + /** + * Retrieves configured name. + * + * @return configured name + */ + CompletableFuture getConfiguredName(); + + /** + * Sets the configured name + * + * @param name configured name + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setConfiguredName(String name) throws Exception; + + /** + * Subscribes to changes in configured name. + * + * @param callback the function to call when the configureed name changes. + */ + void subscribeConfiguredName(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the configured name state. */ + void unsubscribeConfiguredName(); + + /** + * Sends the remote key. + * + * @param key remote key + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setRemoteKey(RemoteKeyEnum key) throws Exception; + + /** + * Retrieves the sleep discovery mode. + * + * @return a future that will contain the sleep discovery mode . + */ + CompletableFuture getSleepDiscoveryMode(); + + /** + * Subscribes to changes in sleep discovery mode. + * + * @param callback the function to call when the sleep discovery mode changes. + */ + void subscribeSleepDiscoveryMode(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the sleep discovery mode. */ + void unsubscribeSleepDiscoveryMode(); + + @Override + default Collection getServices() { + return Collections.singleton(new TelevisionService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/TelevisionSpeakerAccessory.java b/src/main/java/io/github/hapjava/accessories/TelevisionSpeakerAccessory.java new file mode 100644 index 000000000..28df1437d --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/TelevisionSpeakerAccessory.java @@ -0,0 +1,43 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.TelevisionSpeakerService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** Television speaker accessory. */ +public interface TelevisionSpeakerAccessory extends HomekitAccessory { + + /** + * Retrieves mute status. + * + * @return true if accessory is muted + */ + CompletableFuture isMuted(); + + /** + * Sets the mute status + * + * @param mute true if accessory should be muted + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setMute(boolean mute) throws Exception; + + /** + * Subscribes to changes in mute state. + * + * @param callback the function to call when the state changes. + */ + void subscribeMuteState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the mute state. */ + void unsubscribeMuteState(); + + @Override + default Collection getServices() { + return Collections.singleton(new TelevisionSpeakerService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/TemperatureSensor.java b/src/main/java/io/github/hapjava/accessories/TemperatureSensor.java deleted file mode 100644 index a53b40a00..000000000 --- a/src/main/java/io/github/hapjava/accessories/TemperatureSensor.java +++ /dev/null @@ -1,83 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.*; -import io.github.hapjava.accessories.properties.TemperatureUnit; -import io.github.hapjava.impl.services.TemperatureSensorService; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.CompletableFuture; - -/** - * A temperature sensor that reports the current temperature - * - * @author Andy Lintner - */ -public interface TemperatureSensor extends HomekitAccessory { - - /** - * Retrieves the current temperature, in celsius degrees. - * - * @return a future that will contain the temperature. - */ - CompletableFuture getCurrentTemperature(); - - @Override - default Collection getServices() { - return Collections.singleton(new TemperatureSensorService(this)); - } - - /** - * Subscribes to changes in the current temperature. - * - * @param callback the function to call when the state changes. - */ - void subscribeCurrentTemperature(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the current temperature. */ - void unsubscribeCurrentTemperature(); - - /** - * Retrieves the minimum temperature, in celsius degrees, the thermostat can be set to. - * - * @return the minimum temperature. - */ - double getMinimumTemperature(); - - /** - * Retrieves the maximum temperature, in celsius degrees, the thermostat can be set to. - * - * @return the maximum temperature. - */ - double getMaximumTemperature(); - - /** - * Retrieves the temperature unit of the thermostat. The impact of this is unclear, as the actual - * temperature is always communicated in celsius degrees, and the iOS device uses the user's - * locale to determine the unit to convert to. - * - * @return the temperature unit of the thermostat. - */ - default TemperatureUnit getTemperatureUnit() { - return TemperatureUnit.CELSIUS; - } - - /** - * set default temperature unit of the thermostat. this is the unit thermostat use to display - * temprature. the homekit interface uses celsius. - * - * @param unit the temperature unit of the thermostat. - */ - default void setTemperatureUnit(TemperatureUnit unit) { - // override depending on the thermostat if required. - } - - /** - * subscribe to unit changes. - * - * @param callback callback - */ - default void subscribeTemperatureUnit(final HomekitCharacteristicChangeCallback callback) {} - - /** unsubscribe from unit changes. */ - default void unsubscribeTemperatureUnit() {} -} diff --git a/src/main/java/io/github/hapjava/accessories/TemperatureSensorAccessory.java b/src/main/java/io/github/hapjava/accessories/TemperatureSensorAccessory.java new file mode 100644 index 000000000..4f9184926 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/TemperatureSensorAccessory.java @@ -0,0 +1,68 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.TemperatureSensorService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** + * A temperature sensor that reports the current temperature + * + * @author Andy Lintner + */ +public interface TemperatureSensorAccessory extends HomekitAccessory { + + /** + * Retrieves the current temperature, in celsius degrees. + * + * @return a future that will contain the temperature. + */ + CompletableFuture getCurrentTemperature(); + + /** + * return the min value for current temperature. overwrite if you want to change the default + * value. + * + * @return min current temperature + */ + default double getMinCurrentTemperature() { + return 0; + } + + /** + * return the max value for current temperature. overwrite if you want to change the default + * value. + * + * @return max current temperature + */ + default double getMaxCurrentTemperature() { + return 100; + } + + /** + * return the min step value for current temperature. overwrite if you want to change the default + * value. + * + * @return min step current temperature + */ + default double getMinStepCurrentTemperature() { + return 0.1; + } + + /** + * Subscribes to changes in the current temperature. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentTemperature(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current temperature. */ + void unsubscribeCurrentTemperature(); + + @Override + default Collection getServices() { + return Collections.singleton(new TemperatureSensorService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/Thermostat.java b/src/main/java/io/github/hapjava/accessories/Thermostat.java deleted file mode 100644 index 54b1ca625..000000000 --- a/src/main/java/io/github/hapjava/accessories/Thermostat.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.accessories.thermostat.*; - -/** - * A thermostat with heating and cooling controls. - * - * @author Andy Lintner - * @deprecated Use {@link BasicThermostat}, {@link HeatingThermostat}, and {@link CoolingThermostat} - * instead - */ -@Deprecated -public interface Thermostat extends BasicThermostat, HeatingThermostat, CoolingThermostat {} diff --git a/src/main/java/io/github/hapjava/accessories/ThermostatAccessory.java b/src/main/java/io/github/hapjava/accessories/ThermostatAccessory.java new file mode 100644 index 000000000..837993853 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/ThermostatAccessory.java @@ -0,0 +1,214 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.thermostat.CurrentHeatingCoolingStateEnum; +import io.github.hapjava.characteristics.impl.thermostat.TargetHeatingCoolingStateEnum; +import io.github.hapjava.characteristics.impl.thermostat.TemperatureDisplayUnitEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.ThermostatService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** + * A thermostat with heating and cooling controls. + * + * @author Andy Lintner + */ +public interface ThermostatAccessory extends HomekitAccessory { + + /** + * Retrieves the current temperature, in celsius degrees. + * + * @return a future that will contain the temperature. + */ + CompletableFuture getCurrentTemperature(); + + /** + * return the min value for current temperature. overwrite if you want to change the default + * value. + * + * @return min current temperature + */ + default double getMinCurrentTemperature() { + return 0; + } + + /** + * return the max value for current temperature. overwrite if you want to change the default + * value. + * + * @return max current temperature + */ + default double getMaxCurrentTemperature() { + return 100; + } + + /** + * return the min step value for current temperature. overwrite if you want to change the default + * value. + * + * @return min step current temperature + */ + default double getMinStepCurrentTemperature() { + return 0.1; + } + + /** + * Retrieves the target temperature, in celsius degrees. + * + * @return a future that will contain the target temperature. + */ + CompletableFuture getTargetTemperature(); + + /** + * Sets the target temperature. + * + * @param value the target temperature, in celsius degrees. + * @throws Exception when the temperature cannot be changed. + */ + void setTargetTemperature(Double value) throws Exception; + + /** + * return the min value for target temperature. overwrite if you want to change the default value. + * + * @return min target temperature + */ + default double getMinTargetTemperature() { + return 10; + } + + /** + * return the max value for target temperature. overwrite if you want to change the default value. + * + * @return max target temperature + */ + default double getMaxTargetTemperature() { + return 38; + } + + /** + * return the min step value for target temperature. overwrite if you want to change the default + * value. + * + * @return min step target temperature + */ + default double getMinStepTargetTemperature() { + return 0.1; + } + + /** + * Retrieves the current {@link CurrentHeatingCoolingStateEnum} of the thermostat. + * + * @return a future that will contain the mode. + */ + CompletableFuture getCurrentState(); + + /** + * Sets the {@link TargetHeatingCoolingStateEnum} of the thermostat. + * + * @param mode The {@link TargetHeatingCoolingStateEnum} to set. + * @throws Exception when the change cannot be made. + */ + void setTargetState(TargetHeatingCoolingStateEnum mode) throws Exception; + + /** + * Retrieves the pending, but not yet complete, {@link TargetHeatingCoolingStateEnum} of the + * thermostat. + * + * @return a future that will contain the target mode. + */ + CompletableFuture getTargetState(); + + /** + * Retrieves the temperture display units, e.g. C or F. + * + * @return a future that will contain the temperature unit. + */ + CompletableFuture getTemperatureDisplayUnit(); + + /** + * Sets the temperature unit. + * + * @param value the temperature display unit. + * @throws Exception when the temperature cannot be changed. + */ + void setTemperatureDisplayUnit(TemperatureDisplayUnitEnum value) throws Exception; + + /** + * Subscribes to changes in the pending, but not yet complete, {@link + * TargetHeatingCoolingStateEnum} of the thermostat. + * + * @param callback the function to call when the state changes. + */ + void subscribeTargetState(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the target temperature. + * + * @param callback the function to call when the state changes. + */ + void subscribeTargetTemperature(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the temperature display unit. + * + * @param callback the function to call when the uni changes. + */ + void subscribeTemperatureDisplayUnit(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the current temperature. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentTemperature(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the {@link CurrentHeatingCoolingStateEnum} of the thermostat. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the mode of the thermostat. */ + void unsubscribeCurrentState(); + + /** + * Unsubscribes from changes in the pending, but not yet complete, {@link + * TargetHeatingCoolingStateEnum} of the thermostat. + */ + void unsubscribeTargetState(); + + /** Unsubscribes from changes in the current temperature. */ + void unsubscribeCurrentTemperature(); + + /** Unsubscribes from changes in temperature display unit */ + void unsubscribeTemperatureDisplayUnit(); + + /** Unsubscribes from changes in the target temperature. */ + void unsubscribeTargetTemperature(); + + /** + * Valid values for current state. + * + * @return array of valid current states. + */ + default CurrentHeatingCoolingStateEnum[] getCurrentHeatingCoolingStateValidValues() { + return CurrentHeatingCoolingStateEnum.values(); + } + + /** + * Valid values for target state. + * + * @return array of valid targe states. + */ + default TargetHeatingCoolingStateEnum[] getTargetHeatingCoolingStateValidValues() { + return TargetHeatingCoolingStateEnum.values(); + } + + @Override + default Collection getServices() { + return Collections.singleton(new ThermostatService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/Valve.java b/src/main/java/io/github/hapjava/accessories/ValveAccessory.java similarity index 73% rename from src/main/java/io/github/hapjava/accessories/Valve.java rename to src/main/java/io/github/hapjava/accessories/ValveAccessory.java index 8a62f0772..3db17e41f 100644 --- a/src/main/java/io/github/hapjava/accessories/Valve.java +++ b/src/main/java/io/github/hapjava/accessories/ValveAccessory.java @@ -1,10 +1,11 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.properties.ValveType; -import io.github.hapjava.impl.services.ValveService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.InUseEnum; +import io.github.hapjava.characteristics.impl.valve.ValveTypeEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.ValveService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; @@ -14,12 +15,7 @@ * * @author Tim Harper */ -public interface Valve extends HomekitAccessory { - - @Override - default Collection getServices() { - return Collections.singleton(new ValveService(this)); - } +public interface ValveAccessory extends HomekitAccessory { /** * Retrieves the current active state of the valve; Active could mean the valve is open (but not @@ -30,7 +26,7 @@ default Collection getServices() { * * @return a future that will contain the binary state */ - CompletableFuture getValveActive(); + CompletableFuture getValveActive(); /** * Sets the valve active state @@ -39,7 +35,7 @@ default Collection getServices() { * @return a future that completes when the change is made * @throws Exception when the change cannot be made */ - CompletableFuture setValveActive(boolean active) throws Exception; + CompletableFuture setValveActive(ActiveEnum active) throws Exception; /** * Subscribes to changes in the active state of the valve. @@ -59,7 +55,7 @@ default Collection getServices() { * * @return a future that will contain the binary state */ - CompletableFuture getValveInUse(); + CompletableFuture getValveInUse(); /** * Subscribes to changes in the inUse state of the valve. @@ -74,11 +70,9 @@ default Collection getServices() { /** * Retrieves the valve type. * - *

To communicate water is flowing through a valve, inUse should be used. - * - * @return a future that will contain the binary state + * @return a future that will contain the valve type. */ - CompletableFuture getValveType(); + CompletableFuture getValveType(); /** * Subscribes to changes in the valveType state of the valve. @@ -87,6 +81,11 @@ default Collection getServices() { */ void subscribeValveType(HomekitCharacteristicChangeCallback callback); - /** Unsubscribes from changes in the valveType state light. */ + /** Unsubscribes from changes in the valveType state. */ void unsubscribeValveType(); + + @Override + default Collection getServices() { + return Collections.singleton(new ValveService(this)); + } } diff --git a/src/main/java/io/github/hapjava/accessories/ValveWithTimer.java b/src/main/java/io/github/hapjava/accessories/ValveWithTimer.java deleted file mode 100644 index 5ed2ee048..000000000 --- a/src/main/java/io/github/hapjava/accessories/ValveWithTimer.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.hapjava.accessories; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import java.util.concurrent.CompletableFuture; - -/** - * Extends {@link Valve} with timer values. - * - * @author Tim Harper - */ -public interface ValveWithTimer extends Valve { - - /** - * Retrieves the current duration for which the valve will run - * - * @return a future with the value - */ - CompletableFuture getRemainingDuration(); - - /** - * Subscribes to changes in the duration; note it is not necessary to emit a change every second, - * homekit infers the countdown progress clientside. - * - * @param callback the function when the existing duration has been replaced with a new one. - */ - void subscribeRemainingDuration(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes */ - void unsubscribeRemainingDuration(); - - /** - * Retrieves the current set duration for which the valve will be scheduled to run; this is - * usually used as the duration to use when the valve is set to active. - * - * @return a future with the value - */ - CompletableFuture getSetDuration(); - - /** - * Sets the duration for which the valve will be scheduled to run; this is usually used as the - * duration to use when the valve is set to active. - * - *

If the valve is currently running, then Homekit assumes that changing this value affects the - * current remaining duration. - * - * @return a future with the value - */ - CompletableFuture setSetDuration(int value); - - /** - * Subscribes to changes in the set duration - * - * @param callback the function when the value has changed - */ - void subscribeSetDuration(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes */ - void unsubscribeSetDuration(); -} diff --git a/src/main/java/io/github/hapjava/accessories/WindowAccessory.java b/src/main/java/io/github/hapjava/accessories/WindowAccessory.java new file mode 100644 index 000000000..6cc52322b --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/WindowAccessory.java @@ -0,0 +1,78 @@ +package io.github.hapjava.accessories; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.windowcovering.PositionStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.WindowService; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +/** motorized window accessory. */ +public interface WindowAccessory extends HomekitAccessory { + + /** + * Retrieves the position state of the door + * + * @return a future which will contain the door's position state + */ + CompletableFuture getPositionState(); + + /** + * Retrieves the current position of the door + * + * @return a future which will contain the door's current position + */ + CompletableFuture getCurrentPosition(); + + /** + * Retrieves the target position of the door + * + * @return a future which will contain the door's target position + */ + CompletableFuture getTargetPosition(); + + /** + * Sets the targeted state of the door. + * + * @param position the targeted position + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setTargetPosition(Integer position) throws Exception; + + /** + * Subscribes to changes in the door's position state + * + * @param callback the function to call when the state changes + */ + void subscribePositionState(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the door's current position + * + * @param callback the function to call when the current position changes + */ + void subscribeCurrentPosition(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the door's target position + * + * @param callback the function to call when the target position changes + */ + void subscribeTargetPosition(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the door's state */ + void unsubscribePositionState(); + + /** Unsubscribes from changes in the door's current position */ + void unsubscribeCurrentPosition(); + + /** Unsubscribes from changes in the door's target position */ + void unsubscribeTargetPosition(); + + @Override + default Collection getServices() { + return Collections.singleton(new WindowService(this)); + } +} diff --git a/src/main/java/io/github/hapjava/accessories/WindowCovering.java b/src/main/java/io/github/hapjava/accessories/WindowCovering.java deleted file mode 100644 index afabbf097..000000000 --- a/src/main/java/io/github/hapjava/accessories/WindowCovering.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.accessories; - -/** - * A window covering, like blinds, which can be remotely controlled. - * - * @author Andy Lintner - * @deprecated In 1.2.x, this interface will become replaced with BasicWindowCovering. Update your - * code to use that interface for now, and include the HoldPositionWindowCovering and - * ObstructionDetectedWindowCovering interfaces respectively - */ -@Deprecated -public interface WindowCovering - extends BasicWindowCovering, HoldPositionWindowCovering, ObstructionDetectedWindowCovering { - /* - * TODO - 1.2.x: Replace this interface with BasicWindowCovering */ -} diff --git a/src/main/java/io/github/hapjava/accessories/BasicWindowCovering.java b/src/main/java/io/github/hapjava/accessories/WindowCoveringAccessory.java similarity index 81% rename from src/main/java/io/github/hapjava/accessories/BasicWindowCovering.java rename to src/main/java/io/github/hapjava/accessories/WindowCoveringAccessory.java index 7d58b2b2d..1b618d66f 100644 --- a/src/main/java/io/github/hapjava/accessories/BasicWindowCovering.java +++ b/src/main/java/io/github/hapjava/accessories/WindowCoveringAccessory.java @@ -1,16 +1,15 @@ package io.github.hapjava.accessories; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.properties.WindowCoveringPositionState; -import io.github.hapjava.impl.services.WindowCoveringService; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.windowcovering.PositionStateEnum; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.WindowCoveringService; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; -public interface BasicWindowCovering extends HomekitAccessory { - +/** A window covering, like blinds, which can be remotely controlled. */ +public interface WindowCoveringAccessory extends HomekitAccessory { /** * Retrieves the current position * @@ -30,7 +29,7 @@ public interface BasicWindowCovering extends HomekitAccessory { * * @return a future that will contain the current state */ - CompletableFuture getPositionState(); + CompletableFuture getPositionState(); /** * Sets the target position diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithAccessoryFlags.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithAccessoryFlags.java new file mode 100644 index 000000000..27d9c2e18 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithAccessoryFlags.java @@ -0,0 +1,26 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.accessoryinformation.AccessoryFlagsEnum; +import java.util.concurrent.CompletableFuture; + +/** Accessory with accessory flags, which indicates that additional setup is required */ +public interface AccessoryWithAccessoryFlags { + + /** + * When set indicates accessory requires additional setup. + * + * @return a future that will contain the accessory flags + */ + CompletableFuture getAccessoryFlags(); + + /** + * Subscribes to changes in accessory flags + * + * @param callback the function to call when the accessory flags changes. + */ + void subscribeAccessoryFlags(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the accessory flags . */ + void unsubscribeAccessoryFlags(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithActive.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithActive.java new file mode 100644 index 000000000..4ad11be63 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithActive.java @@ -0,0 +1,38 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with active characteristic {@link + * io.github.hapjava.characteristics.impl.common.ActiveCharacteristic}. + */ +public interface AccessoryWithActive { + + /** + * Retrieves the active state (see {@link + * io.github.hapjava.characteristics.impl.common.ActiveEnum} for supported values). + * + * @return a future that will contain the active state + */ + CompletableFuture getActive(); + + /** + * Set the active state (see {@link ActiveEnum} for supported values). + * + * @param active active state + * @return a future that completes when the change is made + */ + CompletableFuture setActive(ActiveEnum active); + + /** + * Subscribes to changes in the active state. + * + * @param callback the function to call when the active state changes. + */ + void subscribeActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the active state. */ + void unsubscribeActive(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithAirPlayEnable.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithAirPlayEnable.java new file mode 100644 index 000000000..76b90b43f --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithAirPlayEnable.java @@ -0,0 +1,37 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with AirPlay enable characteristic {@link + * io.github.hapjava.characteristics.impl.common.AirPlayEnableCharacteristic}. + */ +public interface AccessoryWithAirPlayEnable { + + /** + * Retrieves the AirPlay enable state + * + * @return a future that will contain the AirPlay enable state. + */ + CompletableFuture getAirPlayEnable(); + + /** + * Sets the AirPlay enable state + * + * @param state AirPlay enable state + * @return a future that completes when the AirPlay enable is changed + * @throws Exception when the AirPlay enable cannot be set + */ + CompletableFuture setAirPlayEnable(Integer state) throws Exception; + + /** + * Subscribes to changes in the AirPlay enable state. + * + * @param callback the function to call when the AirPlay enable state changes. + */ + void subscribeAirPlayEnable(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the AirPlay enable state. */ + void unsubscribeAirPlayEnable(); +} diff --git a/src/main/java/io/github/hapjava/accessories/DimmableLightbulb.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithBrightness.java similarity index 81% rename from src/main/java/io/github/hapjava/accessories/DimmableLightbulb.java rename to src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithBrightness.java index 2eea5abdb..4fa4557c2 100644 --- a/src/main/java/io/github/hapjava/accessories/DimmableLightbulb.java +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithBrightness.java @@ -1,14 +1,14 @@ -package io.github.hapjava.accessories; +package io.github.hapjava.accessories.optionalcharacteristic; -import io.github.hapjava.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; import java.util.concurrent.CompletableFuture; /** - * Extends {@link Lightbulb} with brightness values. + * Accessory with brightness values. * * @author Andy Lintner */ -public interface DimmableLightbulb extends Lightbulb { +public interface AccessoryWithBrightness { /** * Retrieves the current brightness of the light diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCarbonDioxideLevel.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCarbonDioxideLevel.java new file mode 100644 index 000000000..bd143b22f --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCarbonDioxideLevel.java @@ -0,0 +1,104 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.carbondioxidesensor.CarbonDioxideLevelCharacteristic; +import io.github.hapjava.characteristics.impl.carbondioxidesensor.CarbonDioxidePeakLevelCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with carbon dioxide level and peak level characteristic. */ +public interface AccessoryWithCarbonDioxideLevel { + + /** + * Retrieves the carbon dioxide peak level + * + * @return a future that will contain the carbon dioxide level as a value between 0 and 100000 + */ + CompletableFuture getCarbonDioxidePeakLevel(); + + /** + * Retrieves the carbon dioxide level + * + * @return a future that will contain the carbon dioxide level as a value between 0 and 100000 + */ + CompletableFuture getCarbonDioxideLevel(); + + /** + * return the min value for carbon dioxide level. overwrite if you want to change the default + * value. + * + * @return min carbon dioxide level + */ + default double getMinCarbonDioxideLevel() { + return CarbonDioxideLevelCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for carbon dioxide level. overwrite if you want to change the default + * value. + * + * @return max carbon dioxide level + */ + default double getMaxCarbonDioxideLevel() { + return CarbonDioxideLevelCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for carbon dioxide level. overwrite if you want to change the default + * value. + * + * @return min step carbon dioxide level + */ + default double getMinStepCarbonDioxideLevel() { + return CarbonDioxideLevelCharacteristic.DEFAULT_STEP; + } + + /** + * return the min value for carbon dioxide peak level. overwrite if you want to change the default + * value. + * + * @return min carbon dioxide peak level + */ + default double getMinCarbonDioxidePeakLevel() { + return CarbonDioxidePeakLevelCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for carbon dioxide peak level. overwrite if you want to change the default + * value. + * + * @return max carbon dioxide peak level + */ + default double getMaxCarbonDioxidePeakLevel() { + return CarbonDioxidePeakLevelCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for carbon dioxide peak level. overwrite if you want to change the + * default value. + * + * @return min step carbon dioxide peak level + */ + default double getMinStepCarbonDioxidePeakLevel() { + return CarbonDioxidePeakLevelCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in the carbon dioxide level. + * + * @param callback the function to call when the state changes. + */ + void subscribeCarbonDioxideLevel(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the carbon dioxide level. */ + void unsubscribeCarbonDioxideLevel(); + + /** + * Subscribes to changes in the carbon dioxide level. + * + * @param callback the function to call when the state changes. + */ + void subscribeCarbonDioxidePeakLevel(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the carbon dioxide level. */ + void unsubscribeCarbonDioxidePeakLevel(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCarbonMonoxideLevel.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCarbonMonoxideLevel.java new file mode 100644 index 000000000..cbccd9647 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCarbonMonoxideLevel.java @@ -0,0 +1,104 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.carbonmonoxidesensor.CarbonMonoxideLevelCharacteristic; +import io.github.hapjava.characteristics.impl.carbonmonoxidesensor.CarbonMonoxidePeakLevelCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with carbon monoxide level and peak level characteristic. */ +public interface AccessoryWithCarbonMonoxideLevel { + + /** + * Retrieves the carbon monoxide peak level + * + * @return a future that will contain the carbon monoxide level as a value between 0 and 100000 + */ + CompletableFuture getCarbonMonoxidePeakLevel(); + + /** + * Retrieves the carbon monoxide level + * + * @return a future that will contain the carbon monoxide level as a value between 0 and 100000 + */ + CompletableFuture getCarbonMonoxideLevel(); + + /** + * return the min value for carbon monoxide level. overwrite if you want to change the default + * value. + * + * @return min carbon monoxide level + */ + default double getMinCarbonMonoxideLevel() { + return CarbonMonoxideLevelCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for carbon monoxide level. overwrite if you want to change the default + * value. + * + * @return max carbon monoxide level + */ + default double getMaxCarbonMonoxideLevel() { + return CarbonMonoxideLevelCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for carbon monoxide level. overwrite if you want to change the + * default value. + * + * @return min step carbon monoxide level + */ + default double getMinStepCarbonMonoxideLevel() { + return CarbonMonoxideLevelCharacteristic.DEFAULT_STEP; + } + + /** + * return the min value for carbon monoxide peak level. overwrite if you want to change the + * default value. + * + * @return min carbon monoxide peak level + */ + default double getMinCarbonMonoxidePeakLevel() { + return CarbonMonoxidePeakLevelCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for carbon monoxide peak level. overwrite if you want to change the + * default value. + * + * @return max carbon monoxide peak level + */ + default double getMaxCarbonMonoxidePeakLevel() { + return CarbonMonoxidePeakLevelCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for carbon monoxide peak level. overwrite if you want to change the + * default value. + * + * @return min step carbon monoxide peak level + */ + default double getMinStepCarbonMonoxidePeakLevel() { + return CarbonMonoxidePeakLevelCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in the carbon monoxide level. + * + * @param callback the function to call when the state changes. + */ + void subscribeCarbonMonoxideLevel(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the carbon monoxide level. */ + void unsubscribeCarbonMonoxideLevel(); + + /** + * Subscribes to changes in the carbon monoxide level. + * + * @param callback the function to call when the state changes. + */ + void subscribeCarbonMonoxidePeakLevel(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the carbon monoxide level. */ + void unsubscribeCarbonMonoxidePeakLevel(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithClosedCaptions.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithClosedCaptions.java new file mode 100644 index 000000000..c13da3289 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithClosedCaptions.java @@ -0,0 +1,37 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.television.ClosedCaptionsEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with closed captions characteristic {@link + * io.github.hapjava.characteristics.impl.television.ClosedCaptionsCharacteristic}. + */ +public interface AccessoryWithClosedCaptions { + + /** + * Retrieves the closed captions state (see {@link ClosedCaptionsEnum} for supported values). + * + * @return a future that will contain the closed captions + */ + CompletableFuture getClosedCaptions(); + + /** + * Set the closed captions state (see {@link ClosedCaptionsEnum} for supported values). + * + * @param closedCaptions closed captions + * @return a future that completes when the change is made + */ + CompletableFuture setClosedCaptions(ClosedCaptionsEnum closedCaptions); + + /** + * Subscribes to changes in the closed captions. + * + * @param callback the function to call when the closed captions changes. + */ + void subscribeClosedCaptions(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the closed captions. */ + void unsubscribeClosedCaptions(); +} diff --git a/src/main/java/io/github/hapjava/accessories/ColorfulLightbulb.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithColor.java similarity index 85% rename from src/main/java/io/github/hapjava/accessories/ColorfulLightbulb.java rename to src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithColor.java index 32ed8d294..e8f2dd66a 100644 --- a/src/main/java/io/github/hapjava/accessories/ColorfulLightbulb.java +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithColor.java @@ -1,15 +1,14 @@ -package io.github.hapjava.accessories; +package io.github.hapjava.accessories.optionalcharacteristic; -import io.github.hapjava.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; import java.util.concurrent.CompletableFuture; /** - * Extends {@link Lightbulb} with color settings. This will usually be implemented along with {@link - * DimmableLightbulb}, but not necessarily so. + * Accessory with Color * * @author Andy Lintner */ -public interface ColorfulLightbulb extends Lightbulb { +public interface AccessoryWithColor { /** * Retrieves the current hue of the light. diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithColorTemperature.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithColorTemperature.java new file mode 100644 index 000000000..ecf74ba63 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithColorTemperature.java @@ -0,0 +1,53 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.lightbulb.ColorTemperatureCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with color temperature. */ +public interface AccessoryWithColorTemperature { + + /** + * Retrieves the color temperature + * + * @return a future that will contain the brightness, expressed as an integer between 0 and 100. + */ + CompletableFuture getColorTemperature(); + + /** + * Sets the color temperature + * + * @param value the brightness, on a scale of 0 to 100, to set + * @return a future that completes when the brightness is changed + * @throws Exception when the brightness cannot be set + */ + CompletableFuture setColorTemperature(Integer value) throws Exception; + + /** + * return the min value for color temperature. overwrite if you want to change the default value. + * + * @return min color temperature + */ + default int getMinColorTemperature() { + return ColorTemperatureCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for color temperature. overwrite if you want to change the default value. + * + * @return max color temperature + */ + default int getMaxColorTemperature() { + return ColorTemperatureCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * Subscribes to changes in color temperature. + * + * @param callback the function to call when the color temperature changes. + */ + void subscribeColorTemperature(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the color temperature. */ + void unsubscribeColorTemperature(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithConfiguredName.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithConfiguredName.java new file mode 100644 index 000000000..0c9528130 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithConfiguredName.java @@ -0,0 +1,34 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with configured name. */ +public interface AccessoryWithConfiguredName { + + /** + * Retrieves configured name. + * + * @return configured name + */ + CompletableFuture getConfiguredName(); + + /** + * Sets the configured name + * + * @param name configured name + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setConfiguredName(String name) throws Exception; + + /** + * Subscribes to changes in configured name. + * + * @param callback the function to call when the configureed name changes. + */ + void subscribeConfiguredName(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the configured name state. */ + void unsubscribeConfiguredName(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCoolingThresholdTemperature.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCoolingThresholdTemperature.java new file mode 100644 index 000000000..c42398a10 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCoolingThresholdTemperature.java @@ -0,0 +1,63 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with cooling threshold temperature. */ +public interface AccessoryWithCoolingThresholdTemperature { + + /** + * Retrieves the temperature above which the thermostat should begin cooling. + * + * @return a future that will contain the threshold temperature, in celsius degrees. + */ + CompletableFuture getCoolingThresholdTemperature(); + + /** + * Sets the temperature above which the thermostat should begin cooling. + * + * @param value the threshold temperature, in celsius degrees. + * @throws Exception when the threshold temperature cannot be changed. + */ + void setCoolingThresholdTemperature(Double value) throws Exception; + + /** + * return the min value for cooling threshold temperature. overwrite if you want to change the + * default value. + * + * @return min threshold temperature + */ + default double getMinCoolingThresholdTemperature() { + return 10; + } + + /** + * return the max value for cooling threshold temperature. overwrite if you want to change the + * default value. + * + * @return max threshold temperature + */ + default double getMaxCoolingThresholdTemperature() { + return 35; + } + + /** + * return the min step value for cooling threshold temperature. overwrite if you want to change + * the default value. + * + * @return step for threshold temperature + */ + default double getStepCoolingThresholdTemperature() { + return 0.1; + } + + /** + * Subscribes to changes in the cooling threshold. + * + * @param callback the function to call when the state changes. + */ + void subscribeCoolingThresholdTemperature(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the cooling threshold. */ + void unsubscribeCoolingThresholdTemperature(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentHorizontalTilting.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentHorizontalTilting.java new file mode 100644 index 000000000..b5ce298bf --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentHorizontalTilting.java @@ -0,0 +1,29 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with current horizontal tilting characteristic. + * + * @author Andy Lintner + */ +public interface AccessoryWithCurrentHorizontalTilting { + + /** + * Retrieves the current horizontal tilt angle + * + * @return a future that will contain the position as a value between -90 and 90 + */ + CompletableFuture getCurrentHorizontalTiltAngle(); + + /** + * Subscribes to changes in the current horizontal tilt angle. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentHorizontalTiltAngle(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current horizontal tilt angle */ + void unsubscribeCurrentHorizontalTiltAngle(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentMediaState.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentMediaState.java new file mode 100644 index 000000000..22350d9b4 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentMediaState.java @@ -0,0 +1,30 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.television.CurrentMediaStateEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with current media state characteristic {@link + * io.github.hapjava.characteristics.impl.television.CurrentMediaStateCharacteristic}. + */ +public interface AccessoryWithCurrentMediaState { + + /** + * Retrieves the current media state (see {@link + * io.github.hapjava.characteristics.impl.television.CurrentMediaStateEnum} for supported values). + * + * @return a future that will contain the current media state + */ + CompletableFuture getCurrentMediaState(); + + /** + * Subscribes to changes in the current media state. + * + * @param callback the function to call when the current media state changes. + */ + void subscribeCurrentMediaState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current media state. */ + void unsubscribeCurrentMediaState(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentRelativeHumidity.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentRelativeHumidity.java new file mode 100644 index 000000000..562e42649 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentRelativeHumidity.java @@ -0,0 +1,25 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** accessory with current relative humidity. */ +public interface AccessoryWithCurrentRelativeHumidity { + + /** + * Retrieves the current relative humidity. + * + * @return a future that will contain the current relative humidity. + */ + CompletableFuture getCurrentRelativeHumidity(); + + /** + * Subscribes to changes in current relative humidity. + * + * @param callback the function to call when the current relative humidity changes. + */ + void subscribeCurrentRelativeHumidity(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current relative humidity. */ + void unsubscribeCurrentRelativeHumidity(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentTilting.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentTilting.java new file mode 100644 index 000000000..54a558491 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentTilting.java @@ -0,0 +1,25 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with current tilting characteristic. */ +public interface AccessoryWithCurrentTilting { + + /** + * Retrieves the current tilt angle + * + * @return a future that will contain the position as a value between -90 and 90 + */ + CompletableFuture getCurrentTiltAngle(); + + /** + * Subscribes to changes in the current tilt angle. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentTiltAngle(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current tilt angle */ + void unsubscribeCurrentTiltAngle(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentVerticalTilting.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentVerticalTilting.java new file mode 100644 index 000000000..3b996c925 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithCurrentVerticalTilting.java @@ -0,0 +1,24 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with current vertical tilting characteristic. */ +public interface AccessoryWithCurrentVerticalTilting { + /** + * Retrieves the current vertical tilt angle + * + * @return a future that will contain the position as a value between -90 and 90 + */ + CompletableFuture getCurrentVerticalTiltAngle(); + + /** + * Subscribes to changes in the current vertical tilt angle. + * + * @param callback the function to call when the state changes. + */ + void subscribeCurrentVerticalTiltAngle(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current vertical tilt angle */ + void unsubscribeCurrentVerticalTiltAngle(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithDuration.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithDuration.java new file mode 100644 index 000000000..a5cebf97c --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithDuration.java @@ -0,0 +1,52 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.valve.SetDurationCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with duration characteristic. */ +public interface AccessoryWithDuration { + + /** + * Retrieves the current set duration; + * + * @return a future with the value + */ + CompletableFuture getSetDuration(); + + /** + * return the min value for duration. overwrite if you want to change the default value. + * + * @return min remaining duration + */ + default int getMinDuration() { + return SetDurationCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for duration. overwrite if you want to change the default value. + * + * @return max duration + */ + default int getMaxDuration() { + return SetDurationCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * Sets the duration for which the service should run. + * + * @param value duration in seconds + * @return a future that completes when the change is made + */ + CompletableFuture setSetDuration(int value); + + /** + * Subscribes to changes in the set duration + * + * @param callback the function when the duration has changed + */ + void subscribeSetDuration(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeSetDuration(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithFanState.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithFanState.java new file mode 100644 index 000000000..75be61e8c --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithFanState.java @@ -0,0 +1,56 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.fan.CurrentFanStateEnum; +import io.github.hapjava.characteristics.impl.fan.TargetFanStateEnum; +import java.util.concurrent.CompletableFuture; + +/** + * An accessory with current and target fan states. + * + * @author Andy Lintner + */ +public interface AccessoryWithFanState { + + /** + * Retrieves the current state of the fan (INACTIVE, IDLE, BLOWING AIR). + * + * @return a future that will contain the state + */ + CompletableFuture getCurrentFanState(); + + /** + * Retrieves the target state of the fan (MANUAL, AUTO). + * + * @return a future that will contain the state + */ + CompletableFuture getTargetFanState(); + + /** + * Set the target state of the fan (MANUAL, AUTO). + * + * @param targetState target state + * @return a future that completes when the change is made + */ + CompletableFuture setTargetFanState(TargetFanStateEnum targetState); + + /** + * Subscribes to changes in the current fan state. + * + * @param callback the function to call when the direction changes. + */ + void subscribeCurrentFanState(HomekitCharacteristicChangeCallback callback); + + /** + * Subscribes to changes in the target fan state. + * + * @param callback the function to call when the direction changes. + */ + void subscribeTargetFanState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current state of the fan. */ + void unsubscribeCurrentFanState(); + + /** Unsubscribes from changes in the target state of the fan. */ + void unsubscribeTargetFanState(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithFilterLifeLevel.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithFilterLifeLevel.java new file mode 100644 index 000000000..2b94d4ec9 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithFilterLifeLevel.java @@ -0,0 +1,25 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with filter level characteristics */ +public interface AccessoryWithFilterLifeLevel { + + /** + * what's the filter life level, percentage wise + * + * @return filter life level + */ + CompletableFuture getFilterLifeLevel(); + + /** + * Subscribes to changes in the filter life level. + * + * @param callback the function to call when the level changes. + */ + void subscribeFilterLifeLevel(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the current filter life level. */ + void unsubscribeFilterLifeLevel(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHardwareRevision.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHardwareRevision.java new file mode 100644 index 000000000..866921817 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHardwareRevision.java @@ -0,0 +1,14 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import java.util.concurrent.CompletableFuture; + +/** Accessory with hardware revision. */ +public interface AccessoryWithHardwareRevision { + + /** + * Returns a hardware revision to display in iOS. + * + * @return the hardware revision, or null. + */ + CompletableFuture getHardwareRevision(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHeatingThresholdTemperature.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHeatingThresholdTemperature.java new file mode 100644 index 000000000..02cb3f819 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHeatingThresholdTemperature.java @@ -0,0 +1,62 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +public interface AccessoryWithHeatingThresholdTemperature { + + /** + * Retrieves the temperature below which the thermostat should begin heating. + * + * @return a future that will contain the threshold temperature, in celsius degrees. + */ + CompletableFuture getHeatingThresholdTemperature(); + + /** + * Sets the temperature below which the thermostat should begin heating. + * + * @param value the threshold temperature, in celsius degrees. + * @throws Exception when the threshold temperature cannot be changed. + */ + void setHeatingThresholdTemperature(Double value) throws Exception; + + /** + * return the min value for heating threshold temperature. overwrite if you want to change the + * default value. + * + * @return min threshold temperature + */ + default double getMinHeatingThresholdTemperature() { + return 0; + } + + /** + * return the max value for heating threshold temperature. overwrite if you want to change the + * default value. + * + * @return max threshold temperature + */ + default double getMaxHeatingThresholdTemperature() { + return 25; + } + + /** + * return the min step value for heating threshold temperature. overwrite if you want to change + * the default value. + * + * @return step for threshold temperature + */ + default double getStepHeatingThresholdTemperature() { + return 0.1; + } + + /** + * Subscribes to changes in the heating threshold. + * + * @param callback the function to call when the state changes. + */ + void subscribeHeatingThresholdTemperature(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the heating threshold. */ + void unsubscribeHeatingThresholdTemperature(); +} diff --git a/src/main/java/io/github/hapjava/accessories/HoldPositionWindowCovering.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHoldPosition.java similarity index 71% rename from src/main/java/io/github/hapjava/accessories/HoldPositionWindowCovering.java rename to src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHoldPosition.java index f5cfe0c80..b1d0d65fa 100644 --- a/src/main/java/io/github/hapjava/accessories/HoldPositionWindowCovering.java +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHoldPosition.java @@ -1,8 +1,9 @@ -package io.github.hapjava.accessories; +package io.github.hapjava.accessories.optionalcharacteristic; import java.util.concurrent.CompletableFuture; -public interface HoldPositionWindowCovering { +/** Accessory with hold position */ +public interface AccessoryWithHoldPosition { /** * Sets the hold position state diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHumidityDehumidifierThreshold.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHumidityDehumidifierThreshold.java new file mode 100644 index 000000000..4dff49352 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHumidityDehumidifierThreshold.java @@ -0,0 +1,33 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Dehumidifier with humidity threshold. */ +public interface AccessoryWithHumidityDehumidifierThreshold { + + /** + * Retrieves the humidity threshold. + * + * @return a future that will contain the humidity threshold. + */ + CompletableFuture getHumidityThreshold(); + + /** + * Sets the humidity threshold above which the dehumidifier should be turned on. + * + * @param value the humidity threshold, in celsius degrees. + * @throws Exception when the threshold cannot be changed. + */ + void setHumidityThreshold(Double value) throws Exception; + + /** + * Subscribes to changes in the humidity threshold. + * + * @param callback the function to call when the state changes. + */ + void subscribeHumidityThreshold(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the humidity threshold. */ + void unsubscribeHumidityThreshold(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHumidityHumidifierThreshold.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHumidityHumidifierThreshold.java new file mode 100644 index 000000000..f783a3039 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithHumidityHumidifierThreshold.java @@ -0,0 +1,33 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Humidifier with humidity threshold. */ +public interface AccessoryWithHumidityHumidifierThreshold { + + /** + * Retrieves the humidity threshold. + * + * @return a future that will contain the humidity threshold. + */ + CompletableFuture getHumidityThreshold(); + + /** + * Sets the humidity threshold above which the humidifier should be turned on. + * + * @param value the humidity threshold, in celsius degrees. + * @throws Exception when the threshold cannot be changed. + */ + void setHumidityThreshold(Double value) throws Exception; + + /** + * Subscribes to changes in the humidity threshold. + * + * @param callback the function to call when the state changes. + */ + void subscribeHumidityThreshold(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the humidity threshold. */ + void unsubscribeHumidityThreshold(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithIdentifier.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithIdentifier.java new file mode 100644 index 000000000..b181d4d99 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithIdentifier.java @@ -0,0 +1,17 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with identifier characteristic {@link + * io.github.hapjava.characteristics.impl.common.IdentifierCharacteristic}. + */ +public interface AccessoryWithIdentifier { + + /** + * Retrieves the identifier of service. + * + * @return a future with the identifier + */ + CompletableFuture getIdentifier(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithInputDeviceType.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithInputDeviceType.java new file mode 100644 index 000000000..fca5f5df1 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithInputDeviceType.java @@ -0,0 +1,29 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.inputsource.InputDeviceTypeEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with input devices, e.g. television. {@link + * io.github.hapjava.characteristics.impl.inputsource.InputDeviceTypeCharacteristic} + */ +public interface AccessoryWithInputDeviceType { + + /** + * Retrieves the input device type. See {@link InputDeviceTypeEnum} for supported values. + * + * @return a future with the value + */ + CompletableFuture getInputDeviceType(); + + /** + * Subscribes to changes in input device type. + * + * @param callback the function when the input device type changes + */ + void subscribeInputDeviceType(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeInputDeviceType(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithIsConfigured.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithIsConfigured.java new file mode 100644 index 000000000..017fdce5f --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithIsConfigured.java @@ -0,0 +1,38 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.IsConfiguredEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with isConfigured characteristics. This characteristic describes if the service is + * configured for use. For example, all of the valves in an irrigation system may not be configured + * depending on physical wire connection. + */ +public interface AccessoryWithIsConfigured { + + /** + * isConfigured state + * + * @return a future that will contain the isConfigured state + */ + CompletableFuture getIsConfigured(); + + /** + * Set the isConfigured (NOT_CONFIGURED, CONFIGURED). + * + * @param isConfigured isConfigured state + * @return a future that completes when the change is made + */ + CompletableFuture setIsConfigured(IsConfiguredEnum isConfigured); + + /** + * Subscribes to changes in isConfigured state + * + * @param callback the function to call when the isConfigured state changes. + */ + void subscribeIsConfigured(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the isConfigured state. */ + void unsubscribeIsConfigured(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithLockCurrentState.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithLockCurrentState.java new file mode 100644 index 000000000..f3f9782ca --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithLockCurrentState.java @@ -0,0 +1,26 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.lock.LockCurrentStateEnum; +import java.util.concurrent.CompletableFuture; + +/** Accessory with current lock state. */ +public interface AccessoryWithLockCurrentState { + + /** + * Retrieves the lock states. The current state of the physical security mechanism (e.g. deadbolt) + * + * @return a future with the value + */ + CompletableFuture getLockCurrentState(); + + /** + * Subscribes to changes in lock current state. + * + * @param callback the function when the lock current state changes + */ + void subscribeLockCurrentState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeLockCurrentState(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithLockTargetState.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithLockTargetState.java new file mode 100644 index 000000000..41ef0d3ed --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithLockTargetState.java @@ -0,0 +1,35 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.lock.LockTargetStateEnum; +import java.util.concurrent.CompletableFuture; + +/** Accessory with lock target state. */ +public interface AccessoryWithLockTargetState { + + /** + * Retrieves the lock states. The target state of the physical security mechanism (e.g. deadbolt) + * + * @return a future with the value + */ + CompletableFuture getLockTargetState(); + + /** + * Sets the lock target state + * + * @param state the target state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setLockTargetState(LockTargetStateEnum state) throws Exception; + + /** + * Subscribes to changes in lock target state. + * + * @param callback the function when the lock target state changes + */ + void subscribeLockTargetState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeLockTargetState(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithMute.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithMute.java new file mode 100644 index 000000000..a0bb08579 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithMute.java @@ -0,0 +1,37 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with mute characteristic {@link + * io.github.hapjava.characteristics.impl.audio.MuteCharacteristic}. + */ +public interface AccessoryWithMute { + + /** + * Retrieves mute status. + * + * @return true if accessory is muted + */ + CompletableFuture isMuted(); + + /** + * Sets the mute status + * + * @param mute true if accessory should be muted + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setMute(boolean mute) throws Exception; + + /** + * Subscribes to changes in mute state. + * + * @param callback the function to call when the state changes. + */ + void subscribeMuteState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the mute state. */ + void unsubscribeMuteState(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithName.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithName.java new file mode 100644 index 000000000..626429124 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithName.java @@ -0,0 +1,14 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import java.util.concurrent.CompletableFuture; + +/** Accessory with name. */ +public interface AccessoryWithName { + + /** + * Retrieves the name of service. + * + * @return a future with the name + */ + CompletableFuture getName(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithNitrogenDioxideDensity.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithNitrogenDioxideDensity.java new file mode 100644 index 000000000..6aead4f98 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithNitrogenDioxideDensity.java @@ -0,0 +1,56 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airquality.NitrogenDioxideDensityCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with nitrogen dioxide density characteristic. */ +public interface AccessoryWithNitrogenDioxideDensity { + + /** + * Retrieves the nitrogen dioxide density. + * + * @return a future with the nitrogen dioxide density + */ + CompletableFuture getNitrogenDioxideDensity(); + + /** + * return the min value for nitrogen dioxide density. overwrite if you want to change the default + * value. + * + * @return min nitrogen dioxide density + */ + default double getMinNitrogenDioxideDensity() { + return NitrogenDioxideDensityCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for nitrogen dioxide density. overwrite if you want to change the default + * value. + * + * @return max nitrogen dioxide density + */ + default double getMaxNitrogenDioxideDensity() { + return NitrogenDioxideDensityCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for nitrogen dioxide density. overwrite if you want to change the + * default value. + * + * @return min step nitrogen dioxide density + */ + default double getMinStepNitrogenDioxideDensity() { + return NitrogenDioxideDensityCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in nitrogen dioxide density. + * + * @param callback the function when nitrogen dioxide density changes + */ + void subscribeNitrogenDioxideDensity(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeNitrogenDioxideDensity(); +} diff --git a/src/main/java/io/github/hapjava/accessories/ObstructionDetectedWindowCovering.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithObstructionDetection.java similarity index 66% rename from src/main/java/io/github/hapjava/accessories/ObstructionDetectedWindowCovering.java rename to src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithObstructionDetection.java index 6dea4ec63..859379cd0 100644 --- a/src/main/java/io/github/hapjava/accessories/ObstructionDetectedWindowCovering.java +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithObstructionDetection.java @@ -1,12 +1,13 @@ -package io.github.hapjava.accessories; +package io.github.hapjava.accessories.optionalcharacteristic; -import io.github.hapjava.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; import java.util.concurrent.CompletableFuture; -public interface ObstructionDetectedWindowCovering { +/** Accessory with hold position */ +public interface AccessoryWithObstructionDetection { /** - * Retrieves an indication that the window covering is obstructed from moving + * Retrieves an indication obstructed is detected * * @return a future that will contain a boolean indicating whether an obstruction is present */ diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithOzoneDensity.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithOzoneDensity.java new file mode 100644 index 000000000..efba2a49f --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithOzoneDensity.java @@ -0,0 +1,53 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airquality.OzoneDensityCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with Ozone Density characteristic. */ +public interface AccessoryWithOzoneDensity { + + /** + * Retrieves the ozone density. + * + * @return a future with the ozone density + */ + CompletableFuture getOzoneDensity(); + + /** + * return the min value for ozone density. overwrite if you want to change the default value. + * + * @return min ozone density + */ + default double getMinOzoneDensity() { + return OzoneDensityCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for ozone density. overwrite if you want to change the default value. + * + * @return max ozone density + */ + default double getMaxOzoneDensity() { + return OzoneDensityCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for ozone density. overwrite if you want to change the default value. + * + * @return min step ozone density + */ + default double getMinStepOzoneDensity() { + return OzoneDensityCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in ozone density. + * + * @param callback the function when ozone density changes + */ + void subscribeOzoneDensity(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeOzoneDensity(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPM10Density.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPM10Density.java new file mode 100644 index 000000000..2ae3cded0 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPM10Density.java @@ -0,0 +1,53 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airquality.PM10DensityCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with PM10 Density characteristic. */ +public interface AccessoryWithPM10Density { + + /** + * Retrieves the PM10 density. + * + * @return a future with the PM10 density + */ + CompletableFuture getPM10Density(); + + /** + * return the min value for PM10 density. overwrite if you want to change the default value. + * + * @return min PM10 density + */ + default double getMinPM10Density() { + return PM10DensityCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for PM10 density. overwrite if you want to change the default value. + * + * @return max PM10 density + */ + default double getMaxPM10Density() { + return PM10DensityCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for PM10 density. overwrite if you want to change the default value. + * + * @return min step PM10 density + */ + default double getMinStepPM10Density() { + return PM10DensityCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in PM10 density. + * + * @param callback the function when PM10 density changes + */ + void subscribePM10Density(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribePM10Density(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPM25Density.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPM25Density.java new file mode 100644 index 000000000..02488f52d --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPM25Density.java @@ -0,0 +1,53 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airquality.PM25DensityCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with PM25 Density characteristic. */ +public interface AccessoryWithPM25Density { + + /** + * Retrieves the PM25 density. + * + * @return a future with the PM25 density + */ + CompletableFuture getPM25Density(); + + /** + * return the min value for PM25 density. overwrite if you want to change the default value. + * + * @return min PM25 density + */ + default double getMinPM25Density() { + return PM25DensityCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for PM25 density. overwrite if you want to change the default value. + * + * @return max PM25 density + */ + default double getMaxPM25Density() { + return PM25DensityCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for PM25 density. overwrite if you want to change the default value. + * + * @return min step PM25 density + */ + default double getMinStepPM25Density() { + return PM25DensityCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in PM25 density. + * + * @param callback the function when PM25 density changes + */ + void subscribePM25Density(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribePM25Density(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPhysicalControlsLock.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPhysicalControlsLock.java new file mode 100644 index 000000000..2e1e3cd87 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPhysicalControlsLock.java @@ -0,0 +1,34 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.fan.LockPhysicalControlsEnum; +import java.util.concurrent.CompletableFuture; + +/** Accessory with physical controls which can be locked, e.g. child lock */ +public interface AccessoryWithPhysicalControlsLock { + + /** + * OPTIONAL: Retrieves the lock controls. + * + * @return a future that will contain the lock controls + */ + CompletableFuture getLockControls(); + + /** + * Set the lock controls (DISABLED, ENABLED). + * + * @param lockControls lock controls mode + * @return a future that completes when the change is made + */ + CompletableFuture setLockControls(LockPhysicalControlsEnum lockControls); + + /** + * Subscribes to changes in the lock controls. + * + * @param callback the function to call when the lock controls changes. + */ + void subscribeLockControls(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the lock controls. */ + void unsubscribeLockControls(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPictureMode.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPictureMode.java new file mode 100644 index 000000000..b369b98bf --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPictureMode.java @@ -0,0 +1,39 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.television.PictureModeEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with picture mode characteristic {@link + * io.github.hapjava.characteristics.impl.television.PictureModeCharacteristic}. + */ +public interface AccessoryWithPictureMode { + + /** + * Retrieves the picture mode (see {@link + * io.github.hapjava.characteristics.impl.television.PictureModeEnum} for supported values). + * + * @return a future that will contain the picture mode + */ + CompletableFuture getPictureMode(); + + /** + * Set the picture mode (see {@link + * io.github.hapjava.characteristics.impl.television.PictureModeEnum} for supported values). + * + * @param pictureMode picture mode + * @return a future that completes when the change is made + */ + CompletableFuture setPictureMode(PictureModeEnum pictureMode); + + /** + * Subscribes to changes in the picture mode. + * + * @param callback the function to call when the picture mode changes. + */ + void subscribePictureMode(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the picture mode. */ + void unsubscribePictureMode(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPowerMode.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPowerMode.java new file mode 100644 index 000000000..5abb7e6f1 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithPowerMode.java @@ -0,0 +1,16 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.impl.television.PowerModeEnum; +import java.util.concurrent.CompletableFuture; + +/** An accessory with power mode. */ +public interface AccessoryWithPowerMode { + + /** + * Set the power mode. See {@link PowerModeEnum} for supported values + * + * @param mode target power mode + * @return a future that completes when the change is made + */ + CompletableFuture setPowerMode(PowerModeEnum mode); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRemainingDuration.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRemainingDuration.java new file mode 100644 index 000000000..7859fb396 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRemainingDuration.java @@ -0,0 +1,49 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.valve.RemainingDurationCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with remaining duration characteristic. + * + * @author Tim Harper + */ +public interface AccessoryWithRemainingDuration { + + /** + * Retrieves the remaining duration + * + * @return a future with the duration in seconds + */ + CompletableFuture getRemainingDuration(); + + /** + * return the min value for remaining duration. overwrite if you want to change the default value. + * + * @return min remaining duration + */ + default int getMinRemainingDuration() { + return RemainingDurationCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for remaining duration. overwrite if you want to change the default value. + * + * @return max remaining duration + */ + default int getMaxRemainingDuration() { + return RemainingDurationCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * Subscribes to changes in the duration; note it is not necessary to emit a change every second, + * homekit infers the countdown progress client side. + * + * @param callback the function when the existing duration has been replaced with a new one. + */ + void subscribeRemainingDuration(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeRemainingDuration(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithResetFilterIndication.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithResetFilterIndication.java new file mode 100644 index 000000000..737ca03ec --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithResetFilterIndication.java @@ -0,0 +1,16 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import java.util.concurrent.CompletableFuture; + +/** Accessory with filter reset characteristics */ +public interface AccessoryWithResetFilterIndication { + + /** + * Request to reset the filter level + * + * @param indication always 1, by HomeKit protocol. (to be ignored) + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture resetFilterIndication(Integer indication) throws Exception; +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRotationDirection.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRotationDirection.java new file mode 100644 index 000000000..91acf9afa --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRotationDirection.java @@ -0,0 +1,35 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.fan.RotationDirectionEnum; +import java.util.concurrent.CompletableFuture; + +/** accessory with rotation direction characteristics. */ +public interface AccessoryWithRotationDirection { + + /** + * Retrieves the current rotation direction. + * + * @return a future that will contain the direction + */ + CompletableFuture getRotationDirection(); + + /** + * Sets the rotation direction + * + * @param direction the direction to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setRotationDirection(RotationDirectionEnum direction) throws Exception; + + /** + * Subscribes to changes in the rotation direction. + * + * @param callback the function to call when the direction changes. + */ + void subscribeRotationDirection(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the rotation direction. */ + void unsubscribeRotationDirection(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRotationSpeed.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRotationSpeed.java new file mode 100644 index 000000000..ef39947ce --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithRotationSpeed.java @@ -0,0 +1,34 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** accessory with rotation speed characteristics. */ +public interface AccessoryWithRotationSpeed { + + /** + * Retrieves the current speed of the rotation + * + * @return a future that will contain the speed, expressed as an integer between 0 and 100. + */ + CompletableFuture getRotationSpeed(); + + /** + * Sets the speed of the rotation + * + * @param speed the speed to set, expressed as an integer between 0 and 100. + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setRotationSpeed(Double speed) throws Exception; + + /** + * Subscribes to changes in the rotation speed. + * + * @param callback the function to call when the speed changes. + */ + void subscribeRotationSpeed(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the rotation speed. */ + void unsubscribeRotationSpeed(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSecurityAlarmType.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSecurityAlarmType.java new file mode 100644 index 000000000..036fd35b3 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSecurityAlarmType.java @@ -0,0 +1,26 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.securitysystem.SecuritySystemAlarmTypeEnum; +import java.util.concurrent.CompletableFuture; + +/** This characteristic describes the type of alarm triggered by a security system. */ +public interface AccessoryWithSecurityAlarmType { + + /** + * return alarm type See {@link SecuritySystemAlarmTypeEnum} for possible values + * + * @return a future with the value + */ + CompletableFuture getSecurityAlarmType(); + + /** + * Subscribes to changes in status alarm type + * + * @param callback the function when the alarm type changes + */ + void subscribeSecurityAlarmType(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeSecurityAlarmType(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithServiceLabelIndex.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithServiceLabelIndex.java new file mode 100644 index 000000000..07cb17fc7 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithServiceLabelIndex.java @@ -0,0 +1,14 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import java.util.concurrent.CompletableFuture; + +/** Accessory with service label index. T */ +public interface AccessoryWithServiceLabelIndex { + + /** + * Retrieves the service label index. + * + * @return a future with the service label index + */ + CompletableFuture getServiceLabelIndex(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusActive.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusActive.java new file mode 100644 index 000000000..6bd7a18b5 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusActive.java @@ -0,0 +1,26 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with status active. */ +public interface AccessoryWithStatusActive { + + /** + * Retrieves the status active. A value of true indicates that the accessory is active and is + * functioning without any errors. + * + * @return a future with the value + */ + CompletableFuture getStatusActive(); + + /** + * Subscribes to changes in status active. + * + * @param callback the function when the status active changes + */ + void subscribeStatusActive(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeStatusActive(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusFault.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusFault.java new file mode 100644 index 000000000..b6b0aebdf --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusFault.java @@ -0,0 +1,28 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.StatusFaultEnum; +import java.util.concurrent.CompletableFuture; + +/** Accessory with characteristic that describes an accessory which has a fault. */ +public interface AccessoryWithStatusFault { + + /** + * Retrieves the status fault. A non-zero value indicates that the accessory has experienced a + * fault that may be interfering with its intended functionality. A value of 0 indicates that + * there is no fault. + * + * @return a future with the value + */ + CompletableFuture getStatusFault(); + + /** + * Subscribes to changes in status fault. + * + * @param callback the function when the status fault changes + */ + void subscribeStatusFault(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeStatusFault(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusLowBattery.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusLowBattery.java new file mode 100644 index 000000000..def16df5d --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusLowBattery.java @@ -0,0 +1,27 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryEnum; +import java.util.concurrent.CompletableFuture; + +/** This characteristic describes an accessoryʼs battery status. */ +public interface AccessoryWithStatusLowBattery { + + /** + * A status of 1 indicates that the battery level of the accessory is low. Value should return to + * 0 when the battery charges to a level thats above the low threshold. + * + * @return a future with the value + */ + CompletableFuture getStatusLowBattery(); + + /** + * Subscribes to changes in status low battery. + * + * @param callback the function when the status low batter changes + */ + void subscribeStatusLowBattery(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeStatusLowBattery(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusTampered.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusTampered.java new file mode 100644 index 000000000..fe25d2f44 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithStatusTampered.java @@ -0,0 +1,26 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.common.StatusTamperedEnum; +import java.util.concurrent.CompletableFuture; + +/** This characteristic describes an accessory which has been tampered with. */ +public interface AccessoryWithStatusTampered { + + /** + * Retrieves the status tampered. + * + * @return a future with the value + */ + CompletableFuture getStatusTampered(); + + /** + * Subscribes to changes in status tampered. + * + * @param callback the function when the status tampered changes + */ + void subscribeStatusTampered(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeStatusTampered(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSulphurDioxideDensity.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSulphurDioxideDensity.java new file mode 100644 index 000000000..dbe0cc947 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSulphurDioxideDensity.java @@ -0,0 +1,56 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airquality.SulphurDioxideDensityCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with sulphur dioxide density characteristic. */ +public interface AccessoryWithSulphurDioxideDensity { + + /** + * Retrieves the sulphur dioxide density. + * + * @return a future with the sulphur dioxide density + */ + CompletableFuture getSulphurDioxideDensity(); + + /** + * return the min value for sulphur dioxide density. overwrite if you want to change the default + * value. + * + * @return min sulphur dioxide density + */ + default double getMinSulphurDioxideDensity() { + return SulphurDioxideDensityCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for sulphur dioxide density. overwrite if you want to change the default + * value. + * + * @return max sulphur dioxide density + */ + default double getMaxSulphurDioxideDensity() { + return SulphurDioxideDensityCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for sulphur dioxide density. overwrite if you want to change the + * default value. + * + * @return min step sulphur dioxide density + */ + default double getMinStepSulphurDioxideDensity() { + return SulphurDioxideDensityCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in sulphur dioxide density. + * + * @param callback the function when sulphur dioxide density changes + */ + void subscribeSulphurDioxideDensity(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeSulphurDioxideDensity(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSwingMode.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSwingMode.java new file mode 100644 index 000000000..ae49ffee6 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithSwingMode.java @@ -0,0 +1,34 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.fan.SwingModeEnum; +import java.util.concurrent.CompletableFuture; + +/** Accessory with Swing Mode characteristics. */ +public interface AccessoryWithSwingMode { + + /** + * Retrieves the swing mode. + * + * @return a future that will contain the swing mode + */ + CompletableFuture getSwingMode(); + + /** + * Set the swing mode (DISABLED, ENABLED). + * + * @param swingMode swing mode + * @return a future that completes when the change is made + */ + CompletableFuture setSwingMode(SwingModeEnum swingMode); + + /** + * Subscribes to changes in the swing mode. + * + * @param callback the function to call when the swing mode changes. + */ + void subscribeSwingMode(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the swing mode. */ + void unsubscribeSwingMode(); +} diff --git a/src/main/java/io/github/hapjava/accessories/HorizontalTiltingWindowCovering.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetHorizontalTilting.java similarity index 54% rename from src/main/java/io/github/hapjava/accessories/HorizontalTiltingWindowCovering.java rename to src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetHorizontalTilting.java index 623291f02..cc154520d 100644 --- a/src/main/java/io/github/hapjava/accessories/HorizontalTiltingWindowCovering.java +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetHorizontalTilting.java @@ -1,21 +1,14 @@ -package io.github.hapjava.accessories; +package io.github.hapjava.accessories.optionalcharacteristic; -import io.github.hapjava.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; import java.util.concurrent.CompletableFuture; /** - * Extends WindowCovering with the ability to control horizontal tilt angles + * Accessory with target horizontal tilting characteristic. * * @author Andy Lintner */ -public interface HorizontalTiltingWindowCovering extends WindowCovering { - - /** - * Retrieves the current horizontal tilt angle - * - * @return a future that will contain the position as a value between -90 and 90 - */ - CompletableFuture getCurrentHorizontalTiltAngle(); +public interface AccessoryWithTargetHorizontalTilting { /** * Retrieves the target horizontal tilt angle @@ -33,13 +26,6 @@ public interface HorizontalTiltingWindowCovering extends WindowCovering { */ CompletableFuture setTargetHorizontalTiltAngle(int angle) throws Exception; - /** - * Subscribes to changes in the current horizontal tilt angle. - * - * @param callback the function to call when the state changes. - */ - void subscribeCurrentHorizontalTiltAngle(HomekitCharacteristicChangeCallback callback); - /** * Subscribes to changes in the target horizontal tilt angle. * @@ -47,9 +33,6 @@ public interface HorizontalTiltingWindowCovering extends WindowCovering { */ void subscribeTargetHorizontalTiltAngle(HomekitCharacteristicChangeCallback callback); - /** Unsubscribes from changes in the current horizontal tilt angle */ - void unsubscribeCurrentHorizontalTiltAngle(); - /** Unsubscribes from changes in the target horizontal tilt angle */ void unsubscribeTargetHorizontalTiltAngle(); } diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetMediaState.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetMediaState.java new file mode 100644 index 000000000..e1f1a34bd --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetMediaState.java @@ -0,0 +1,37 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.television.TargetMediaStateEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with target media state characteristic {@link + * io.github.hapjava.characteristics.impl.television.TargetMediaStateCharacteristic}. + */ +public interface AccessoryWithTargetMediaState { + + /** + * Retrieves the target media state (see {@link TargetMediaStateEnum} for supported values). + * + * @return a future that will contain the target media state + */ + CompletableFuture getTargetMediaState(); + + /** + * Set the target media state (see {@link TargetMediaStateEnum} for supported values). + * + * @param targetMediaState target media state + * @return a future that completes when the change is made + */ + CompletableFuture setTargetMediaState(TargetMediaStateEnum targetMediaState); + + /** + * Subscribes to changes in the target media state. + * + * @param callback the function to call when the target media state changes. + */ + void subscribeTargetMediaState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the target media state. */ + void unsubscribeTargetMediaState(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetRelativeHumidity.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetRelativeHumidity.java new file mode 100644 index 000000000..23ac5fd97 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetRelativeHumidity.java @@ -0,0 +1,33 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** accessory with target relative humidity. */ +public interface AccessoryWithTargetRelativeHumidity { + + /** + * Retrieves the target relative humidity. + * + * @return a future that will contain the target relative humidity. + */ + CompletableFuture getTargetRelativeHumidity(); + + /** + * Sets the target relative humidity. + * + * @param value the target relative humidity. + * @throws Exception when the target relative humidity cannot be changed. + */ + void setTargetRelativeHumidity(Double value) throws Exception; + + /** + * Subscribes to changes in the target relative humidity. + * + * @param callback the function to call when the target relative humidity changes. + */ + void subscribeTargetRelativeHumidity(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the target relative humidity. */ + void unsubscribeTargetRelativeHumidity(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetTilting.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetTilting.java new file mode 100644 index 000000000..9c2bc8009 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetTilting.java @@ -0,0 +1,34 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with target tilting characteristic. */ +public interface AccessoryWithTargetTilting { + + /** + * Retrieves the target tilt angle + * + * @return a future that will contain the target position as a value between -90 and 90 + */ + CompletableFuture getTargetTiltAngle(); + + /** + * Sets the target tilt angle + * + * @param angle the target angle to set, as a value between -90 and 90 + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setTargetTiltAngle(int angle) throws Exception; + + /** + * Subscribes to changes in the target tilt angle. + * + * @param callback the function to call when the state changes. + */ + void subscribeTargetTiltAngle(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the target tilt angle */ + void unsubscribeTargetTiltAngle(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetVerticalTilting.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetVerticalTilting.java new file mode 100644 index 000000000..e87607204 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetVerticalTilting.java @@ -0,0 +1,34 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with target vertical tilting characteristic. */ +public interface AccessoryWithTargetVerticalTilting { + + /** + * Retrieves the target vertical tilt angle + * + * @return a future that will contain the target position as a value between -90 and 90 + */ + CompletableFuture getTargetVerticalTiltAngle(); + + /** + * Sets the target position + * + * @param angle the target angle to set, as a value between -90 and 90 + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setTargetVerticalTiltAngle(int angle) throws Exception; + + /** + * Subscribes to changes in the target vertical tilt angle. + * + * @param callback the function to call when the state changes. + */ + void subscribeTargetVerticalTiltAngle(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the target vertical tilt angle */ + void unsubscribeTargetVerticalTiltAngle(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetVisibilityState.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetVisibilityState.java new file mode 100644 index 000000000..dcadd1cc5 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTargetVisibilityState.java @@ -0,0 +1,36 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.inputsource.TargetVisibilityStateEnum; +import java.util.concurrent.CompletableFuture; + +/** accessory with target visibility state characteristics. */ +public interface AccessoryWithTargetVisibilityState { + + /** + * Retrieves the target visibility state. + * + * @return a future that will contain the target visibility state + */ + CompletableFuture getTargetVisibilityState(); + + /** + * Sets the target visibility state + * + * @param state the target visibility state to set + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setTargetVisibilityState(TargetVisibilityStateEnum state) + throws Exception; + + /** + * Subscribes to changes in t target visibility state. + * + * @param callback the function to call when the target visibility state changes. + */ + void subscribeTargetVisibilityState(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the target visibility state. */ + void unsubscribeTargetVisibilityState(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTemperatureDisplayUnits.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTemperatureDisplayUnits.java new file mode 100644 index 000000000..b9407b34b --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithTemperatureDisplayUnits.java @@ -0,0 +1,39 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.thermostat.TemperatureDisplayUnitEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with characteristic that describes units of temperature used for presentation purposes + * (e.g. the units of temperature displayed on the screen). + */ +public interface AccessoryWithTemperatureDisplayUnits { + + /** + * Retrieves temperature display units + * + * @return a future that will contain temperature display units + */ + CompletableFuture getTemperatureDisplayUnits(); + + /** + * Sets the temperature display units + * + * @param units the target temperature display units + * @return a future that completes when the change is made + * @throws Exception when the change cannot be made + */ + CompletableFuture setTemperatureDisplayUnits(TemperatureDisplayUnitEnum units) + throws Exception; + + /** + * Subscribes to changes in the temperature display units + * + * @param callback the function to call when temperature display units changes. + */ + void subscribeTemperatureDisplayUnits(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the temperature display units */ + void unsubscribeTemperatureDisplayUnits(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVOCDensity.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVOCDensity.java new file mode 100644 index 000000000..f8a7bc46b --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVOCDensity.java @@ -0,0 +1,53 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.airquality.VOCDensityCharacteristic; +import java.util.concurrent.CompletableFuture; + +/** Accessory with VOC Density characteristic. */ +public interface AccessoryWithVOCDensity { + + /** + * Retrieves the VOC density. + * + * @return a future with the VOC density + */ + CompletableFuture getVOCDensity(); + + /** + * return the min value for VOC density. overwrite if you want to change the default value. + * + * @return min VOC density + */ + default double getMinVOCDensity() { + return VOCDensityCharacteristic.DEFAULT_MIN_VALUE; + } + + /** + * return the max value for VOC density. overwrite if you want to change the default value. + * + * @return max VOC density + */ + default double getMaxVOCDensity() { + return VOCDensityCharacteristic.DEFAULT_MAX_VALUE; + } + + /** + * return the min step value for VOC density. overwrite if you want to change the default value. + * + * @return min step VOC density + */ + default double getMinStepVOCDensity() { + return VOCDensityCharacteristic.DEFAULT_STEP; + } + + /** + * Subscribes to changes in VOC density. + * + * @param callback the function when VOC density changes + */ + void subscribeVOCDensity(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes */ + void unsubscribeVOCDensity(); +} diff --git a/src/main/java/io/github/hapjava/accessories/VerticalTiltingWindowCovering.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVerticalTilting.java similarity index 83% rename from src/main/java/io/github/hapjava/accessories/VerticalTiltingWindowCovering.java rename to src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVerticalTilting.java index e85a7e9c0..3e849e5bb 100644 --- a/src/main/java/io/github/hapjava/accessories/VerticalTiltingWindowCovering.java +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVerticalTilting.java @@ -1,15 +1,10 @@ -package io.github.hapjava.accessories; +package io.github.hapjava.accessories.optionalcharacteristic; -import io.github.hapjava.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; import java.util.concurrent.CompletableFuture; -/** - * Extends WindowCovering with the ability to control vertical tilt angles - * - * @author Andy Lintner - */ -public interface VerticalTiltingWindowCovering extends WindowCovering { - +/** Accessory with vertical tilting characteristic. */ +public interface AccessoryWithVerticalTilting { /** * Retrieves the current vertical tilt angle * diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolume.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolume.java new file mode 100644 index 000000000..b6dda376f --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolume.java @@ -0,0 +1,34 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with volume values. */ +public interface AccessoryWithVolume { + + /** + * Retrieves the current volume + * + * @return a future that will contain the volume, expressed as an integer between 0 and 100. + */ + CompletableFuture getVolume(); + + /** + * Sets the current volume + * + * @param value the volume, on a scale of 0 to 100, to set + * @return a future that completes when the volume is changed + * @throws Exception when the volume cannot be set + */ + CompletableFuture setVolume(Integer value) throws Exception; + + /** + * Subscribes to changes in the volume. + * + * @param callback the function to call when the state changes. + */ + void subscribeVolume(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the volume. */ + void unsubscribeVolume(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolumeControlType.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolumeControlType.java new file mode 100644 index 000000000..21a6f6c66 --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolumeControlType.java @@ -0,0 +1,30 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.televisionspeaker.VolumeControlTypeEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with volume control type {@link + * io.github.hapjava.characteristics.impl.televisionspeaker.VolumeControlTypeCharacteristic} + */ +public interface AccessoryWithVolumeControlType { + + /** + * Retrieves the current volume control type. see {@link VolumeControlTypeEnum} for possible + * values + * + * @return a future that will contain the type. + */ + CompletableFuture getVolumeControlType(); + + /** + * Subscribes to changes in the volume. + * + * @param callback the function to call when the state changes. + */ + void subscribeVolumeControlType(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the volume. */ + void unsubscribeVolumeControlType(); +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolumeSelector.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolumeSelector.java new file mode 100644 index 000000000..0c2a2890f --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithVolumeSelector.java @@ -0,0 +1,20 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.impl.televisionspeaker.VolumeSelectorEnum; +import java.util.concurrent.CompletableFuture; + +/** + * Accessory with volume selector {@link + * io.github.hapjava.characteristics.impl.televisionspeaker.VolumeSelectorCharacteristic} + */ +public interface AccessoryWithVolumeSelector { + + /** + * Sets the volume selector + * + * @param value the volume selector + * @return a future that completes when the volume selector is changed + * @throws Exception when the volume selector cannot be set + */ + CompletableFuture setVolumeSelector(VolumeSelectorEnum value) throws Exception; +} diff --git a/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithWaterLevel.java b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithWaterLevel.java new file mode 100644 index 000000000..591a1b5ac --- /dev/null +++ b/src/main/java/io/github/hapjava/accessories/optionalcharacteristic/AccessoryWithWaterLevel.java @@ -0,0 +1,25 @@ +package io.github.hapjava.accessories.optionalcharacteristic; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.concurrent.CompletableFuture; + +/** Accessory with water level. */ +public interface AccessoryWithWaterLevel { + + /** + * Retrieves the water level in percent. + * + * @return a future that will contain the water level, expressed as an double between 0 and 100. + */ + CompletableFuture getWaterLevel(); + + /** + * Subscribes to changes in the water level. + * + * @param callback the function to call when the state changes. + */ + void subscribeWaterLevel(HomekitCharacteristicChangeCallback callback); + + /** Unsubscribes from changes in the water level. */ + void unsubscribeWaterLevel(); +} diff --git a/src/main/java/io/github/hapjava/accessories/properties/CarbonMonoxideDetectedState.java b/src/main/java/io/github/hapjava/accessories/properties/CarbonMonoxideDetectedState.java deleted file mode 100644 index 3a713094d..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/CarbonMonoxideDetectedState.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -public enum CarbonMonoxideDetectedState { - NORMAL(0), - ABNORMAL(1); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(CarbonMonoxideDetectedState.values()) - .collect(Collectors.toMap(CarbonMonoxideDetectedState::getCode, t -> t)); - } - - public static CarbonMonoxideDetectedState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - CarbonMonoxideDetectedState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/ContactState.java b/src/main/java/io/github/hapjava/accessories/properties/ContactState.java deleted file mode 100644 index 958e0b689..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/ContactState.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -public enum ContactState { - DETECTED(0), - NOT_DETECTED(1); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(ContactState.values()) - .collect(Collectors.toMap(ContactState::getCode, t -> t)); - } - - public static ContactState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - ContactState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/CurrentSecuritySystemState.java b/src/main/java/io/github/hapjava/accessories/properties/CurrentSecuritySystemState.java deleted file mode 100644 index f444a38cc..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/CurrentSecuritySystemState.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.SecuritySystem; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The current state of a {@link SecuritySystem}. Unlike {@link TargetSecuritySystemState}, this - * enum includes a triggered state. - * - * @author Gaston Dombiak - */ -public enum CurrentSecuritySystemState { - - /** The home is occupied and residents are active. */ - STAY_ARM(0), - /** The home is unoccupied. */ - AWAY_ARM(1), - /** The home is occupied and residents are sleeping. */ - NIGHT_ARM(2), - /** The security system is disarmed. */ - DISARMED(3), - /** The security system is triggered. */ - TRIGGERED(4); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(CurrentSecuritySystemState.values()) - .collect(Collectors.toMap(CurrentSecuritySystemState::getCode, t -> t)); - } - - public static CurrentSecuritySystemState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - CurrentSecuritySystemState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/DoorState.java b/src/main/java/io/github/hapjava/accessories/properties/DoorState.java deleted file mode 100644 index c47bc4ccf..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/DoorState.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -public enum DoorState { - OPEN(0), - CLOSED(1), - OPENING(2), - CLOSING(3), - STOPPED(4); - - private static final Map reverse; - - static { - reverse = Arrays.stream(DoorState.values()).collect(Collectors.toMap(t -> t.getCode(), t -> t)); - } - - public static DoorState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - private DoorState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/LockMechanismState.java b/src/main/java/io/github/hapjava/accessories/properties/LockMechanismState.java deleted file mode 100644 index 7dceff8c7..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/LockMechanismState.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.LockMechanism; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The state of a {@link LockMechanism}. - * - * @author Andy Lintner - */ -public enum LockMechanismState { - UNSECURED(0), - SECURED(1), - JAMMED(2), - UNKNOWN(3); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(LockMechanismState.values()) - .collect(Collectors.toMap(t -> t.getCode(), t -> t)); - } - - public static LockMechanismState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - private LockMechanismState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/RotationDirection.java b/src/main/java/io/github/hapjava/accessories/properties/RotationDirection.java deleted file mode 100644 index 96ee54749..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/RotationDirection.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -public enum RotationDirection { - CLOCKWISE(0), - COUNTER_CLOCKWISE(1); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(RotationDirection.values()) - .collect(Collectors.toMap(t -> t.getCode(), t -> t)); - } - - public static RotationDirection fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - private RotationDirection(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/SecuritySystemAlarmType.java b/src/main/java/io/github/hapjava/accessories/properties/SecuritySystemAlarmType.java deleted file mode 100644 index d8a96de63..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/SecuritySystemAlarmType.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.SecuritySystem; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Type of alarm of a {@link SecuritySystem}. - * - * @author Gaston Dombiak - */ -public enum SecuritySystemAlarmType { - - /** Alarm conditions are cleared */ - NO_ALARM(0), - /** Alarm type is not known */ - UNKNOWN(1); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(SecuritySystemAlarmType.values()) - .collect(Collectors.toMap(SecuritySystemAlarmType::getCode, t -> t)); - } - - public static SecuritySystemAlarmType fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - SecuritySystemAlarmType(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/SmokeDetectedState.java b/src/main/java/io/github/hapjava/accessories/properties/SmokeDetectedState.java deleted file mode 100644 index a7f71a30a..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/SmokeDetectedState.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -public enum SmokeDetectedState { - NOT_DETECTED(0), - DETECTED(1); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(SmokeDetectedState.values()) - .collect(Collectors.toMap(SmokeDetectedState::getCode, t -> t)); - } - - public static SmokeDetectedState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - SmokeDetectedState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/TargetSecuritySystemState.java b/src/main/java/io/github/hapjava/accessories/properties/TargetSecuritySystemState.java deleted file mode 100644 index a08a2987b..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/TargetSecuritySystemState.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.SecuritySystem; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The target state of a {@link SecuritySystem}. - * - * @author Gaston Dombiak - */ -public enum TargetSecuritySystemState { - - /** Arm the system when the home is occupied and residents are active. */ - STAY_ARM(0), - /** Arm the system when the home is unoccupied. */ - AWAY_ARM(1), - /** Arm the system when the home is occupied and residents are sleeping. */ - NIGHT_ARM(2), - /** Disarm the system. */ - DISARM(3); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(TargetSecuritySystemState.values()) - .collect(Collectors.toMap(TargetSecuritySystemState::getCode, t -> t)); - } - - public static TargetSecuritySystemState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - TargetSecuritySystemState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/TemperatureUnit.java b/src/main/java/io/github/hapjava/accessories/properties/TemperatureUnit.java deleted file mode 100644 index 228366cec..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/TemperatureUnit.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.TemperatureSensor; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The temperature unit used by a {@link TemperatureSensor}. - * - * @author Andy Lintner - */ -public enum TemperatureUnit { - CELSIUS(0), - FAHRENHEIT(1); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(TemperatureUnit.values()).collect(Collectors.toMap(t -> t.getCode(), t -> t)); - } - - static TemperatureUnit fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - private TemperatureUnit(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/ThermostatMode.java b/src/main/java/io/github/hapjava/accessories/properties/ThermostatMode.java deleted file mode 100644 index 4eb586584..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/ThermostatMode.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.thermostat.BasicThermostat; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The mode used by a {@link BasicThermostat} - * - * @author Andy Lintner - */ -public enum ThermostatMode { - OFF(0), - HEAT(1), - COOL(2), - AUTO(3); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(ThermostatMode.values()).collect(Collectors.toMap(t -> t.getCode(), t -> t)); - } - - public static ThermostatMode fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - private ThermostatMode(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/ValveType.java b/src/main/java/io/github/hapjava/accessories/properties/ValveType.java deleted file mode 100644 index 95f564869..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/ValveType.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.Valve; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The mode used by a {@link Valve} - * - * @author Tim Harper - */ -public enum ValveType { - GENERIC(0), - IRRIGATION(1), - SHOWER(2), - WATER_FAUCET(3); - - private static final Map reverse; - - static { - reverse = Arrays.stream(ValveType.values()).collect(Collectors.toMap(t -> t.getCode(), t -> t)); - } - - public static ValveType fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - private ValveType(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/WindowCoveringPositionState.java b/src/main/java/io/github/hapjava/accessories/properties/WindowCoveringPositionState.java deleted file mode 100644 index 1686fd2fb..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/WindowCoveringPositionState.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.accessories.properties; - -import io.github.hapjava.accessories.WindowCovering; -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The position state used by a {@link WindowCovering} - * - * @author Andy Lintner - */ -public enum WindowCoveringPositionState { - DECREASING(0), - INCREASING(1), - STOPPED(2); - - private static final Map reverse; - - static { - reverse = - Arrays.stream(WindowCoveringPositionState.values()) - .collect(Collectors.toMap(t -> t.getCode(), t -> t)); - } - - public static WindowCoveringPositionState fromCode(Integer code) { - return reverse.get(code); - } - - private final int code; - - private WindowCoveringPositionState(int code) { - this.code = code; - } - - public int getCode() { - return code; - } -} diff --git a/src/main/java/io/github/hapjava/accessories/properties/package-info.java b/src/main/java/io/github/hapjava/accessories/properties/package-info.java deleted file mode 100644 index f2827b56b..000000000 --- a/src/main/java/io/github/hapjava/accessories/properties/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -/** Contains properties used by {@link io.github.hapjava.accessories}. */ -package io.github.hapjava.accessories.properties; diff --git a/src/main/java/io/github/hapjava/accessories/thermostat/BasicThermostat.java b/src/main/java/io/github/hapjava/accessories/thermostat/BasicThermostat.java deleted file mode 100644 index 8747ab01a..000000000 --- a/src/main/java/io/github/hapjava/accessories/thermostat/BasicThermostat.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.github.hapjava.accessories.thermostat; - -import io.github.hapjava.*; -import io.github.hapjava.accessories.TemperatureSensor; -import io.github.hapjava.accessories.properties.ThermostatMode; -import io.github.hapjava.impl.services.ThermostatService; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.CompletableFuture; - -public interface BasicThermostat extends HomekitAccessory, TemperatureSensor { - - /** - * Retrieves the current {@link ThermostatMode} of the thermostat. - * - * @return a future that will contain the mode. - */ - CompletableFuture getCurrentMode(); - - /** - * Subscribes to changes in the {@link ThermostatMode} of the thermostat. - * - * @param callback the function to call when the state changes. - */ - void subscribeCurrentMode(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the mode of the thermostat. */ - void unsubscribeCurrentMode(); - - /** - * Sets the {@link ThermostatMode} of the thermostat. - * - * @param mode The {@link ThermostatMode} to set. - * @throws Exception when the change cannot be made. - */ - void setTargetMode(ThermostatMode mode) throws Exception; - - /** - * Retrieves the pending, but not yet complete, {@link ThermostatMode} of the thermostat. - * - * @return a future that will contain the target mode. - */ - CompletableFuture getTargetMode(); - - /** - * Subscribes to changes in the pending, but not yet complete, {@link ThermostatMode} of the - * thermostat. - * - * @param callback the function to call when the state changes. - */ - void subscribeTargetMode(HomekitCharacteristicChangeCallback callback); - - /** - * Unsubscribes from changes in the pending, but not yet complete, {@link ThermostatMode} of the - * thermostat. - */ - void unsubscribeTargetMode(); - - /** - * Retrieves the target temperature, in celsius degrees. - * - * @return a future that will contain the target temperature. - */ - CompletableFuture getTargetTemperature(); - - /** - * Sets the target temperature. - * - * @param value the target temperature, in celsius degrees. - * @throws Exception when the temperature cannot be changed. - */ - void setTargetTemperature(Double value) throws Exception; - - /** - * Subscribes to changes in the target temperature. - * - * @param callback the function to call when the state changes. - */ - void subscribeTargetTemperature(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the target temperature. */ - void unsubscribeTargetTemperature(); - - @Override - default Collection getServices() { - return Collections.singleton(new ThermostatService(this)); - } -} diff --git a/src/main/java/io/github/hapjava/accessories/thermostat/CoolingThermostat.java b/src/main/java/io/github/hapjava/accessories/thermostat/CoolingThermostat.java deleted file mode 100644 index 3229146b5..000000000 --- a/src/main/java/io/github/hapjava/accessories/thermostat/CoolingThermostat.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.hapjava.accessories.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import java.util.concurrent.CompletableFuture; - -public interface CoolingThermostat extends BasicThermostat { - - /** - * Retrieves the temperature above which the thermostat should begin cooling. - * - * @return a future that will contain the threshold temperature, in celsius degrees. - */ - CompletableFuture getCoolingThresholdTemperature(); - - /** - * Sets the temperature above which the thermostat should begin cooling. - * - * @param value the threshold temperature, in celsius degrees. - * @throws Exception when the threshold temperature cannot be changed. - */ - void setCoolingThresholdTemperature(Double value) throws Exception; - - /** - * Subscribes to changes in the cooling threshold. - * - * @param callback the function to call when the state changes. - */ - void subscribeCoolingThresholdTemperature(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the cooling threshold. */ - void unsubscribeCoolingThresholdTemperature(); -} diff --git a/src/main/java/io/github/hapjava/accessories/thermostat/HeatingThermostat.java b/src/main/java/io/github/hapjava/accessories/thermostat/HeatingThermostat.java deleted file mode 100644 index 5a672adb9..000000000 --- a/src/main/java/io/github/hapjava/accessories/thermostat/HeatingThermostat.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.hapjava.accessories.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import java.util.concurrent.CompletableFuture; - -public interface HeatingThermostat extends BasicThermostat { - - /** - * Retrieves the temperature below which the thermostat should begin heating. - * - * @return a future that will contain the threshold temperature, in celsius degrees. - */ - CompletableFuture getHeatingThresholdTemperature(); - - /** - * Sets the temperature below which the thermostat should begin heating. - * - * @param value the threshold temperature, in celsius degrees. - * @throws Exception when the threshold temperature cannot be changed. - */ - void setHeatingThresholdTemperature(Double value) throws Exception; - - /** - * Subscribes to changes in the heating threshold. - * - * @param callback the function to call when the state changes. - */ - void subscribeHeatingThresholdTemperature(HomekitCharacteristicChangeCallback callback); - - /** Unsubscribes from changes in the heating threshold. */ - void unsubscribeHeatingThresholdTemperature(); -} diff --git a/src/main/java/io/github/hapjava/characteristics/BooleanCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/BooleanCharacteristic.java deleted file mode 100644 index f5f064bfb..000000000 --- a/src/main/java/io/github/hapjava/characteristics/BooleanCharacteristic.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.github.hapjava.characteristics; - -import javax.json.JsonNumber; -import javax.json.JsonValue; -import javax.json.JsonValue.ValueType; - -/** - * Characteristic that exposes a Boolean value. - * - * @author Andy Lintner - */ -public abstract class BooleanCharacteristic extends BaseCharacteristic { - - /** - * Default constructor - * - * @param type a string containing a UUID that indicates the type of characteristic. Apple defines - * a set of these, however implementors can create their own as well. - * @param isWritable indicates whether the value can be changed. - * @param isReadable indicates whether the value can be retrieved. - * @param description a description of the characteristic to be passed to the consuming device. - */ - public BooleanCharacteristic( - String type, boolean isWritable, boolean isReadable, String description) { - super(type, "bool", isWritable, isReadable, description); - } - - /** {@inheritDoc} */ - @Override - protected Boolean convert(JsonValue jsonValue) { - if (jsonValue.getValueType().equals(ValueType.NUMBER)) { - return ((JsonNumber) jsonValue).intValue() > 0; - } - return jsonValue.equals(JsonValue.TRUE); - } - - /** {@inheritDoc} */ - @Override - protected Boolean getDefault() { - return false; - } -} diff --git a/src/main/java/io/github/hapjava/characteristics/Characteristic.java b/src/main/java/io/github/hapjava/characteristics/Characteristic.java index ec85f8d65..b2454e5f9 100644 --- a/src/main/java/io/github/hapjava/characteristics/Characteristic.java +++ b/src/main/java/io/github/hapjava/characteristics/Characteristic.java @@ -8,7 +8,7 @@ /** * Interface for the characteristics provided by a Service. * - *

Characteristics are the lowest level building block of the Homekit Accessory Protocol. They + *

Characteristics are the lowest level building block of the HomeKit Accessory Protocol. They * define variables that can be retrieved or set by the remote client. Most consumers of this * library will be better served by using one of the characteristic classes in {@link * io.github.hapjava.characteristics} when creating custom accessory types (the standard accessories @@ -18,6 +18,8 @@ * @author Andy Lintner */ public interface Characteristic { + /** @return The UUID type for this characteristic. */ + String getType(); /** * Adds an attribute to the passed JsonObjectBuilder named "value" with the current value of the @@ -28,7 +30,7 @@ public interface Characteristic { void supplyValue(JsonObjectBuilder characteristicBuilder); /** - * Creates the JSON representation of the characteristic, in accordance with the Homekit Accessory + * Creates the JSON representation of the characteristic, in accordance with the HomeKit Accessory * Protocol. * * @param iid The instance ID of the characteristic to be included in the serialization. @@ -42,4 +44,14 @@ public interface Characteristic { * @param jsonValue the JSON serialized value to set. */ void setValue(JsonValue jsonValue); + + /** + * Invoked by the remote client, this updates the current value of the characteristic. + * + * @param jsonValue the JSON serialized value to set. + * @param username the authenticated username making the request + */ + default void setValue(JsonValue jsonValue, String username) { + setValue(jsonValue); + } } diff --git a/src/main/java/io/github/hapjava/characteristics/CharacteristicEnum.java b/src/main/java/io/github/hapjava/characteristics/CharacteristicEnum.java new file mode 100644 index 000000000..bc8dbc9c2 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/CharacteristicEnum.java @@ -0,0 +1,5 @@ +package io.github.hapjava.characteristics; + +public interface CharacteristicEnum { + int getCode(); +} diff --git a/src/main/java/io/github/hapjava/characteristics/EnumCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/EnumCharacteristic.java deleted file mode 100644 index 84000fbb2..000000000 --- a/src/main/java/io/github/hapjava/characteristics/EnumCharacteristic.java +++ /dev/null @@ -1,65 +0,0 @@ -package io.github.hapjava.characteristics; - -import java.util.concurrent.CompletableFuture; -import javax.json.JsonNumber; -import javax.json.JsonObject; -import javax.json.JsonObjectBuilder; -import javax.json.JsonValue; - -/** - * Characteristic that exposes an Enum value. Enums are represented as an Integer value in the - * Homekit protocol, and classes extending this one must handle the static mapping to an Integer - * value. - * - * @author Andy Lintner - */ -public abstract class EnumCharacteristic extends BaseCharacteristic { - - private final int maxValue; - - /** - * Default constructor - * - * @param type a string containing a UUID that indicates the type of characteristic. Apple defines - * a set of these, however implementors can create their own as well. - * @param isWritable indicates whether the value can be changed. - * @param isReadable indicates whether the value can be retrieved. - * @param description a description of the characteristic to be passed to the consuming device. - * @param maxValue the number of enum items. - */ - public EnumCharacteristic( - String type, boolean isWritable, boolean isReadable, String description, int maxValue) { - super(type, "int", isWritable, isReadable, description); - this.maxValue = maxValue; - } - - /** {@inheritDoc} */ - @Override - protected CompletableFuture makeBuilder(int iid) { - return super.makeBuilder(iid) - .thenApply( - builder -> { - return builder.add("minValue", 0).add("maxValue", maxValue).add("minStep", 1); - }); - } - - /** {@inheritDoc} */ - @Override - protected Integer convert(JsonValue jsonValue) { - if (jsonValue instanceof JsonNumber) { - return ((JsonNumber) jsonValue).intValue(); - } else if (jsonValue == JsonObject.TRUE) { - return 1; // For at least one enum type (locks), homekit will send a true instead of 1 - } else if (jsonValue == JsonObject.FALSE) { - return 0; - } else { - throw new IndexOutOfBoundsException("Cannot convert " + jsonValue.getClass() + " to int"); - } - } - - /** {@inheritDoc} */ - @Override - protected Integer getDefault() { - return 0; - } -} diff --git a/src/main/java/io/github/hapjava/characteristics/EventableCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/EventableCharacteristic.java index ddb5c5558..1da8f228b 100644 --- a/src/main/java/io/github/hapjava/characteristics/EventableCharacteristic.java +++ b/src/main/java/io/github/hapjava/characteristics/EventableCharacteristic.java @@ -1,7 +1,5 @@ package io.github.hapjava.characteristics; -import io.github.hapjava.HomekitCharacteristicChangeCallback; - /** * A characteristic that can be listened to by the connected iOS device. * diff --git a/src/main/java/io/github/hapjava/characteristics/ExceptionalConsumer.java b/src/main/java/io/github/hapjava/characteristics/ExceptionalConsumer.java new file mode 100644 index 000000000..1c625470d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/ExceptionalConsumer.java @@ -0,0 +1,9 @@ +package io.github.hapjava.characteristics; + +public interface ExceptionalConsumer { + void accept(T t) throws Exception; + + default void accept(T t, String username) throws Exception { + accept(t); + } +} diff --git a/src/main/java/io/github/hapjava/HomekitCharacteristicChangeCallback.java b/src/main/java/io/github/hapjava/characteristics/HomekitCharacteristicChangeCallback.java similarity index 86% rename from src/main/java/io/github/hapjava/HomekitCharacteristicChangeCallback.java rename to src/main/java/io/github/hapjava/characteristics/HomekitCharacteristicChangeCallback.java index 6008b9d04..e2d5bc5f2 100644 --- a/src/main/java/io/github/hapjava/HomekitCharacteristicChangeCallback.java +++ b/src/main/java/io/github/hapjava/characteristics/HomekitCharacteristicChangeCallback.java @@ -1,6 +1,4 @@ -package io.github.hapjava; - -import io.github.hapjava.characteristics.EventableCharacteristic; +package io.github.hapjava.characteristics; /** * A callback interface for notifying subscribers that a characteristic value has changed. diff --git a/src/main/java/io/github/hapjava/characteristics/IntegerCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/IntegerCharacteristic.java deleted file mode 100644 index f83000a79..000000000 --- a/src/main/java/io/github/hapjava/characteristics/IntegerCharacteristic.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.github.hapjava.characteristics; - -import java.util.concurrent.CompletableFuture; -import javax.json.JsonNumber; -import javax.json.JsonObjectBuilder; -import javax.json.JsonValue; - -/** - * A characteristic that provides an Integer data type. - * - * @author Andy Lintner - */ -public abstract class IntegerCharacteristic extends BaseCharacteristic { - - private final int minValue; - private final int maxValue; - private final String unit; - - /** - * Default constructor - * - * @param type a string containing a UUID that indicates the type of characteristic. Apple defines - * a set of these, however implementors can create their own as well. - * @param isWritable indicates whether the value can be changed. - * @param isReadable indicates whether the value can be retrieved. - * @param description a description of the characteristic to be passed to the consuming device. - * @param minValue the minimum supported value. - * @param maxValue the maximum supported value - * @param unit a description of the unit this characteristic supports. - */ - public IntegerCharacteristic( - String type, - boolean isWritable, - boolean isReadable, - String description, - int minValue, - int maxValue, - String unit) { - super(type, "int", isWritable, isReadable, description); - this.minValue = minValue; - this.maxValue = maxValue; - this.unit = unit; - } - - /** {@inheritDoc} */ - @Override - protected CompletableFuture makeBuilder(int iid) { - return super.makeBuilder(iid) - .thenApply( - builder -> { - return builder - .add("minValue", minValue) - .add("maxValue", maxValue) - .add("minStep", 1) - .add("unit", unit); - }); - } - - /** {@inheritDoc} */ - @Override - protected Integer getDefault() { - return minValue; - } - - /** {@inheritDoc} */ - @Override - protected Integer convert(JsonValue jsonValue) { - return ((JsonNumber) jsonValue).intValue(); - } -} diff --git a/src/main/java/io/github/hapjava/characteristics/WriteOnlyBooleanCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/WriteOnlyBooleanCharacteristic.java deleted file mode 100644 index d055a0872..000000000 --- a/src/main/java/io/github/hapjava/characteristics/WriteOnlyBooleanCharacteristic.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.hapjava.characteristics; - -import java.util.concurrent.CompletableFuture; -import javax.json.JsonObjectBuilder; - -/** - * A characteristic that provides a boolean that can only be written to, not read. - * - * @author Andy Lintner - */ -public abstract class WriteOnlyBooleanCharacteristic extends BooleanCharacteristic { - - /** - * Default constructor - * - * @param type a string containing a UUID that indicates the type of characteristic. Apple defines - * a set of these, however implementors can create their own as well. - * @param description a description of the characteristic to be passed to the consuming device. - */ - public WriteOnlyBooleanCharacteristic(String type, String description) { - super(type, true, false, description); - } - - @Override - protected final CompletableFuture getValue() { - return CompletableFuture.completedFuture(false); - } - - @Override - protected final void setJsonValue(JsonObjectBuilder builder, Boolean value) { - // Do nothing - non-readable characteristics cannot have a value key set - } -} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/AccessoryFlagsCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/AccessoryFlagsCharacteristic.java new file mode 100644 index 000000000..f04a4dd8e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/AccessoryFlagsCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates whether accessory requires additional setup. See {@link + * AccessoryFlagsEnum} for possible values. + */ +public class AccessoryFlagsCharacteristic extends EnumCharacteristic { + + public AccessoryFlagsCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000A6-0000-1000-8000-0026BB765291", + "accessory flags", + AccessoryFlagsEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/AccessoryFlagsEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/AccessoryFlagsEnum.java new file mode 100644 index 000000000..a849383e8 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/AccessoryFlagsEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0x0001 (bit0) ”Requires additional setup” 0x0002 - 0xFFFF ”Reserved” */ +public enum AccessoryFlagsEnum implements CharacteristicEnum { + NO_FLAGS(0), + REQUIRES_ADDITIONAL_SETUP(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(AccessoryFlagsEnum.values()) + .collect(Collectors.toMap(AccessoryFlagsEnum::getCode, t -> t)); + } + + public static AccessoryFlagsEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + AccessoryFlagsEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/FirmwareRevisionCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/FirmwareRevisionCharacteristic.java new file mode 100644 index 000000000..542cb805b --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/FirmwareRevisionCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.impl.base.StaticStringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** This characteristic describes a firmware revision string */ +public class FirmwareRevisionCharacteristic extends StaticStringCharacteristic { + + public FirmwareRevisionCharacteristic(Supplier> getter) { + super( + "00000052-0000-1000-8000-0026BB765291", + "firmware revision", + Optional.of(getter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/HardwareRevisionCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/HardwareRevisionCharacteristic.java new file mode 100644 index 000000000..f323de0d8 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/HardwareRevisionCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.impl.base.StaticStringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** This characteristic describes a hardware revision in a form x[.y[.z]] (e.g. ”100.1.1”) */ +public class HardwareRevisionCharacteristic extends StaticStringCharacteristic { + + public HardwareRevisionCharacteristic(Supplier> getter) { + super( + "00000053-0000-1000-8000-0026BB765291", + "hardware revision", + Optional.of(getter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/IdentifyCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/IdentifyCharacteristic.java new file mode 100644 index 000000000..8936ba77d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/IdentifyCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; + +/** This characteristic enables accessory to run its identify routine. */ +public class IdentifyCharacteristic extends BooleanCharacteristic { + + public IdentifyCharacteristic(ExceptionalConsumer setter) { + super( + "00000014-0000-1000-8000-0026BB765291", + "identifies the accessory", + Optional.empty(), + Optional.of(setter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/ManufacturerCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/ManufacturerCharacteristic.java new file mode 100644 index 000000000..777b571c2 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/ManufacturerCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.impl.base.StaticStringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** This characteristic contains the name of the company whose brand will appear on the accessory */ +public class ManufacturerCharacteristic extends StaticStringCharacteristic { + + public ManufacturerCharacteristic(Supplier> getter) { + super( + "00000020-0000-1000-8000-0026BB765291", + "manufacturer", + Optional.of(getter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/ModelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/ModelCharacteristic.java new file mode 100644 index 000000000..4df7975af --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/ModelCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.impl.base.StaticStringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** This characteristic contains the manufacturer-specific model of the accessory */ +public class ModelCharacteristic extends StaticStringCharacteristic { + + public ModelCharacteristic(Supplier> getter) { + super( + "00000021-0000-1000-8000-0026BB765291", + "model", + Optional.of(getter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/SerialNumberCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/SerialNumberCharacteristic.java new file mode 100644 index 000000000..0c9860d73 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/accessoryinformation/SerialNumberCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.accessoryinformation; + +import io.github.hapjava.characteristics.impl.base.StaticStringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** This characteristic contains the manufacturer-specific serial number of the accessory. */ +public class SerialNumberCharacteristic extends StaticStringCharacteristic { + + public SerialNumberCharacteristic(Supplier> getter) { + super( + "00000030-0000-1000-8000-0026BB765291", + "serial number", + Optional.of(getter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/CurrentAirPurifierCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/CurrentAirPurifierCharacteristic.java new file mode 100644 index 000000000..c5b506c40 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/CurrentAirPurifierCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.airpurifier; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the current state of the air purifier. See {@link + * CurrentAirPurifierStateEnum} for possible values. + */ +public class CurrentAirPurifierCharacteristic + extends EnumCharacteristic { + + public CurrentAirPurifierCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000A9-0000-1000-8000-0026BB765291", + "current air purifier state", + CurrentAirPurifierStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/CurrentAirPurifierStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/CurrentAirPurifierStateEnum.java new file mode 100644 index 000000000..ce4d8cc0d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/CurrentAirPurifierStateEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.airpurifier; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Inactive” 1 ”Idle” 2 ”Purifying Air” */ +public enum CurrentAirPurifierStateEnum implements CharacteristicEnum { + INACTIVE(0), + IDLE(1), + PURIFYING_AIR(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentAirPurifierStateEnum.values()) + .collect(Collectors.toMap(CurrentAirPurifierStateEnum::getCode, t -> t)); + } + + public static CurrentAirPurifierStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentAirPurifierStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/TargetAirPurifierStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/TargetAirPurifierStateCharacteristic.java new file mode 100644 index 000000000..e8452d655 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/TargetAirPurifierStateCharacteristic.java @@ -0,0 +1,32 @@ +package io.github.hapjava.characteristics.impl.airpurifier; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the target state of the air purifier. See {@link + * TargetAirPurifierStateEnum} for possible values. + */ +public class TargetAirPurifierStateCharacteristic + extends EnumCharacteristic { + + public TargetAirPurifierStateCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000A8-0000-1000-8000-0026BB765291", + "Air purifier state", + TargetAirPurifierStateEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/TargetAirPurifierStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/TargetAirPurifierStateEnum.java new file mode 100644 index 000000000..a20a73e9f --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airpurifier/TargetAirPurifierStateEnum.java @@ -0,0 +1,33 @@ +package io.github.hapjava.characteristics.impl.airpurifier; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Manual” 1 ”Auto” */ +public enum TargetAirPurifierStateEnum implements CharacteristicEnum { + MANUAL(0), + AUTO(1); + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetAirPurifierStateEnum.values()) + .collect(Collectors.toMap(t -> t.getCode(), t -> t)); + } + + public static TargetAirPurifierStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + private TargetAirPurifierStateEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/AirQualityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/AirQualityCharacteristic.java new file mode 100644 index 000000000..448b90383 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/AirQualityCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the air quality. See {@link AirQualityEnum} for possible values. + */ +public class AirQualityCharacteristic extends EnumCharacteristic { + + public AirQualityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000095-0000-1000-8000-0026BB765291", + "air quality", + AirQualityEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/AirQualityEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/AirQualityEnum.java new file mode 100644 index 000000000..390b51dfe --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/AirQualityEnum.java @@ -0,0 +1,39 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Unknown” 1 ”Excellent” 2 ”Good” 3 ”Fair” 4 ”Inferior” 5 ”Poor” */ +public enum AirQualityEnum implements CharacteristicEnum { + UNKNOWN(0), + EXCELLENT(1), + GOOD(2), + FAIR(3), + INFERIOR(4), + POOR(5); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(AirQualityEnum.values()) + .collect(Collectors.toMap(AirQualityEnum::getCode, t -> t)); + } + + public static AirQualityEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + AirQualityEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/NitrogenDioxideDensityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/NitrogenDioxideDensityCharacteristic.java new file mode 100644 index 000000000..1e37e28b6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/NitrogenDioxideDensityCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic contains the current NO2 density in micrograms/m3. */ +public class NitrogenDioxideDensityCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 1000; + public static final double DEFAULT_STEP = 1; + + public NitrogenDioxideDensityCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C4-0000-1000-8000-0026BB765291", + "nitrogen dioxide density", + minValue, + maxValue, + minStep, + "micrograms", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public NitrogenDioxideDensityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/OzoneDensityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/OzoneDensityCharacteristic.java new file mode 100644 index 000000000..577339288 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/OzoneDensityCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic contains the current ozone density in micrograms/m3. */ +public class OzoneDensityCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 1000; + public static final double DEFAULT_STEP = 1; + + public OzoneDensityCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C3-0000-1000-8000-0026BB765291", + "ozone density", + minValue, + maxValue, + minStep, + "micrograms", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public OzoneDensityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/PM10DensityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/PM10DensityCharacteristic.java new file mode 100644 index 000000000..a7b9c1245 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/PM10DensityCharacteristic.java @@ -0,0 +1,44 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic contains the current PM10 micrometer particulate density in micrograms/m3. + */ +public class PM10DensityCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 1000; + public static final double DEFAULT_STEP = 1; + + public PM10DensityCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C7-0000-1000-8000-0026BB765291", + "PM10 density", + minValue, + maxValue, + minStep, + "micrograms", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public PM10DensityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/PM25DensityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/PM25DensityCharacteristic.java new file mode 100644 index 000000000..1667934ef --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/PM25DensityCharacteristic.java @@ -0,0 +1,44 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic contains the current PM2.5 micrometer particulate density in micrograms/m3. + */ +public class PM25DensityCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 1000; + public static final double DEFAULT_STEP = 1; + + public PM25DensityCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C6-0000-1000-8000-0026BB765291", + "PM2.5 density", + minValue, + maxValue, + minStep, + "micrograms", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public PM25DensityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/SulphurDioxideDensityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/SulphurDioxideDensityCharacteristic.java new file mode 100644 index 000000000..81df2c64b --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/SulphurDioxideDensityCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic contains the current SO2 density in micrograms/m3. */ +public class SulphurDioxideDensityCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 1000; + public static final double DEFAULT_STEP = 1; + + public SulphurDioxideDensityCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C5-0000-1000-8000-0026BB765291", + "sulphur dioxide density", + minValue, + maxValue, + minStep, + "micrograms", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public SulphurDioxideDensityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/airquality/VOCDensityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/airquality/VOCDensityCharacteristic.java new file mode 100644 index 000000000..a752161c9 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/airquality/VOCDensityCharacteristic.java @@ -0,0 +1,45 @@ +package io.github.hapjava.characteristics.impl.airquality; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates the current volatile organic compound (VOC) density in + * micrograms/m3. + */ +public class VOCDensityCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 1000; + public static final double DEFAULT_STEP = 1; + + public VOCDensityCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C8-0000-1000-8000-0026BB765291", + "VOC density", + minValue, + maxValue, + minStep, + "micrograms", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public VOCDensityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/audio/MuteCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/audio/MuteCharacteristic.java new file mode 100644 index 000000000..105ca0977 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/audio/MuteCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.audio; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** Mute characteristic to control audio input or output accessory. */ +public class MuteCharacteristic extends BooleanCharacteristic { + public MuteCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000011A-0000-1000-8000-0026BB765291", + "Mute", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/audio/VolumeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/audio/VolumeCharacteristic.java new file mode 100644 index 000000000..2d1caedd7 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/audio/VolumeCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.audio; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** Volume characteristic to control audio volume. */ +public class VolumeCharacteristic extends IntegerCharacteristic implements EventableCharacteristic { + + public VolumeCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000119-0000-1000-8000-0026BB765291", + "volume", + 0, + 100, + "percentage", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/BaseCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java similarity index 64% rename from src/main/java/io/github/hapjava/characteristics/BaseCharacteristic.java rename to src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java index f345c9d8b..0808883bb 100644 --- a/src/main/java/io/github/hapjava/characteristics/BaseCharacteristic.java +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java @@ -1,9 +1,14 @@ -package io.github.hapjava.characteristics; +package io.github.hapjava.characteristics.impl.base; +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; import java.math.BigDecimal; import java.math.BigInteger; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.function.Consumer; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; @@ -17,17 +22,18 @@ * * @author Andy Lintner */ -public abstract class BaseCharacteristic implements Characteristic { +public abstract class BaseCharacteristic implements Characteristic, EventableCharacteristic { private final Logger logger = LoggerFactory.getLogger(BaseCharacteristic.class); private final String type; private final String shortType; private final String format; - private final boolean isWritable; - private final boolean isReadable; - private final boolean isEventable; private final String description; + private final boolean isReadable; + private final boolean isWritable; + private final Optional> subscriber; + private final Optional unsubscriber; /** * Default constructor @@ -39,9 +45,17 @@ public abstract class BaseCharacteristic implements Characteristic { * @param isWritable indicates whether the value can be changed. * @param isReadable indicates whether the value can be retrieved. * @param description a description of the characteristic to be passed to the consuming device. + * @param subscriber subscribes to changes + * @param unsubscriber unsubscribes to changes */ public BaseCharacteristic( - String type, String format, boolean isWritable, boolean isReadable, String description) { + String type, + String format, + String description, + boolean isReadable, + boolean isWritable, + Optional> subscriber, + Optional unsubscriber) { if (type == null || format == null || description == null) { throw new NullPointerException(); } @@ -49,10 +63,17 @@ public BaseCharacteristic( this.type = type; this.shortType = this.type.replaceAll("^0*([0-9a-fA-F]+)-0000-1000-8000-0026BB765291$", "$1"); this.format = format; - this.isWritable = isWritable; - this.isReadable = isReadable; - this.isEventable = this instanceof EventableCharacteristic; this.description = description; + this.isReadable = isReadable; + this.isWritable = isWritable; + this.subscriber = subscriber; + this.unsubscriber = unsubscriber; + } + + @Override + /** {@inheritDoc} */ + public String getType() { + return type; } @Override @@ -62,7 +83,7 @@ public final CompletableFuture toJson(int iid) { } /** - * Creates the JSON serialized form of the accessory for use over the Homekit Accessory Protocol. + * Creates the JSON serialized form of the accessory for use over the HomeKit Accessory Protocol. * * @param instanceId the static id of the accessory. * @return a future that will complete with the JSON builder for the object. @@ -71,26 +92,25 @@ protected CompletableFuture makeBuilder(int instanceId) { CompletableFuture futureValue = getValue(); if (futureValue == null) { - logger.error("Could not retrieve value " + this.getClass().getName()); - return null; + futureValue = CompletableFuture.completedFuture(getDefault()); } return futureValue .exceptionally( t -> { - logger.error("Could not retrieve value " + this.getClass().getName(), t); + logger.warn("Could not retrieve value " + this.getClass().getName(), t); return null; }) .thenApply( value -> { JsonArrayBuilder perms = Json.createArrayBuilder(); - if (isWritable) { - perms.add("pw"); - } if (isReadable) { perms.add("pr"); } - if (isEventable) { + if (isWritable) { + perms.add("pw"); + } + if (subscriber.isPresent()) { perms.add("ev"); } JsonObjectBuilder builder = @@ -98,10 +118,9 @@ protected CompletableFuture makeBuilder(int instanceId) { .add("iid", instanceId) .add("type", shortType) .add("perms", perms.build()) - .add("format", format) - .add("ev", false) - .add("description", description); - setJsonValue(builder, value); + .add("format", format); + if (shortType.length() == type.length()) builder.add("description", description); + if (isReadable) setJsonValue(builder, value); return builder; }); } @@ -109,24 +128,54 @@ protected CompletableFuture makeBuilder(int instanceId) { /** {@inheritDoc} */ @Override public final void setValue(JsonValue jsonValue) { + setValue(jsonValue, null); + } + + /** {@inheritDoc} */ + @Override + public final void setValue(JsonValue jsonValue, String username) { try { - this.setValue(convert(jsonValue)); + setValue(convert(jsonValue), username); } catch (Exception e) { - logger.error("Error while setting JSON value", e); + logger.warn( + "Error while setting JSON value {} for characteristic {} from user {}", + jsonValue, + getClass().getName(), + username, + e); } } /** {@inheritDoc} */ @Override public void supplyValue(JsonObjectBuilder builder) { + CompletableFuture futureValue = getValue(); + + if (futureValue == null) { + setJsonValue(builder, getDefault()); + return; + } + try { - setJsonValue(builder, getValue().get()); + setJsonValue(builder, futureValue.get()); } catch (InterruptedException | ExecutionException e) { - logger.error("Error retrieving value", e); + logger.warn("Error retrieving value", e); setJsonValue(builder, getDefault()); } } + /** {@inheritDoc} */ + @Override + public void subscribe(HomekitCharacteristicChangeCallback callback) { + subscriber.ifPresent(s -> s.accept(callback)); + } + + /** {@inheritDoc} */ + @Override + public void unsubscribe() { + unsubscriber.ifPresent(u -> u.run()); + } + /** * Converts from the JSON value to a Java object of the type T * @@ -141,14 +190,25 @@ public void supplyValue(JsonObjectBuilder builder) { * @param value the new value to set. * @throws Exception if the value cannot be set. */ - protected abstract void setValue(T value) throws Exception; + public abstract void setValue(T value) throws Exception; + + /** + * Update the characteristic value using a new value supplied by the connected client. + * + * @param value the new value to set. + * @param username the authenticated username making the request + * @throws Exception if the value cannot be set. + */ + public void setValue(T value, String username) throws Exception { + setValue(value); + } /** * Retrieves the current value of the characteristic. * * @return a future that will complete with the current value. */ - protected abstract CompletableFuture getValue(); + public abstract CompletableFuture getValue(); /** * Supplies a default value for the characteristic to send to connected clients when the real @@ -156,7 +216,7 @@ public void supplyValue(JsonObjectBuilder builder) { * * @return a sensible default value. */ - protected abstract T getDefault(); + public abstract T getDefault(); /** * Writes the value key to the serialized characteristic diff --git a/src/main/java/io/github/hapjava/characteristics/impl/base/BooleanCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/BooleanCharacteristic.java new file mode 100644 index 000000000..b8c93a4e9 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/BooleanCharacteristic.java @@ -0,0 +1,82 @@ +package io.github.hapjava.characteristics.impl.base; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.json.JsonNumber; +import javax.json.JsonValue; +import javax.json.JsonValue.ValueType; + +/** + * Characteristic that exposes a Boolean value. + * + * @author Andy Lintner + */ +public abstract class BooleanCharacteristic extends BaseCharacteristic { + + private final Optional>> getter; + private final Optional> setter; + + /** + * Default constructor + * + * @param type a string containing a UUID that indicates the type of characteristic. Apple defines + * a set of these, however implementors can create their own as well. + * @param description a description of the characteristic to be passed to the consuming device. + * @param getter getter to retrieve the value + * @param setter setter to set value + * @param subscriber subscriber to subscribe to changes + * @param unsubscriber unsubscriber to unsubscribe from chnages + */ + public BooleanCharacteristic( + String type, + String description, + Optional>> getter, + Optional> setter, + Optional> subscriber, + Optional unsubscriber) { + super( + type, + "bool", + description, + getter.isPresent(), + setter.isPresent(), + subscriber, + unsubscriber); + this.getter = getter; + this.setter = setter; + } + + /** {@inheritDoc} */ + @Override + protected Boolean convert(JsonValue jsonValue) { + if (jsonValue.getValueType().equals(ValueType.NUMBER)) { + return ((JsonNumber) jsonValue).intValue() > 0; + } + return jsonValue.equals(JsonValue.TRUE); + } + + @Override + public CompletableFuture getValue() { + return getter.isPresent() ? getter.map(booleanGetter -> booleanGetter.get()).get() : null; + } + + @Override + public void setValue(Boolean value) throws Exception { + setValue(value, null); + } + + @Override + public void setValue(Boolean value, String username) throws Exception { + if (setter.isPresent()) setter.get().accept(value, username); + } + + /** {@inheritDoc} */ + @Override + public Boolean getDefault() { + return false; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/base/EnumCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/EnumCharacteristic.java new file mode 100644 index 000000000..a12cb0673 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/EnumCharacteristic.java @@ -0,0 +1,162 @@ +package io.github.hapjava.characteristics.impl.base; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.Arrays; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonNumber; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; +import javax.json.JsonValue; + +/** + * Characteristic that exposes an Enum value. Enums are represented as an Integer value in the + * HomeKit protocol, and classes extending this one must handle the static mapping to an Integer + * value. + * + * @author Andy Lintner + */ +public abstract class EnumCharacteristic + extends BaseCharacteristic { + + private final T[] validValues; + protected Optional>> getter; + protected Optional> setter; + + /** + * Default constructor + * + * @param type a string containing a UUID that indicates the type of characteristic. Apple defines + * a set of these, however implementors can create their own as well. + * @param description a description of the characteristic to be passed to the consuming device. + * @param validValues an array of valid values for enum. + * @param getter getter to retrieve the value + * @param setter setter to set value + * @param subscriber subscriber to subscribe to changes + * @param unsubscriber unsubscriber to unsubscribe from chnages + */ + public EnumCharacteristic( + String type, + String description, + T[] validValues, + Optional>> getter, + Optional> setter, + Optional> subscriber, + Optional unsubscriber) { + super( + type, "int", description, getter.isPresent(), setter.isPresent(), subscriber, unsubscriber); + this.getter = getter; + this.setter = setter; + this.validValues = validValues; + } + + /** {@inheritDoc} */ + @Override + protected CompletableFuture makeBuilder(int iid) { + JsonArrayBuilder validValuesBuilder = Json.createArrayBuilder(); + if (validValues != null && validValues.length != 0) { + Arrays.stream(validValues).forEach((T value) -> validValuesBuilder.add(value.getCode())); + } + return super.makeBuilder(iid) + .thenApply( + builder -> { + return builder.add("valid-values", validValuesBuilder); + }); + } + + /** {@inheritDoc} */ + @Override + protected Integer convert(JsonValue jsonValue) { + if (jsonValue instanceof JsonNumber) { + return ((JsonNumber) jsonValue).intValue(); + } else if (jsonValue == JsonObject.TRUE) { + return 1; // For at least one enum type (locks), homekit will send a true instead of 1 + } else if (jsonValue == JsonObject.FALSE) { + return 0; + } else { + throw new IndexOutOfBoundsException("Cannot convert " + jsonValue.getClass() + " to int"); + } + } + + /** + * @return the current value of this characteristic, or null if it has no value or can't be + * fetched + */ + public CompletableFuture getEnumValue() { + if (!getter.isPresent()) { + return null; + } + return getter.get().get(); + } + + @Override + public CompletableFuture getValue() { + if (!getter.isPresent()) { + return null; + } + return getter + .get() + .get() + .thenApply( + e -> { + if (e == null) { + return null; + } + return e.getCode(); + }); + } + + public void setValue(T value) throws Exception { + setValue(value, null); + } + + public void setValue(T value, String username) throws Exception { + if (!setter.isPresent()) { + return; + } + + setter.get().accept(value, username); + } + + @Override + public void setValue(Integer value) throws Exception { + setValue(value, null); + } + + @Override + public void setValue(Integer value, String username) throws Exception { + if (!setter.isPresent()) { + return; + } + + // check if value is in valid values + if (validValues != null && value != null) { + for (T valid : validValues) { + if (valid.getCode() == value) { + setValue(valid, username); + return; + } + } + } + } + + /** {@inheritDoc} */ + @Override + public Integer getDefault() { + // as default return first item from valid values + if (validValues != null && validValues.length > 0) { + return validValues[0].getCode(); + } + return 0; + } + + public T[] getValidValues() { + return validValues; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/FloatCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/FloatCharacteristic.java similarity index 64% rename from src/main/java/io/github/hapjava/characteristics/FloatCharacteristic.java rename to src/main/java/io/github/hapjava/characteristics/impl/base/FloatCharacteristic.java index b3e086cfc..f4b5fa562 100644 --- a/src/main/java/io/github/hapjava/characteristics/FloatCharacteristic.java +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/FloatCharacteristic.java @@ -1,6 +1,11 @@ -package io.github.hapjava.characteristics; +package io.github.hapjava.characteristics.impl.base; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; import javax.json.JsonNumber; import javax.json.JsonObjectBuilder; import javax.json.JsonValue; @@ -20,34 +25,49 @@ public abstract class FloatCharacteristic extends BaseCharacteristic { private final double maxValue; private final double minStep; private final String unit; + private final Optional>> getter; + private final Optional> setter; /** * Default constructor * * @param type a string containing a UUID that indicates the type of characteristic. Apple defines * a set of these, however implementors can create their own as well. - * @param isWritable indicates whether the value can be changed. - * @param isReadable indicates whether the value can be retrieved. * @param description a description of the characteristic to be passed to the consuming device. * @param minValue the minimum supported value. * @param maxValue the maximum supported value * @param minStep the smallest supported step. Values will be rounded to a multiple of this. * @param unit a description of the unit this characteristic supports. + * @param getter getter to retrieve the value + * @param setter setter to set value + * @param subscriber subscriber to subscribe to changes + * @param unsubscriber unsubscriber to unsubscribe from chnages */ public FloatCharacteristic( String type, - boolean isWritable, - boolean isReadable, String description, double minValue, double maxValue, double minStep, - String unit) { - super(type, "float", isWritable, isReadable, description); + String unit, + Optional>> getter, + Optional> setter, + Optional> subscriber, + Optional unsubscriber) { + super( + type, + "float", + description, + getter.isPresent(), + setter.isPresent(), + subscriber, + unsubscriber); this.minValue = minValue; this.maxValue = maxValue; - this.minStep = minStep; this.unit = unit; + this.getter = getter; + this.setter = setter; + this.minStep = minStep; } /** {@inheritDoc} */ @@ -74,9 +94,14 @@ protected Double convert(JsonValue jsonValue) { * the constructor. */ @Override - protected final CompletableFuture getValue() { + public final CompletableFuture getValue() { + if (!getter.isPresent()) { + return null; + } double rounder = 1 / this.minStep; - return getDoubleValue() + return getter + .get() + .get() .thenApply(d -> d == null ? null : Math.round(d * rounder) / rounder) .thenApply( d -> { @@ -103,16 +128,31 @@ protected final CompletableFuture getValue() { }); } + @Override + public void setValue(Double value) throws Exception { + setValue(value, null); + } + + @Override + public void setValue(Double value, String username) throws Exception { + if (setter.isPresent()) setter.get().accept(value, username); + } + /** {@inheritDoc} */ @Override - protected Double getDefault() { + public Double getDefault() { return minValue; } - /** - * Supplies the value of this characteristic as a double. - * - * @return a future that will contain the value. - */ - protected abstract CompletableFuture getDoubleValue(); + public double getMinValue() { + return minValue; + } + + public double getMaxValue() { + return maxValue; + } + + public double getMinStep() { + return minStep; + } } diff --git a/src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java new file mode 100644 index 000000000..6b6cd2982 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java @@ -0,0 +1,146 @@ +package io.github.hapjava.characteristics.impl.base; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.json.JsonNumber; +import javax.json.JsonObjectBuilder; +import javax.json.JsonValue; + +/** + * A characteristic that provides an Integer data type. + * + * @author Andy Lintner + */ +public abstract class IntegerCharacteristic extends BaseCharacteristic { + + private final int minValue; + private final int maxValue; + private final String unit; + private final Optional>> getter; + private final Optional> setter; + + /** + * Default constructor + * + * @param type a string containing a UUID that indicates the type of characteristic. Apple defines + * a set of these, however implementors can create their own as well. + * @param description a description of the characteristic to be passed to the consuming device. + * @param minValue the minimum supported value. + * @param maxValue the maximum supported value + * @param unit a description of the unit this characteristic supports. + * @param getter getter for value + * @param setter setter for value + * @param subscriber subscribers to changes + * @param unsubscriber unsubscribers to changes + */ + public IntegerCharacteristic( + String type, + String description, + int minValue, + int maxValue, + String unit, + Optional>> getter, + Optional> setter, + Optional> subscriber, + Optional unsubscriber) { + this( + type, + "int", + description, + minValue, + maxValue, + unit, + getter, + setter, + subscriber, + unsubscriber); + } + + /** + * Constructor for characteristics whose HAP format differs from the default "int", e.g. "uint8", + * "uint16" or "uint32". Values are still handled as Java {@link Integer}, so the supported range + * must fit into a signed 32-bit integer. + * + * @param type a string containing a UUID that indicates the type of characteristic. Apple defines + * a set of these, however implementors can create their own as well. + * @param format the HAP format to advertise, e.g. "int" or "uint32". + * @param description a description of the characteristic to be passed to the consuming device. + * @param minValue the minimum supported value. + * @param maxValue the maximum supported value + * @param unit a description of the unit this characteristic supports. + * @param getter getter for value + * @param setter setter for value + * @param subscriber subscribers to changes + * @param unsubscriber unsubscribers to changes + */ + protected IntegerCharacteristic( + String type, + String format, + String description, + int minValue, + int maxValue, + String unit, + Optional>> getter, + Optional> setter, + Optional> subscriber, + Optional unsubscriber) { + super( + type, + format, + description, + getter.isPresent(), + setter.isPresent(), + subscriber, + unsubscriber); + this.minValue = minValue; + this.maxValue = maxValue; + this.unit = unit; + this.getter = getter; + this.setter = setter; + } + + /** {@inheritDoc} */ + @Override + protected CompletableFuture makeBuilder(int iid) { + return super.makeBuilder(iid) + .thenApply( + builder -> { + builder.add("minValue", minValue).add("maxValue", maxValue).add("minStep", 1); + if (this.unit != null) { + builder.add("unit", unit); + } + return builder; + }); + } + + @Override + public CompletableFuture getValue() { + return getter.map(integerGetter -> integerGetter.get()).orElse(null); + } + + @Override + public void setValue(Integer value) throws Exception { + setValue(value, null); + } + + @Override + public void setValue(Integer value, String username) throws Exception { + if (setter.isPresent()) setter.get().accept(value, username); + } + + /** {@inheritDoc} */ + @Override + public Integer getDefault() { + return minValue; + } + + /** {@inheritDoc} */ + @Override + protected Integer convert(JsonValue jsonValue) { + return ((JsonNumber) jsonValue).intValue(); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/StaticStringCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/StaticStringCharacteristic.java similarity index 56% rename from src/main/java/io/github/hapjava/characteristics/StaticStringCharacteristic.java rename to src/main/java/io/github/hapjava/characteristics/impl/base/StaticStringCharacteristic.java index 0665d8359..fc5961d4d 100644 --- a/src/main/java/io/github/hapjava/characteristics/StaticStringCharacteristic.java +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/StaticStringCharacteristic.java @@ -1,6 +1,10 @@ -package io.github.hapjava.characteristics; +package io.github.hapjava.characteristics.impl.base; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; import javax.json.JsonObjectBuilder; import javax.json.JsonString; import javax.json.JsonValue; @@ -14,19 +18,25 @@ public class StaticStringCharacteristic extends BaseCharacteristic { private static final int MAX_LEN = 255; - private final String value; - + private final Optional>> getter; /** * Default constructor * * @param type a string containing a UUID that indicates the type of characteristic. Apple defines * a set of these, however implementors can create their own as well. * @param description a description of the characteristic to be passed to the consuming device. - * @param value the value of the static string. + * @param getter getter to retrieve the value + * @param subscriber subscriber to subscribe to changes + * @param unsubscriber unsubscriber to unsubscribe from chnages */ - public StaticStringCharacteristic(String type, String description, String value) { - super(type, "string", false, true, description); - this.value = value; + public StaticStringCharacteristic( + String type, + String description, + Optional>> getter, + Optional> subscriber, + Optional unsubscriber) { + super(type, "string", description, getter.isPresent(), false, subscriber, unsubscriber); + this.getter = getter; } /** {@inheritDoc} */ @@ -49,13 +59,13 @@ public void setValue(String value) throws Exception { /** {@inheritDoc} */ @Override - protected CompletableFuture getValue() { - return CompletableFuture.completedFuture(value).thenApply(s -> s != null ? s : "Unavailable"); + public CompletableFuture getValue() { + return getter.map(stringGetter -> stringGetter.get()).orElse(null); } /** {@inheritDoc} */ @Override - protected String getDefault() { + public String getDefault() { return "Unknown"; } } diff --git a/src/main/java/io/github/hapjava/characteristics/impl/base/StringCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/StringCharacteristic.java new file mode 100644 index 000000000..72ff0afd6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/StringCharacteristic.java @@ -0,0 +1,86 @@ +package io.github.hapjava.characteristics.impl.base; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.json.JsonObjectBuilder; +import javax.json.JsonString; +import javax.json.JsonValue; + +/** + * A characteristic that provides an string value. + * + * @author Eugen Freiter + */ +public class StringCharacteristic extends BaseCharacteristic { + private final Optional>> getter; + private final Optional> setter; + /** + * Default constructor + * + * @param type a string containing a UUID that indicates the type of characteristic. Apple defines + * a set of these, however implementors can create their own as well. + * @param description a description of the characteristic to be passed to the consuming device. + * @param getter getter to retrieve the value + * @param setter setter for value + * @param subscriber subscriber to subscribe to changes + * @param unsubscriber unsubscriber to unsubscribe from chnages + */ + public StringCharacteristic( + String type, + String description, + Optional>> getter, + Optional> setter, + Optional> subscriber, + Optional unsubscriber) { + super( + type, + "string", + description, + getter.isPresent(), + setter.isPresent(), + subscriber, + unsubscriber); + this.getter = getter; + this.setter = setter; + } + + /** {@inheritDoc} */ + @Override + protected CompletableFuture makeBuilder(int iid) { + return super.makeBuilder(iid); + } + + /** {@inheritDoc} */ + @Override + public String convert(JsonValue jsonValue) { + return ((JsonString) jsonValue).getString(); + } + + /** {@inheritDoc} */ + @Override + public void setValue(String value) throws Exception { + setValue(value, null); + } + + /** {@inheritDoc} */ + @Override + public void setValue(String value, String username) throws Exception { + if (setter.isPresent()) setter.get().accept(value, username); + } + + /** {@inheritDoc} */ + @Override + public CompletableFuture getValue() { + return getter.map(stringGetter -> stringGetter.get()).orElse(null); + } + + /** {@inheritDoc} */ + @Override + public String getDefault() { + return "Unknown"; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/battery/BatteryLevelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/battery/BatteryLevelCharacteristic.java new file mode 100644 index 000000000..0fa56ff40 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/battery/BatteryLevelCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.battery; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current level of the battery. */ +public class BatteryLevelCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public BatteryLevelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000068-0000-1000-8000-0026BB765291", + "battery level", + 0, + 100, + "%", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/battery/ChargingStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/battery/ChargingStateCharacteristic.java new file mode 100644 index 000000000..f034e2c3c --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/battery/ChargingStateCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.battery; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the charging state of a battery or an accessory. See {@link + * ChargingStateEnum} for possible values. + */ +public class ChargingStateCharacteristic extends EnumCharacteristic { + + public ChargingStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000008F-0000-1000-8000-0026BB765291", + "Charging state", + ChargingStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/battery/ChargingStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/battery/ChargingStateEnum.java new file mode 100644 index 000000000..d790ff2f7 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/battery/ChargingStateEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.battery; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Not Charging” 1 ”Charging” 2 ”Not Chargeable” */ +public enum ChargingStateEnum implements CharacteristicEnum { + NOT_CHARGING(0), + CHARGING(1), + NOT_CHARABLE(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ChargingStateEnum.values()) + .collect(Collectors.toMap(ChargingStateEnum::getCode, t -> t)); + } + + public static ChargingStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + ChargingStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/battery/StatusLowBatteryCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/battery/StatusLowBatteryCharacteristic.java new file mode 100644 index 000000000..fac7f3ead --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/battery/StatusLowBatteryCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.battery; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes an accessory battery status. See {@link StatusLowBatteryEnum} for + * possible values + */ +public class StatusLowBatteryCharacteristic extends EnumCharacteristic { + + public StatusLowBatteryCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000079-0000-1000-8000-0026BB765291", + "Status Low Battery", + StatusLowBatteryEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/battery/StatusLowBatteryEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/battery/StatusLowBatteryEnum.java new file mode 100644 index 000000000..92981247d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/battery/StatusLowBatteryEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.battery; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Battery level is normal” 1 ”Battery level is low” */ +public enum StatusLowBatteryEnum implements CharacteristicEnum { + NORMAL(0), + LOW(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(StatusLowBatteryEnum.values()) + .collect(Collectors.toMap(StatusLowBatteryEnum::getCode, t -> t)); + } + + public static StatusLowBatteryEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + StatusLowBatteryEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideDetectedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideDetectedCharacteristic.java new file mode 100644 index 000000000..ab327a40e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideDetectedCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.carbondioxidesensor; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates the levels of Carbon Dioxide. See {@link CarbonDioxideDetectedEnum} + * for possible values. + */ +public class CarbonDioxideDetectedCharacteristic + extends EnumCharacteristic implements EventableCharacteristic { + + public CarbonDioxideDetectedCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000092-0000-1000-8000-0026BB765291", + "Carbon Dioxide Detected", + CarbonDioxideDetectedEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideDetectedEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideDetectedEnum.java new file mode 100644 index 000000000..a6fe144b0 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideDetectedEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.carbondioxidesensor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Carbon Dioxide levels are normal” 1 ”Carbon Dioxide levels are abnormal” */ +public enum CarbonDioxideDetectedEnum implements CharacteristicEnum { + NORMAL(0), + ABNORMAL(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CarbonDioxideDetectedEnum.values()) + .collect(Collectors.toMap(CarbonDioxideDetectedEnum::getCode, t -> t)); + } + + public static CarbonDioxideDetectedEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CarbonDioxideDetectedEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideLevelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideLevelCharacteristic.java new file mode 100644 index 000000000..b9b320564 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxideLevelCharacteristic.java @@ -0,0 +1,44 @@ +package io.github.hapjava.characteristics.impl.carbondioxidesensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates the detected level of Carbon Dioxide in parts per million (ppm). + */ +public class CarbonDioxideLevelCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 100000; + public static final double DEFAULT_STEP = 1; + + public CarbonDioxideLevelCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000093-0000-1000-8000-0026BB765291", + "Carbon Dioxide Level", + minValue, + maxValue, + minStep, + "ppm", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CarbonDioxideLevelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxidePeakLevelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxidePeakLevelCharacteristic.java new file mode 100644 index 000000000..1a1793773 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbondioxidesensor/CarbonDioxidePeakLevelCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.carbondioxidesensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic indicates the highest detected level (ppm) of carbon dioxide. */ +public class CarbonDioxidePeakLevelCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 100000; + public static final double DEFAULT_STEP = 1; + + public CarbonDioxidePeakLevelCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000094-0000-1000-8000-0026BB765291", + "Carbon Dioxide Level", + minValue, + maxValue, + minStep, + "ppm", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CarbonDioxidePeakLevelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideDetectedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideDetectedCharacteristic.java new file mode 100644 index 000000000..2ef603b6e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideDetectedCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.carbonmonoxidesensor; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates the levels of Carbon Monoxide. See {@link + * CarbonMonoxideDetectedEnum} for possible values + */ +public class CarbonMonoxideDetectedCharacteristic + extends EnumCharacteristic implements EventableCharacteristic { + + public CarbonMonoxideDetectedCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000069-0000-1000-8000-0026BB765291", + "Carbon Monoxide Detected", + CarbonMonoxideDetectedEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideDetectedEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideDetectedEnum.java new file mode 100644 index 000000000..2d1adf7f0 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideDetectedEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.carbonmonoxidesensor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Carbon Monoxide levels are normal” 1 ”Carbon Monoxide levels are abnormal” */ +public enum CarbonMonoxideDetectedEnum implements CharacteristicEnum { + NORMAL(0), + ABNORMAL(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CarbonMonoxideDetectedEnum.values()) + .collect(Collectors.toMap(CarbonMonoxideDetectedEnum::getCode, t -> t)); + } + + public static CarbonMonoxideDetectedEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CarbonMonoxideDetectedEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideLevelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideLevelCharacteristic.java new file mode 100644 index 000000000..e35171b38 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxideLevelCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.carbonmonoxidesensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic contains the Carbon Monoxide levels in parts per million (ppm). */ +public class CarbonMonoxideLevelCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 100; + public static final double DEFAULT_STEP = 1; + + public CarbonMonoxideLevelCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000090-0000-1000-8000-0026BB765291", + "Carbon Monoxide Level", + minValue, + maxValue, + minStep, + "ppm", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CarbonMonoxideLevelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxidePeakLevelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxidePeakLevelCharacteristic.java new file mode 100644 index 000000000..892901866 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/carbonmonoxidesensor/CarbonMonoxidePeakLevelCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.carbonmonoxidesensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic indicates the highest detected level (ppm) of Carbon Monoxide. */ +public class CarbonMonoxidePeakLevelCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 100; + public static final double DEFAULT_STEP = 1; + + public CarbonMonoxidePeakLevelCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000091-0000-1000-8000-0026BB765291", + "Carbon Monoxide Peak Level", + minValue, + maxValue, + minStep, + "ppm", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CarbonMonoxidePeakLevelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveCharacteristic.java new file mode 100644 index 000000000..0d7fc2c1c --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Active characteristic indicates whether the service is currently active. See {@link ActiveEnum} + * for possible values. + */ +public class ActiveCharacteristic extends EnumCharacteristic { + + public ActiveCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000B0-0000-1000-8000-0026BB765291", + "Active", + ActiveEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveEnum.java new file mode 100644 index 000000000..7fd0318c4 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveEnum.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Inactive” 1 ”Active” 2-255 ”Reserved” */ +public enum ActiveEnum implements CharacteristicEnum { + INACTIVE(0), + ACTIVE(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ActiveEnum.values()).collect(Collectors.toMap(ActiveEnum::getCode, t -> t)); + } + + public static ActiveEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + ActiveEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveIdentifierCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveIdentifierCharacteristic.java new file mode 100644 index 000000000..587c1b666 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ActiveIdentifierCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class ActiveIdentifierCharacteristic extends IntegerCharacteristic { + + public ActiveIdentifierCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000E7-0000-1000-8000-0026BB765291", + "active identifier", + 0, + 1000, + "", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/AirPlayEnableCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/AirPlayEnableCharacteristic.java new file mode 100644 index 000000000..6158f13be --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/AirPlayEnableCharacteristic.java @@ -0,0 +1,32 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** characteristic to control air play. */ +public class AirPlayEnableCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public AirPlayEnableCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000025B-0000-1000-8000-0026BB765291", + "AirPlay enable", + 0, + 1, + "", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ConfiguredNameCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ConfiguredNameCharacteristic.java new file mode 100644 index 000000000..471d5a368 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ConfiguredNameCharacteristic.java @@ -0,0 +1,27 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.StringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes a configured name. */ +public class ConfiguredNameCharacteristic extends StringCharacteristic { + + public ConfiguredNameCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000E3-0000-1000-8000-0026BB765291", + "configured name", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/IdentifierCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/IdentifierCharacteristic.java new file mode 100644 index 000000000..4b8f7613c --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/IdentifierCharacteristic.java @@ -0,0 +1,22 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +public class IdentifierCharacteristic extends IntegerCharacteristic { + + public IdentifierCharacteristic(Supplier> getter) { + super( + "000000E6-0000-1000-8000-0026BB765291", + "identifier", + 0, + 1000, + "", + Optional.of(getter), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/InUseCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/InUseCharacteristic.java new file mode 100644 index 000000000..882c27a01 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/InUseCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates whether the service is in use. See {@link InUseEnum} for possible + * values. + */ +public class InUseCharacteristic extends EnumCharacteristic { + public InUseCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000D2-0000-1000-8000-0026BB765291", + "In Use", + InUseEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/InUseEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/InUseEnum.java new file mode 100644 index 000000000..0b368b128 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/InUseEnum.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Not in use” 1 ”In use” 2-255 ”Reserved” */ +public enum InUseEnum implements CharacteristicEnum { + NOT_IN_USE(0), + IN_USE(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(InUseEnum.values()).collect(Collectors.toMap(InUseEnum::getCode, t -> t)); + } + + public static InUseEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + InUseEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/IsConfiguredCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/IsConfiguredCharacteristic.java new file mode 100644 index 000000000..c016e87c9 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/IsConfiguredCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes whether the service is configured for use. See {@link + * IsConfiguredEnum} for possible values. + */ +public class IsConfiguredCharacteristic extends EnumCharacteristic { + public IsConfiguredCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000D6-0000-1000-8000-0026BB765291", + "Is Configured", + IsConfiguredEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/IsConfiguredEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/IsConfiguredEnum.java new file mode 100644 index 000000000..1d20f6b3b --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/IsConfiguredEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Not Configured” 1 ”Configured” 2-255 ”Reserved” */ +public enum IsConfiguredEnum implements CharacteristicEnum { + NOT_CONFIGURED(0), + CONFIGURED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(IsConfiguredEnum.values()) + .collect(Collectors.toMap(IsConfiguredEnum::getCode, t -> t)); + } + + public static IsConfiguredEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + IsConfiguredEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/NameCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/NameCharacteristic.java new file mode 100644 index 000000000..49c3a824a --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/NameCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.impl.base.StaticStringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** This characteristic describes a name and must not be a null value. */ +public class NameCharacteristic extends StaticStringCharacteristic { + + public NameCharacteristic(Supplier> getter) { + super( + "00000023-0000-1000-8000-0026BB765291", + "name", + Optional.of(getter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ObstructionDetectedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ObstructionDetectedCharacteristic.java new file mode 100644 index 000000000..2644232e3 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ObstructionDetectedCharacteristic.java @@ -0,0 +1,24 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current state of an obstruction sensor. */ +public class ObstructionDetectedCharacteristic extends BooleanCharacteristic { + public ObstructionDetectedCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000024-0000-1000-8000-0026BB765291", + "Obstruction", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/OnCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/OnCharacteristic.java new file mode 100644 index 000000000..99da018b8 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/OnCharacteristic.java @@ -0,0 +1,27 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic represents the states for “on” and “off”. */ +public class OnCharacteristic extends BooleanCharacteristic { + + public OnCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000025-0000-1000-8000-0026BB765291", + "On / Off state", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ProgramModeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgramModeCharacteristic.java new file mode 100644 index 000000000..1580ae392 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgramModeCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes if there are programs scheduled on the accessory. See {@link + * ProgramModeEnum} for possible values. + */ +public class ProgramModeCharacteristic extends EnumCharacteristic { + public ProgramModeCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000D1-0000-1000-8000-0026BB765291", + "Program Mode", + ProgramModeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ProgramModeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgramModeEnum.java new file mode 100644 index 000000000..7924f370b --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgramModeEnum.java @@ -0,0 +1,39 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 0 ”No Programs Scheduled” 1 ”Program Scheduled” 2 ”Program Scheduled, currently overriden to + * manual mode” + */ +public enum ProgramModeEnum implements CharacteristicEnum { + NO_SCHEDULED(0), + SCHEDULED(1), + SCHEDULED_MANUAL(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ProgramModeEnum.values()) + .collect(Collectors.toMap(ProgramModeEnum::getCode, t -> t)); + } + + public static ProgramModeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + ProgramModeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ProgrammableSwitchEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgrammableSwitchEnum.java new file mode 100644 index 000000000..988472a0c --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgrammableSwitchEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Single Press” 1 ”Double Press” 2 ”Long Press” 3-255 ”Reserved” */ +public enum ProgrammableSwitchEnum implements CharacteristicEnum { + SINGLE_PRESS(0), + DOUBLE_PRESS(1), + LONG_PRESS(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ProgrammableSwitchEnum.values()) + .collect(Collectors.toMap(ProgrammableSwitchEnum::getCode, t -> t)); + } + + public static ProgrammableSwitchEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + ProgrammableSwitchEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ProgrammableSwitchEventCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgrammableSwitchEventCharacteristic.java new file mode 100644 index 000000000..b19430100 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ProgrammableSwitchEventCharacteristic.java @@ -0,0 +1,41 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes an event generated by a programmable switch. For BLE accessories, + * read request should return the last event. For IP accessory, read request must return "null". The + * changes are reported via events + * + *

See {@link ProgrammableSwitchEnum} for possible values. + */ +public class ProgrammableSwitchEventCharacteristic + extends EnumCharacteristic { + + public ProgrammableSwitchEventCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(ProgrammableSwitchEnum.values(), getter, subscriber, unsubscriber); + } + + public ProgrammableSwitchEventCharacteristic( + ProgrammableSwitchEnum[] validValues, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000073-0000-1000-8000-0026BB765291", + "Switch Event", + validValues, + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelIndexCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelIndexCharacteristic.java new file mode 100644 index 000000000..522cb04fe --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelIndexCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** + * This characteristic is used to identify the index of the label according to {@link + * ServiceLabelNamespaceCharacteristic} + */ +public class ServiceLabelIndexCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public ServiceLabelIndexCharacteristic(Supplier> getter) { + super( + "000000CB-0000-1000-8000-0026BB765291", + "service label index", + 0, + 100, + "%", + Optional.of(getter), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelNamespaceCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelNamespaceCharacteristic.java new file mode 100644 index 000000000..9f8dd3248 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelNamespaceCharacteristic.java @@ -0,0 +1,25 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** + * This characteristic describes the naming schema for an accessory. See {@link + * ServiceLabelNamespaceEnum} for possible values. + */ +public class ServiceLabelNamespaceCharacteristic + extends EnumCharacteristic { + public ServiceLabelNamespaceCharacteristic( + Supplier> getter) { + super( + "000000CD-0000-1000-8000-0026BB765291", + "service label namespace", + ServiceLabelNamespaceEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelNamespaceEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelNamespaceEnum.java new file mode 100644 index 000000000..a9b2df513 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/ServiceLabelNamespaceEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Dots. For e.g ”.” ”..” ”...” ”....”” 1 ”Arabic numerals. For e.g. 0,1,2,3” */ +public enum ServiceLabelNamespaceEnum implements CharacteristicEnum { + DOTS(0), + ARABIC_NUMERALS(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ServiceLabelNamespaceEnum.values()) + .collect(Collectors.toMap(ServiceLabelNamespaceEnum::getCode, t -> t)); + } + + public static ServiceLabelNamespaceEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + ServiceLabelNamespaceEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/StatusActiveCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusActiveCharacteristic.java new file mode 100644 index 000000000..a242ae6a1 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusActiveCharacteristic.java @@ -0,0 +1,24 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes current working (active and functional) status of accessory. */ +public class StatusActiveCharacteristic extends BooleanCharacteristic { + public StatusActiveCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000075-0000-1000-8000-0026BB765291", + "Active status", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/StatusFaultCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusFaultCharacteristic.java new file mode 100644 index 000000000..5754e11a8 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusFaultCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes fault status. See {@link StatusFaultEnum} for possible values. */ +public class StatusFaultCharacteristic extends EnumCharacteristic { + + public StatusFaultCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000077-0000-1000-8000-0026BB765291", + "Status Fault", + StatusFaultEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/StatusFaultEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusFaultEnum.java new file mode 100644 index 000000000..4fd866847 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusFaultEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”No Fault” 1 ”General Fault” */ +public enum StatusFaultEnum implements CharacteristicEnum { + NO_FAULT(0), + GENERAL_FAULT(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(StatusFaultEnum.values()) + .collect(Collectors.toMap(StatusFaultEnum::getCode, t -> t)); + } + + public static StatusFaultEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + StatusFaultEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/StatusTamperedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusTamperedCharacteristic.java new file mode 100644 index 000000000..501bbaedb --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusTamperedCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes tampered status. See {@link StatusTamperedEnum} for possible + * values. + */ +public class StatusTamperedCharacteristic extends EnumCharacteristic { + + public StatusTamperedCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000007A-0000-1000-8000-0026BB765291", + "Status Tampered", + StatusTamperedEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/StatusTamperedEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusTamperedEnum.java new file mode 100644 index 000000000..2d725c132 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/StatusTamperedEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Accessory is not tampered” 1 ”Accessory is tampered with” */ +public enum StatusTamperedEnum implements CharacteristicEnum { + NOT_TAMPERED(0), + TAMPERED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(StatusTamperedEnum.values()) + .collect(Collectors.toMap(StatusTamperedEnum::getCode, t -> t)); + } + + public static StatusTamperedEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + StatusTamperedEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/VersionCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/VersionCharacteristic.java new file mode 100644 index 000000000..75c8aaf9e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/VersionCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.impl.base.StaticStringCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** This characteristic describes HAP version. */ +public class VersionCharacteristic extends StaticStringCharacteristic { + + public VersionCharacteristic(Supplier> getter) { + super( + "00000037-0000-1000-8000-0026BB765291", + "HAP version", + Optional.of(getter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/common/WaterLavelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/common/WaterLavelCharacteristic.java new file mode 100644 index 000000000..dda11b087 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/common/WaterLavelCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.common; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the water level. */ +public class WaterLavelCharacteristic extends FloatCharacteristic + implements EventableCharacteristic { + + public WaterLavelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000B5-0000-1000-8000-0026BB765291", + "water level", + 0, + 100, + 1, + "%", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/contactsensor/ContactSensorStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/contactsensor/ContactSensorStateCharacteristic.java new file mode 100644 index 000000000..8ac3c1fde --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/contactsensor/ContactSensorStateCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.contactsensor; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the state of a door/window contact sensor. See {@link + * ContactStateEnum} for possible values. + */ +public class ContactSensorStateCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public ContactSensorStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000006A-0000-1000-8000-0026BB765291", + "Contact Sensor", + ContactStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/contactsensor/ContactStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/contactsensor/ContactStateEnum.java new file mode 100644 index 000000000..275ed9734 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/contactsensor/ContactStateEnum.java @@ -0,0 +1,37 @@ +package io.github.hapjava.characteristics.impl.contactsensor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/* + * 0 ”Contact is detected” + * 1 ”Contact is not detected” + */ +public enum ContactStateEnum implements CharacteristicEnum { + DETECTED(0), + NOT_DETECTED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ContactStateEnum.values()) + .collect(Collectors.toMap(ContactStateEnum::getCode, t -> t)); + } + + public static ContactStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + ContactStateEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/CurrentFanStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/CurrentFanStateCharacteristic.java new file mode 100644 index 000000000..75f932e50 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/CurrentFanStateCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the current state of the fan. See {@link CurrentFanStateEnum} for + * possible values. + */ +public class CurrentFanStateCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public CurrentFanStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000AF-0000-1000-8000-0026BB765291", + "Current Fan State", + CurrentFanStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/CurrentFanStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/CurrentFanStateEnum.java new file mode 100644 index 000000000..674924e9a --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/CurrentFanStateEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum CurrentFanStateEnum implements CharacteristicEnum { + INACTIVE(0), + IDLE(1), + BLOWING_AIR(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentFanStateEnum.values()) + .collect(Collectors.toMap(CurrentFanStateEnum::getCode, t -> t)); + } + + public static CurrentFanStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentFanStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/LockPhysicalControlsCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/LockPhysicalControlsCharacteristic.java new file mode 100644 index 000000000..8ea6f35c6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/LockPhysicalControlsCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes physical controls on an accessory (eg. child lock). */ +public class LockPhysicalControlsCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public LockPhysicalControlsCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000A7-0000-1000-8000-0026BB765291", + "Physical Locks", + LockPhysicalControlsEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/LockPhysicalControlsEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/LockPhysicalControlsEnum.java new file mode 100644 index 000000000..87503ed96 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/LockPhysicalControlsEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Control lock disabled” 1 ”Control lock enabled” */ +public enum LockPhysicalControlsEnum implements CharacteristicEnum { + CONTROL_LOCK_DISABLED(0), + CONTROL_LOCK_ENABLED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(LockPhysicalControlsEnum.values()) + .collect(Collectors.toMap(LockPhysicalControlsEnum::getCode, t -> t)); + } + + public static LockPhysicalControlsEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + LockPhysicalControlsEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationDirectionCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationDirectionCharacteristic.java new file mode 100644 index 000000000..efa82681f --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationDirectionCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the direction of rotation of a fan. */ +public class RotationDirectionCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public RotationDirectionCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000028-0000-1000-8000-0026BB765291", + "Rotation direction", + RotationDirectionEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationDirectionEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationDirectionEnum.java new file mode 100644 index 000000000..20651fd1c --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationDirectionEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Clockwise” 1 ”Counter-clockwise” 2-255 ”Reserved” */ +public enum RotationDirectionEnum implements CharacteristicEnum { + CLOCKWISE(0), + COUNTER_CLOCKWISE(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(RotationDirectionEnum.values()) + .collect(Collectors.toMap(RotationDirectionEnum::getCode, t -> t)); + } + + public static RotationDirectionEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + RotationDirectionEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationSpeedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationSpeedCharacteristic.java new file mode 100644 index 000000000..d7a1d6929 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/RotationSpeedCharacteristic.java @@ -0,0 +1,54 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the rotation speed of a fan. */ +public class RotationSpeedCharacteristic extends FloatCharacteristic + implements EventableCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 100; + public static final double DEFAULT_STEP = 1; + + public RotationSpeedCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000029-0000-1000-8000-0026BB765291", + "Rotation Speed", + minValue, + maxValue, + minStep, + "%", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public RotationSpeedCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this( + DEFAULT_MIN_VALUE, + DEFAULT_MAX_VALUE, + DEFAULT_STEP, + getter, + setter, + subscriber, + unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/SwingModeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/SwingModeCharacteristic.java new file mode 100644 index 000000000..ba58dfd0f --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/SwingModeCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes if swing mode is enabled. */ +public class SwingModeCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public SwingModeCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000B6-0000-1000-8000-0026BB765291", + "Swing Mode", + SwingModeEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/SwingModeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/SwingModeEnum.java new file mode 100644 index 000000000..928bafd27 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/SwingModeEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Swing disabled” 1 ”Swing enabled” */ +public enum SwingModeEnum implements CharacteristicEnum { + SWING_DISABLED(0), + SWING_ENABLED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(SwingModeEnum.values()) + .collect(Collectors.toMap(SwingModeEnum::getCode, t -> t)); + } + + public static SwingModeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + SwingModeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/TargetFanStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/TargetFanStateCharacteristic.java new file mode 100644 index 000000000..1ab9ca305 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/TargetFanStateCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target state of the fan. */ +public class TargetFanStateCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public TargetFanStateCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000BF-0000-1000-8000-0026BB765291", + "Target Fan State", + TargetFanStateEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/fan/TargetFanStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/fan/TargetFanStateEnum.java new file mode 100644 index 000000000..600f07401 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/fan/TargetFanStateEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.fan; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Manual” 1 ”Auto” */ +public enum TargetFanStateEnum implements CharacteristicEnum { + MANUAL(0), + AUTO(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetFanStateEnum.values()) + .collect(Collectors.toMap(TargetFanStateEnum::getCode, t -> t)); + } + + public static TargetFanStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + TargetFanStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterChangeIndicationCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterChangeIndicationCharacteristic.java new file mode 100644 index 000000000..31ccbb25e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterChangeIndicationCharacteristic.java @@ -0,0 +1,27 @@ +package io.github.hapjava.characteristics.impl.filtermaintenance; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class FilterChangeIndicationCharacteristic + extends EnumCharacteristic implements EventableCharacteristic { + + public FilterChangeIndicationCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000AC-0000-1000-8000-0026BB765291", + "filter change indication", + FilterChangeIndicationEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterChangeIndicationEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterChangeIndicationEnum.java new file mode 100644 index 000000000..03d610afb --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterChangeIndicationEnum.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.filtermaintenance; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum FilterChangeIndicationEnum implements CharacteristicEnum { + NO_CHANGE_NEEDED(0), + CHANGE_NEEDED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(FilterChangeIndicationEnum.values()) + .collect(Collectors.toMap(FilterChangeIndicationEnum::getCode, t -> t)); + } + + public static FilterChangeIndicationEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + FilterChangeIndicationEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterLifeLevelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterLifeLevelCharacteristic.java new file mode 100644 index 000000000..29cdf8d6e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/FilterLifeLevelCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.filtermaintenance; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class FilterLifeLevelCharacteristic extends FloatCharacteristic + implements EventableCharacteristic { + + public FilterLifeLevelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000AB-0000-1000-8000-0026BB765291", + "Filter Life Level", + 0, + 100, + 1, + "%", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/ResetFilterIndicationCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/ResetFilterIndicationCharacteristic.java new file mode 100644 index 000000000..10d06bf96 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/filtermaintenance/ResetFilterIndicationCharacteristic.java @@ -0,0 +1,21 @@ +package io.github.hapjava.characteristics.impl.filtermaintenance; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; + +public class ResetFilterIndicationCharacteristic extends IntegerCharacteristic { + + public ResetFilterIndicationCharacteristic(ExceptionalConsumer setter) { + super( + "000000AD-0000-1000-8000-0026BB765291", + "Reset Filter Indication", + 1, + 1, + null, + Optional.empty(), + Optional.of(setter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/CurrentDoorStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/CurrentDoorStateCharacteristic.java new file mode 100644 index 000000000..e06937daa --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/CurrentDoorStateCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.garagedoor; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current state of a door. */ +public class CurrentDoorStateCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public CurrentDoorStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000000E-0000-1000-8000-0026BB765291", + "Current Door State", + CurrentDoorStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/CurrentDoorStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/CurrentDoorStateEnum.java new file mode 100644 index 000000000..88474e6cc --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/CurrentDoorStateEnum.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.garagedoor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 0 ”Open. The door is fully open.” 1 ”Closed. The door is fully closed.” 2 ”Opening. The door is + * actively opening.” 3 ”Closing. The door is actively closing.” 4 ”Stopped. The door is not moving, + * and it is not fully open nor fully closed.” + */ +public enum CurrentDoorStateEnum implements CharacteristicEnum { + OPEN(0), + CLOSED(1), + OPENING(2), + CLOSING(3), + STOPPED(4); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentDoorStateEnum.values()) + .collect(Collectors.toMap(CurrentDoorStateEnum::getCode, t -> t)); + } + + public static CurrentDoorStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentDoorStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/TargetDoorStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/TargetDoorStateCharacteristic.java new file mode 100644 index 000000000..f5b490c6e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/TargetDoorStateCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.garagedoor; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target state of a door. */ +public class TargetDoorStateCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public TargetDoorStateCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000032-0000-1000-8000-0026BB765291", + "Target Door State", + TargetDoorStateEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/TargetDoorStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/TargetDoorStateEnum.java new file mode 100644 index 000000000..ca282fdc3 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/garagedoor/TargetDoorStateEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.garagedoor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Open” 1 ”Closed” 2-255 ”Reserved” */ +public enum TargetDoorStateEnum implements CharacteristicEnum { + OPEN(0), + CLOSED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetDoorStateEnum.values()) + .collect(Collectors.toMap(TargetDoorStateEnum::getCode, t -> t)); + } + + public static TargetDoorStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + TargetDoorStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/CurrentHeaterCoolerStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/CurrentHeaterCoolerStateCharacteristic.java new file mode 100644 index 000000000..f7d48bae6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/CurrentHeaterCoolerStateCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.heatercooler; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current state of a heater cooler. */ +public class CurrentHeaterCoolerStateCharacteristic + extends EnumCharacteristic implements EventableCharacteristic { + + public CurrentHeaterCoolerStateCharacteristic( + CurrentHeaterCoolerStateEnum[] validValues, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000B1-0000-1000-8000-0026BB765291", + "current heater cooler state", + validValues, + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/CurrentHeaterCoolerStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/CurrentHeaterCoolerStateEnum.java new file mode 100644 index 000000000..9864acb12 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/CurrentHeaterCoolerStateEnum.java @@ -0,0 +1,37 @@ +package io.github.hapjava.characteristics.impl.heatercooler; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Inactive” 1 ”Idle” 2 ”Heating” 3 ”Cooling” */ +public enum CurrentHeaterCoolerStateEnum implements CharacteristicEnum { + INACTIVE(0), + IDLE(1), + HEATING(2), + COOLING(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentHeaterCoolerStateEnum.values()) + .collect(Collectors.toMap(CurrentHeaterCoolerStateEnum::getCode, t -> t)); + } + + public static CurrentHeaterCoolerStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentHeaterCoolerStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/TargetHeaterCoolerStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/TargetHeaterCoolerStateCharacteristic.java new file mode 100644 index 000000000..a9a167d45 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/TargetHeaterCoolerStateCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.heatercooler; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target state of heater cooler. */ +public class TargetHeaterCoolerStateCharacteristic + extends EnumCharacteristic implements EventableCharacteristic { + + public TargetHeaterCoolerStateCharacteristic( + TargetHeaterCoolerStateEnum[] validValues, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000B2-0000-1000-8000-0026BB765291", + "target heater cooler state", + validValues, + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/TargetHeaterCoolerStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/TargetHeaterCoolerStateEnum.java new file mode 100644 index 000000000..a16d3cd6a --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/heatercooler/TargetHeaterCoolerStateEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.heatercooler; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 AUTO - ”Heat or Cool” 1 ”Heat” 2 ”Cool” */ +public enum TargetHeaterCoolerStateEnum implements CharacteristicEnum { + AUTO(0), + HEAT(1), + COOL(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetHeaterCoolerStateEnum.values()) + .collect(Collectors.toMap(TargetHeaterCoolerStateEnum::getCode, t -> t)); + } + + public static TargetHeaterCoolerStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + TargetHeaterCoolerStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humidifier/CurrentHumidifierDehumidifierStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/CurrentHumidifierDehumidifierStateCharacteristic.java new file mode 100644 index 000000000..229d0aa73 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/CurrentHumidifierDehumidifierStateCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.humidifier; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current state of a humidifier or/and a dehumidifier. */ +public class CurrentHumidifierDehumidifierStateCharacteristic + extends EnumCharacteristic + implements EventableCharacteristic { + + public CurrentHumidifierDehumidifierStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000B3-0000-1000-8000-0026BB765291", + "current humidifier state", + CurrentHumidifierDehumidifierStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humidifier/CurrentHumidifierDehumidifierStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/CurrentHumidifierDehumidifierStateEnum.java new file mode 100644 index 000000000..d6ec775de --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/CurrentHumidifierDehumidifierStateEnum.java @@ -0,0 +1,37 @@ +package io.github.hapjava.characteristics.impl.humidifier; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Inactive” 1 ”Idle” 2 ”Humidifying” 3 ”Dehumidifying” */ +public enum CurrentHumidifierDehumidifierStateEnum implements CharacteristicEnum { + INACTIVE(0), + IDLE(1), + HUMIDIFYING(2), + DEHUMIDIFYING(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentHumidifierDehumidifierStateEnum.values()) + .collect(Collectors.toMap(CurrentHumidifierDehumidifierStateEnum::getCode, t -> t)); + } + + public static CurrentHumidifierDehumidifierStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentHumidifierDehumidifierStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humidifier/HumidityDehumidifierThresholdCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/HumidityDehumidifierThresholdCharacteristic.java new file mode 100644 index 000000000..b8a4ca569 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/HumidityDehumidifierThresholdCharacteristic.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.humidifier; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the relative humidity dehumidifier threshold on which dehumidifier + * turns on. + */ +public class HumidityDehumidifierThresholdCharacteristic extends FloatCharacteristic { + + public HumidityDehumidifierThresholdCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C9-0000-1000-8000-0026BB765291", + "humidity threshold dehumidifier", + 0, + 100, + 1, + "%", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humidifier/HumidityHumidifierThresholdCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/HumidityHumidifierThresholdCharacteristic.java new file mode 100644 index 000000000..2ee8adbf2 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/HumidityHumidifierThresholdCharacteristic.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.humidifier; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the relative humidity humidifier threshold on which humidifier + * turns on. + */ +public class HumidityHumidifierThresholdCharacteristic extends FloatCharacteristic { + + public HumidityHumidifierThresholdCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000CA-0000-1000-8000-0026BB765291", + "humidity threshold humidifier", + 0, + 100, + 1, + "%", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humidifier/TargetHumidifierDehumidifierStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/TargetHumidifierDehumidifierStateCharacteristic.java new file mode 100644 index 000000000..4b4a90a54 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/TargetHumidifierDehumidifierStateCharacteristic.java @@ -0,0 +1,32 @@ +package io.github.hapjava.characteristics.impl.humidifier; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target state of a humidifier or/and a dehumidifier.. */ +public class TargetHumidifierDehumidifierStateCharacteristic + extends EnumCharacteristic + implements EventableCharacteristic { + + public TargetHumidifierDehumidifierStateCharacteristic( + TargetHumidifierDehumidifierStateEnum[] validValues, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000B4-0000-1000-8000-0026BB765291", + "target humidifier state", + validValues, + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humidifier/TargetHumidifierDehumidifierStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/TargetHumidifierDehumidifierStateEnum.java new file mode 100644 index 000000000..3d4fee0a5 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humidifier/TargetHumidifierDehumidifierStateEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.humidifier; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 - Auto - ”Humidifier or Dehumidifier” 1 ”Humidifier” 2 ”Dehumidifier” */ +public enum TargetHumidifierDehumidifierStateEnum implements CharacteristicEnum { + AUTO(0), + HUMIDIFIER(1), + DEHUMIDIFIER(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetHumidifierDehumidifierStateEnum.values()) + .collect(Collectors.toMap(TargetHumidifierDehumidifierStateEnum::getCode, t -> t)); + } + + public static TargetHumidifierDehumidifierStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + TargetHumidifierDehumidifierStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humiditysensor/CurrentRelativeHumidityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/humiditysensor/CurrentRelativeHumidityCharacteristic.java new file mode 100644 index 000000000..be77125b6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humiditysensor/CurrentRelativeHumidityCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.humiditysensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current relative humidity. */ +public class CurrentRelativeHumidityCharacteristic extends FloatCharacteristic { + + public CurrentRelativeHumidityCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000010-0000-1000-8000-0026BB765291", + "Current Relative Humidity", + 0, + 100, + 1, + "%", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/humiditysensor/TargetRelativeHumidityCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/humiditysensor/TargetRelativeHumidityCharacteristic.java new file mode 100644 index 000000000..ab8ad7e29 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/humiditysensor/TargetRelativeHumidityCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.humiditysensor; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target relative humidity. */ +public class TargetRelativeHumidityCharacteristic extends FloatCharacteristic { + + public TargetRelativeHumidityCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000034-0000-1000-8000-0026BB765291", + "Target Relative Humidity", + 0, + 100, + 1, + "%", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/CurrentVisibilityStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/CurrentVisibilityStateCharacteristic.java new file mode 100644 index 000000000..65c358a3f --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/CurrentVisibilityStateCharacteristic.java @@ -0,0 +1,27 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes current visibility state. */ +public class CurrentVisibilityStateCharacteristic + extends EnumCharacteristic { + + public CurrentVisibilityStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000135-0000-1000-8000-0026BB765291", + "current visibility state", + CurrentVisibilityStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/CurrentVisibilityStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/CurrentVisibilityStateEnum.java new file mode 100644 index 000000000..2159393d8 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/CurrentVisibilityStateEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum CurrentVisibilityStateEnum implements CharacteristicEnum { + SHOWN(0), + HIDDEN(1), + UNKNOWN_1(2), + UNKNOWN_2(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentVisibilityStateEnum.values()) + .collect(Collectors.toMap(CurrentVisibilityStateEnum::getCode, t -> t)); + } + + public static CurrentVisibilityStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentVisibilityStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputDeviceTypeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputDeviceTypeCharacteristic.java new file mode 100644 index 000000000..51a6fbde5 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputDeviceTypeCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes input device type. */ +public class InputDeviceTypeCharacteristic extends EnumCharacteristic { + + public InputDeviceTypeCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000DC-0000-1000-8000-0026BB765291", + "input device type", + InputDeviceTypeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputDeviceTypeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputDeviceTypeEnum.java new file mode 100644 index 000000000..5c7337174 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputDeviceTypeEnum.java @@ -0,0 +1,38 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum InputDeviceTypeEnum implements CharacteristicEnum { + OTHER(0), + TV(1), + RECORDING(2), + TUNER(3), + PLAYBACK(4), + AUDIO_SYSTEM(5); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(InputDeviceTypeEnum.values()) + .collect(Collectors.toMap(InputDeviceTypeEnum::getCode, t -> t)); + } + + public static InputDeviceTypeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + InputDeviceTypeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputSourceTypeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputSourceTypeCharacteristic.java new file mode 100644 index 000000000..91134891b --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputSourceTypeCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes input source type. */ +public class InputSourceTypeCharacteristic extends EnumCharacteristic { + + public InputSourceTypeCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000DB-0000-1000-8000-0026BB765291", + "input source type", + InputSourceTypeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputSourceTypeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputSourceTypeEnum.java new file mode 100644 index 000000000..94545ec18 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/InputSourceTypeEnum.java @@ -0,0 +1,43 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum InputSourceTypeEnum implements CharacteristicEnum { + OTHER(0), + HOME_SCREEN(1), + TUNER(2), + HDMI(3), + COMPOSITE_VIDEO(4), + S_VIDEO(5), + COMPONENT_VIDEO(6), + DVI(7), + AIRPLAY(8), + USB(9), + APPLICATION(10); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(InputSourceTypeEnum.values()) + .collect(Collectors.toMap(InputSourceTypeEnum::getCode, t -> t)); + } + + public static InputSourceTypeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + InputSourceTypeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/TargetVisibilityStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/TargetVisibilityStateCharacteristic.java new file mode 100644 index 000000000..ea466d182 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/TargetVisibilityStateCharacteristic.java @@ -0,0 +1,29 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes target visibility state. */ +public class TargetVisibilityStateCharacteristic + extends EnumCharacteristic { + + public TargetVisibilityStateCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000134-0000-1000-8000-0026BB765291", + "target visibility state", + TargetVisibilityStateEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/inputsource/TargetVisibilityStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/TargetVisibilityStateEnum.java new file mode 100644 index 000000000..6a75b0c30 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/inputsource/TargetVisibilityStateEnum.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.inputsource; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum TargetVisibilityStateEnum implements CharacteristicEnum { + SHOWN(0), + HIDDEN(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetVisibilityStateEnum.values()) + .collect(Collectors.toMap(TargetVisibilityStateEnum::getCode, t -> t)); + } + + public static TargetVisibilityStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + TargetVisibilityStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/leaksensor/LeakDetectedStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/leaksensor/LeakDetectedStateCharacteristic.java new file mode 100644 index 000000000..ca0a2043e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/leaksensor/LeakDetectedStateCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.leaksensor; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates if a sensor detected a leak (e.g. water leak, gas leak). See {@link + * LeakDetectedStateEnum} for possible values + */ +public class LeakDetectedStateCharacteristic extends EnumCharacteristic + implements EventableCharacteristic { + + public LeakDetectedStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000070-0000-1000-8000-0026BB765291", + "Leak Detected State", + LeakDetectedStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/leaksensor/LeakDetectedStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/leaksensor/LeakDetectedStateEnum.java new file mode 100644 index 000000000..1708230c8 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/leaksensor/LeakDetectedStateEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.leaksensor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Leak is not detected” 1 ”Leak is detected” */ +public enum LeakDetectedStateEnum implements CharacteristicEnum { + LEAK_NOT_DETECTED(0), + LEAK_DETECTED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(LeakDetectedStateEnum.values()) + .collect(Collectors.toMap(LeakDetectedStateEnum::getCode, t -> t)); + } + + public static LeakDetectedStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + LeakDetectedStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/BrightnessCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/BrightnessCharacteristic.java new file mode 100644 index 000000000..693e42efc --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/BrightnessCharacteristic.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes a perceived level of brightness, The value is a percentage (%) of + * the maximum level of supported brightness. + */ +public class BrightnessCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public BrightnessCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000008-0000-1000-8000-0026BB765291", + "level of brightness", + 0, + 100, + "%", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/ColorTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/ColorTemperatureCharacteristic.java new file mode 100644 index 000000000..987ab5eee --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/ColorTemperatureCharacteristic.java @@ -0,0 +1,44 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes color temperature in mireds */ +public class ColorTemperatureCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + public static final int DEFAULT_MIN_VALUE = 50; + public static final int DEFAULT_MAX_VALUE = 400; + + public ColorTemperatureCharacteristic( + int minValue, + int maxValue, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000CE-0000-1000-8000-0026BB765291", + "color temperature", + minValue, + maxValue, + "mired", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public ColorTemperatureCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, getter, setter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/HueCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/HueCharacteristic.java new file mode 100644 index 000000000..7a00816bc --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/HueCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes hue or color. */ +public class HueCharacteristic extends FloatCharacteristic { + public HueCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000013-0000-1000-8000-0026BB765291", + "hue or color", + 0, + 360, + 1, + "arcdegrees", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/SaturationCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/SaturationCharacteristic.java new file mode 100644 index 000000000..90694ef98 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/SaturationCharacteristic.java @@ -0,0 +1,33 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes color saturation. */ +public class SaturationCharacteristic extends FloatCharacteristic + implements EventableCharacteristic { + + public SaturationCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000002F-0000-1000-8000-0026BB765291", + "color saturation", + 0, + 100, + 1, + "%", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightsensor/CurrentAmbientLightLevelCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lightsensor/CurrentAmbientLightLevelCharacteristic.java new file mode 100644 index 000000000..afec35ce6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightsensor/CurrentAmbientLightLevelCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.lightsensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic indicates the current light level in Lux */ +public class CurrentAmbientLightLevelCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0.0001; + public static final double DEFAULT_MAX_VALUE = 100000; + public static final double DEFAULT_STEP = 0.0001; + + public CurrentAmbientLightLevelCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000006B-0000-1000-8000-0026BB765291", + "ambient light level", + minValue, + maxValue, + minStep, + "lux", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CurrentAmbientLightLevelCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lock/LockCurrentStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockCurrentStateCharacteristic.java new file mode 100644 index 000000000..b6946313b --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockCurrentStateCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.lock; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** The current state of the physical security mechanism (e.g. deadbolt). */ +public class LockCurrentStateCharacteristic extends EnumCharacteristic { + + public LockCurrentStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000001D-0000-1000-8000-0026BB765291", + "Current Lock State", + LockCurrentStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lock/LockCurrentStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockCurrentStateEnum.java new file mode 100644 index 000000000..66eb23afe --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockCurrentStateEnum.java @@ -0,0 +1,37 @@ +package io.github.hapjava.characteristics.impl.lock; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Unsecured” 1 ”Secured” 2 ”Jammed” 3 ”Unknown” 4-255 ”Reserved” */ +public enum LockCurrentStateEnum implements CharacteristicEnum { + UNSECURED(0), + SECURED(1), + JAMMED(2), + UNKNOWN(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(LockCurrentStateEnum.values()) + .collect(Collectors.toMap(LockCurrentStateEnum::getCode, t -> t)); + } + + public static LockCurrentStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + LockCurrentStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lock/LockTargetStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockTargetStateCharacteristic.java new file mode 100644 index 000000000..c46a4eab5 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockTargetStateCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.lock; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** The target state of the physical security mechanism (e.g. deadbolt). */ +public class LockTargetStateCharacteristic extends EnumCharacteristic { + + public LockTargetStateCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000001E-0000-1000-8000-0026BB765291", + "Target Lock State", + LockTargetStateEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lock/LockTargetStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockTargetStateEnum.java new file mode 100644 index 000000000..d5aa0d536 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lock/LockTargetStateEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.lock; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Unsecured” 1 ”Secured” 4-255 ”Reserved” */ +public enum LockTargetStateEnum implements CharacteristicEnum { + UNSECURED(0), + SECURED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(LockTargetStateEnum.values()) + .collect(Collectors.toMap(LockTargetStateEnum::getCode, t -> t)); + } + + public static LockTargetStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + LockTargetStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/motionsensor/MotionDetectedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/motionsensor/MotionDetectedCharacteristic.java new file mode 100644 index 000000000..4be591bec --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/motionsensor/MotionDetectedCharacteristic.java @@ -0,0 +1,25 @@ +package io.github.hapjava.characteristics.impl.motionsensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic indicates if motion (e.g. a person moving) was detected. */ +public class MotionDetectedCharacteristic extends BooleanCharacteristic { + + public MotionDetectedCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000022-0000-1000-8000-0026BB765291", + "Motion detection", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/occupancysensor/OccupancyDetectedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/occupancysensor/OccupancyDetectedCharacteristic.java new file mode 100644 index 000000000..0057b0968 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/occupancysensor/OccupancyDetectedCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.occupancysensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic indicates if occupancy was detected (e.g. a person present). */ +public class OccupancyDetectedCharacteristic extends EnumCharacteristic { + + public OccupancyDetectedCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000071-0000-1000-8000-0026BB765291", + "Occupancy Detected", + OccupancyDetectedEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/occupancysensor/OccupancyDetectedEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/occupancysensor/OccupancyDetectedEnum.java new file mode 100644 index 000000000..688fa9d24 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/occupancysensor/OccupancyDetectedEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.occupancysensor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Occupancy is not detected” 1 ”Occupancy is detected” */ +public enum OccupancyDetectedEnum implements CharacteristicEnum { + NOT_DETECTED(0), + DETECTED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(OccupancyDetectedEnum.values()) + .collect(Collectors.toMap(OccupancyDetectedEnum::getCode, t -> t)); + } + + public static OccupancyDetectedEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + OccupancyDetectedEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/outlet/OutletInUseCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/outlet/OutletInUseCharacteristic.java new file mode 100644 index 000000000..bd70f46f7 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/outlet/OutletInUseCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.outlet; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes if the power outlet has an appliance physically plugged in. This + * characteristic is set to True even if the plugged-in appliance is off. + */ +public class OutletInUseCharacteristic extends BooleanCharacteristic { + + public OutletInUseCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000026-0000-1000-8000-0026BB765291", + "Outlet in Use", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/CurrentSecuritySystemStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/CurrentSecuritySystemStateCharacteristic.java new file mode 100644 index 000000000..38ec2c3fd --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/CurrentSecuritySystemStateCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.securitysystem; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the state of a security system */ +public class CurrentSecuritySystemStateCharacteristic + extends EnumCharacteristic { + + public CurrentSecuritySystemStateCharacteristic( + CurrentSecuritySystemStateEnum[] validValues, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000066-0000-1000-8000-0026BB765291", + "Current Security System State", + validValues, + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/CurrentSecuritySystemStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/CurrentSecuritySystemStateEnum.java new file mode 100644 index 000000000..90a66cf7e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/CurrentSecuritySystemStateEnum.java @@ -0,0 +1,52 @@ +package io.github.hapjava.characteristics.impl.securitysystem; + +import io.github.hapjava.accessories.SecuritySystemAccessory; +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * The current state of a {@link SecuritySystemAccessory}. Unlike {@link + * TargetSecuritySystemStateEnum}, this enum includes a triggered state. 0 ”Stay Arm. The home is + * occupied and the residents are active. e.g. morning or evenings” 1 ”Away Arm. The home is + * unoccupied” 2 ”Night Arm. The home is occupied and the residents are sleeping” 3 ”Disarmed” 4 + * ”Alarm Triggered” 5-255 ”Reserved” + * + * @author Gaston Dombiak + */ +public enum CurrentSecuritySystemStateEnum implements CharacteristicEnum { + + /** The home is occupied and residents are active. */ + STAY_ARM(0), + /** The home is unoccupied. */ + AWAY_ARM(1), + /** The home is occupied and residents are sleeping. */ + NIGHT_ARM(2), + /** The security system is disarmed. */ + DISARMED(3), + /** The security system is triggered. */ + TRIGGERED(4); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentSecuritySystemStateEnum.values()) + .collect(Collectors.toMap(CurrentSecuritySystemStateEnum::getCode, t -> t)); + } + + public static CurrentSecuritySystemStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentSecuritySystemStateEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/SecuritySystemAlarmTypeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/SecuritySystemAlarmTypeCharacteristic.java new file mode 100644 index 000000000..14c118399 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/SecuritySystemAlarmTypeCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.securitysystem; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the type of alarm triggered by a security system. See {@link + * SecuritySystemAlarmTypeEnum} for possible values. + */ +public class SecuritySystemAlarmTypeCharacteristic + extends EnumCharacteristic { + + public SecuritySystemAlarmTypeCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000008E-0000-1000-8000-0026BB765291", + "Alert Type", + SecuritySystemAlarmTypeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/SecuritySystemAlarmTypeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/SecuritySystemAlarmTypeEnum.java new file mode 100644 index 000000000..00bc0f24e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/SecuritySystemAlarmTypeEnum.java @@ -0,0 +1,45 @@ +package io.github.hapjava.characteristics.impl.securitysystem; + +import io.github.hapjava.accessories.SecuritySystemAccessory; +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Type of alarm of a {@link SecuritySystemAccessory}. + * + *

This characteristic describes the type of alarm triggered by a security system. A value of 1 + * indicates an ʼunknownʼ cause. Value should revert to 0 when the alarm conditions are cleared. + * + * @author Gaston Dombiak + */ +public enum SecuritySystemAlarmTypeEnum implements CharacteristicEnum { + + /** Alarm conditions are cleared */ + NO_ALARM(0), + /** Alarm type is not known */ + UNKNOWN(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(SecuritySystemAlarmTypeEnum.values()) + .collect(Collectors.toMap(SecuritySystemAlarmTypeEnum::getCode, t -> t)); + } + + public static SecuritySystemAlarmTypeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + SecuritySystemAlarmTypeEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/TargetSecuritySystemStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/TargetSecuritySystemStateCharacteristic.java new file mode 100644 index 000000000..5289ba380 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/TargetSecuritySystemStateCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.securitysystem; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target state of the security system. */ +public class TargetSecuritySystemStateCharacteristic + extends EnumCharacteristic { + + public TargetSecuritySystemStateCharacteristic( + TargetSecuritySystemStateEnum[] validValues, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000067-0000-1000-8000-0026BB765291", + "Target Security System State", + validValues, + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/TargetSecuritySystemStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/TargetSecuritySystemStateEnum.java new file mode 100644 index 000000000..81b0adc22 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/securitysystem/TargetSecuritySystemStateEnum.java @@ -0,0 +1,50 @@ +package io.github.hapjava.characteristics.impl.securitysystem; + +import io.github.hapjava.accessories.SecuritySystemAccessory; +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * The target state of a {@link SecuritySystemAccessory}. + * + *

0 ”Stay Arm. The home is occupied and the residents are active. e.g. morning or evenings” 1 + * ”Away Arm. The home is unoccupied” 2 ”Night Arm. The home is occupied and the residents are + * sleeping” 3 ”Disarm” 4-255 ”Reserved” + * + * @author Gaston Dombiak + */ +public enum TargetSecuritySystemStateEnum implements CharacteristicEnum { + + /** Arm the system when the home is occupied and residents are active. */ + STAY_ARM(0), + /** Arm the system when the home is unoccupied. */ + AWAY_ARM(1), + /** Arm the system when the home is occupied and residents are sleeping. */ + NIGHT_ARM(2), + /** Disarm the system. */ + DISARM(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetSecuritySystemStateEnum.values()) + .collect(Collectors.toMap(TargetSecuritySystemStateEnum::getCode, t -> t)); + } + + public static TargetSecuritySystemStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + TargetSecuritySystemStateEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentSlatStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentSlatStateCharacteristic.java new file mode 100644 index 000000000..84e5e1daa --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentSlatStateCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.slat; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current state of the slats. */ +public class CurrentSlatStateCharacteristic extends EnumCharacteristic { + + public CurrentSlatStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000AA-0000-1000-8000-0026BB765291", + "current slat state", + CurrentSlatStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentSlatStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentSlatStateEnum.java new file mode 100644 index 000000000..a94fd4d8e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentSlatStateEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.slat; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Fixed” 1 ”Jammed” 2 ”Swinging” */ +public enum CurrentSlatStateEnum implements CharacteristicEnum { + FIXED(0), + JAMMED(1), + SWINGING(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentSlatStateEnum.values()) + .collect(Collectors.toMap(CurrentSlatStateEnum::getCode, t -> t)); + } + + public static CurrentSlatStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentSlatStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentTiltAngleCharacteristic.java new file mode 100644 index 000000000..3a4868b2c --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/slat/CurrentTiltAngleCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.slat; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describe current tilt angle (between -90 and 90) */ +public class CurrentTiltAngleCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public CurrentTiltAngleCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C1-0000-1000-8000-0026BB765291", + "current tilt angle", + -90, + 90, + "arcdegrees", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/slat/SlatTypeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/slat/SlatTypeCharacteristic.java new file mode 100644 index 000000000..0d9f60608 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/slat/SlatTypeCharacteristic.java @@ -0,0 +1,23 @@ +package io.github.hapjava.characteristics.impl.slat; + +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** + * This characteristic describes the type of the slats. See {@link SlatTypeEnum} for possible values + */ +public class SlatTypeCharacteristic extends EnumCharacteristic { + + public SlatTypeCharacteristic(Supplier> getter) { + super( + "000000C0-0000-1000-8000-0026BB765291", + "slat type", + SlatTypeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/slat/SlatTypeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/slat/SlatTypeEnum.java new file mode 100644 index 000000000..2634b0ef5 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/slat/SlatTypeEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.slat; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Horizontal” 1 ”Vertical” */ +public enum SlatTypeEnum implements CharacteristicEnum { + HORIZONTAL(0), + VERTICAL(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(SlatTypeEnum.values()) + .collect(Collectors.toMap(SlatTypeEnum::getCode, t -> t)); + } + + public static SlatTypeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + SlatTypeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/slat/TargetTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/slat/TargetTiltAngleCharacteristic.java new file mode 100644 index 000000000..2a327522d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/slat/TargetTiltAngleCharacteristic.java @@ -0,0 +1,32 @@ +package io.github.hapjava.characteristics.impl.slat; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target angle of slats. */ +public class TargetTiltAngleCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public TargetTiltAngleCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000C2-0000-1000-8000-0026BB765291", + "target tilt angle", + -90, + 90, + "arcdegrees", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/smokesensor/SmokeDetectedCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/smokesensor/SmokeDetectedCharacteristic.java new file mode 100644 index 000000000..9befabed0 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/smokesensor/SmokeDetectedCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.smokesensor; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic indicates if a sensor detects smoke. */ +public class SmokeDetectedCharacteristic extends EnumCharacteristic { + + public SmokeDetectedCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000076-0000-1000-8000-0026BB765291", + "Smoke Detected", + SmokeDetectedStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/smokesensor/SmokeDetectedStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/smokesensor/SmokeDetectedStateEnum.java new file mode 100644 index 000000000..c6e3b6d5d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/smokesensor/SmokeDetectedStateEnum.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.smokesensor; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Smoke is not detected” 1 ”Smoke is detected” */ +public enum SmokeDetectedStateEnum implements CharacteristicEnum { + NOT_DETECTED(0), + DETECTED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(SmokeDetectedStateEnum.values()) + .collect(Collectors.toMap(SmokeDetectedStateEnum::getCode, t -> t)); + } + + public static SmokeDetectedStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + SmokeDetectedStateEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/ClosedCaptionsCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/television/ClosedCaptionsCharacteristic.java new file mode 100644 index 000000000..a963ca222 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/ClosedCaptionsCharacteristic.java @@ -0,0 +1,31 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Characteristic indicates whether the service provides closed captions. See {@link + * ClosedCaptionsEnum} for possible values. + */ +public class ClosedCaptionsCharacteristic extends EnumCharacteristic { + + public ClosedCaptionsCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000DD-0000-1000-8000-0026BB765291", + "closed captions", + ClosedCaptionsEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/ClosedCaptionsEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/television/ClosedCaptionsEnum.java new file mode 100644 index 000000000..2eb994149 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/ClosedCaptionsEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Disabled” 1 ”Enabled” 2-255 ”Reserved” */ +public enum ClosedCaptionsEnum implements CharacteristicEnum { + DISABLED(0), + ENABLED(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ClosedCaptionsEnum.values()) + .collect(Collectors.toMap(ClosedCaptionsEnum::getCode, t -> t)); + } + + public static ClosedCaptionsEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + ClosedCaptionsEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/CurrentMediaStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/television/CurrentMediaStateCharacteristic.java new file mode 100644 index 000000000..ca72c4ee9 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/CurrentMediaStateCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates current media state. See {@link CurrentMediaStateEnum} for possible + * values. + */ +public class CurrentMediaStateCharacteristic extends EnumCharacteristic { + public CurrentMediaStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000E0-0000-1000-8000-0026BB765291", + "current media state", + CurrentMediaStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/CurrentMediaStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/television/CurrentMediaStateEnum.java new file mode 100644 index 000000000..83836c4c6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/CurrentMediaStateEnum.java @@ -0,0 +1,37 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Play” 1 ”Pause” 2 "Stop" 3 "Unknown" 4-255 ”Reserved” */ +public enum CurrentMediaStateEnum implements CharacteristicEnum { + PLAY(0), + PAUSE(1), + STOP(2), + UNKNOWN(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentMediaStateEnum.values()) + .collect(Collectors.toMap(CurrentMediaStateEnum::getCode, t -> t)); + } + + public static CurrentMediaStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentMediaStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/PictureModeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/television/PictureModeCharacteristic.java new file mode 100644 index 000000000..7efefa23a --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/PictureModeCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic retrieves / sets picture mode. See {@link PictureModeEnum} for possible + * values. + */ +public class PictureModeCharacteristic extends EnumCharacteristic { + public PictureModeCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000E2-0000-1000-8000-0026BB765291", + "picture mode", + PictureModeEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/PictureModeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/television/PictureModeEnum.java new file mode 100644 index 000000000..ac387cf65 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/PictureModeEnum.java @@ -0,0 +1,44 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 0 ”Other” 1 ”Standard” 2 "Calibrated" 3 "CalibratedDark" 4 "Vivid" 5 "Game" 6 "Computer" 7 + * "Custom" 8-255 ”Reserved” + */ +public enum PictureModeEnum implements CharacteristicEnum { + OTHER(0), + STANDARD(1), + CALIBRATED(2), + CALIBRATED_DARK(3), + VIVID(4), + GAME(5), + COMPUTER(6), + CUSTOM(7); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(PictureModeEnum.values()) + .collect(Collectors.toMap(PictureModeEnum::getCode, t -> t)); + } + + public static PictureModeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + PictureModeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/PowerModeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/television/PowerModeCharacteristic.java new file mode 100644 index 000000000..cebbe4124 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/PowerModeCharacteristic.java @@ -0,0 +1,20 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; + +/** characteristic sets power mode. See {@link PowerModeEnum} for possible values. */ +public class PowerModeCharacteristic extends EnumCharacteristic { + + public PowerModeCharacteristic(ExceptionalConsumer setter) { + super( + "000000DF-0000-1000-8000-0026BB765291", + "power mode selection", + PowerModeEnum.values(), + Optional.empty(), + Optional.of(setter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/PowerModeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/television/PowerModeEnum.java new file mode 100644 index 000000000..a171ba135 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/PowerModeEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Show” 1 ”Hide” 2-255 ”Reserved” */ +public enum PowerModeEnum implements CharacteristicEnum { + SHOW(0), + HIDE(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(PowerModeEnum.values()) + .collect(Collectors.toMap(PowerModeEnum::getCode, t -> t)); + } + + public static PowerModeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + PowerModeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/RemoteKeyCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/television/RemoteKeyCharacteristic.java new file mode 100644 index 000000000..fe028d10d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/RemoteKeyCharacteristic.java @@ -0,0 +1,22 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; + +/** + * This characteristic sends information about pressed key on tv remote. See {@link RemoteKeyEnum} + * for possible values. + */ +public class RemoteKeyCharacteristic extends EnumCharacteristic { + public RemoteKeyCharacteristic(ExceptionalConsumer setter) { + super( + "000000E1-0000-1000-8000-0026BB765291", + "remote key", + RemoteKeyEnum.values(), + Optional.empty(), + Optional.of(setter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/RemoteKeyEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/television/RemoteKeyEnum.java new file mode 100644 index 000000000..d62298b84 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/RemoteKeyEnum.java @@ -0,0 +1,45 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum RemoteKeyEnum implements CharacteristicEnum { + REWIND(0), + FAST_FORWARD(1), + NEXT_TRACK(2), + PREV_TRACK(3), + ARROW_UP(4), + ARROW_DOWN(5), + ARROW_LEFT(6), + ARROW_RIGHT(7), + SELECT(8), + BACK(9), + EXIT(10), + PLAY_PAUSE(11), + INFO(15); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(RemoteKeyEnum.values()) + .collect(Collectors.toMap(RemoteKeyEnum::getCode, t -> t)); + } + + public static RemoteKeyEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + RemoteKeyEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/SleepDiscoveryModeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/television/SleepDiscoveryModeCharacteristic.java new file mode 100644 index 000000000..2a7f41829 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/SleepDiscoveryModeCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates whether the service can be discovered. See {@link + * SleepDiscoveryModeEnum} for possible values. + */ +public class SleepDiscoveryModeCharacteristic extends EnumCharacteristic { + public SleepDiscoveryModeCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000E8-0000-1000-8000-0026BB765291", + "sleep discovery mode", + SleepDiscoveryModeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/SleepDiscoveryModeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/television/SleepDiscoveryModeEnum.java new file mode 100644 index 000000000..da1377b9a --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/SleepDiscoveryModeEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Not discoverable” 1 ”Always discoverable” 2-255 ”Reserved” */ +public enum SleepDiscoveryModeEnum implements CharacteristicEnum { + NOT_DISCOVERABLE(0), + ALWAYS_DISCOVERABLE(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(SleepDiscoveryModeEnum.values()) + .collect(Collectors.toMap(SleepDiscoveryModeEnum::getCode, t -> t)); + } + + public static SleepDiscoveryModeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + SleepDiscoveryModeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/TargetMediaStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/television/TargetMediaStateCharacteristic.java new file mode 100644 index 000000000..8909bb1ea --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/TargetMediaStateCharacteristic.java @@ -0,0 +1,27 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic sets media state. See {@link TargetMediaStateEnum} for possible values. */ +public class TargetMediaStateCharacteristic extends EnumCharacteristic { + public TargetMediaStateCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000137-0000-1000-8000-0026BB765291", + "current media state", + TargetMediaStateEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/television/TargetMediaStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/television/TargetMediaStateEnum.java new file mode 100644 index 000000000..b6f6633ff --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/television/TargetMediaStateEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.television; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Play” 1 ”Pause” 2 "Stop" 3-255 ”Reserved” */ +public enum TargetMediaStateEnum implements CharacteristicEnum { + PLAY(0), + PAUSE(1), + STOP(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetMediaStateEnum.values()) + .collect(Collectors.toMap(TargetMediaStateEnum::getCode, t -> t)); + } + + public static TargetMediaStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + TargetMediaStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeControlTypeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeControlTypeCharacteristic.java new file mode 100644 index 000000000..c6d18a858 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeControlTypeCharacteristic.java @@ -0,0 +1,28 @@ +package io.github.hapjava.characteristics.impl.televisionspeaker; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic indicates volume control type. See {@link VolumeControlTypeEnum} for possible + * values. + */ +public class VolumeControlTypeCharacteristic extends EnumCharacteristic { + public VolumeControlTypeCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000E9-0000-1000-8000-0026BB765291", + "volume control type", + VolumeControlTypeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeControlTypeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeControlTypeEnum.java new file mode 100644 index 000000000..dfeb24636 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeControlTypeEnum.java @@ -0,0 +1,36 @@ +package io.github.hapjava.characteristics.impl.televisionspeaker; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum VolumeControlTypeEnum implements CharacteristicEnum { + NONE(0), + RELATIVE(1), + RELATIVE_WITH_CURRENT(2), + ABSOLUTE(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(VolumeControlTypeEnum.values()) + .collect(Collectors.toMap(VolumeControlTypeEnum::getCode, t -> t)); + } + + public static VolumeControlTypeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + VolumeControlTypeEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeSelectorCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeSelectorCharacteristic.java new file mode 100644 index 000000000..8f2f84e7b --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeSelectorCharacteristic.java @@ -0,0 +1,22 @@ +package io.github.hapjava.characteristics.impl.televisionspeaker; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; + +/** + * This characteristic sends information about volume changes. See {@link VolumeSelectorEnum} for + * possible values. + */ +public class VolumeSelectorCharacteristic extends EnumCharacteristic { + public VolumeSelectorCharacteristic(ExceptionalConsumer setter) { + super( + "000000EA-0000-1000-8000-0026BB765291", + "volume selector", + VolumeSelectorEnum.values(), + Optional.empty(), + Optional.of(setter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeSelectorEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeSelectorEnum.java new file mode 100644 index 000000000..63bc60e50 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/televisionspeaker/VolumeSelectorEnum.java @@ -0,0 +1,34 @@ +package io.github.hapjava.characteristics.impl.televisionspeaker; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public enum VolumeSelectorEnum implements CharacteristicEnum { + INCREMENT(0), + DECREMENT(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(VolumeSelectorEnum.values()) + .collect(Collectors.toMap(VolumeSelectorEnum::getCode, t -> t)); + } + + public static VolumeSelectorEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + VolumeSelectorEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CoolingThresholdTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CoolingThresholdTemperatureCharacteristic.java new file mode 100644 index 000000000..d855f70d6 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CoolingThresholdTemperatureCharacteristic.java @@ -0,0 +1,54 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the cooling threshold on which accessories turns on the cooling. + */ +public class CoolingThresholdTemperatureCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 10; + public static final double DEFAULT_MAX_VALUE = 35; + public static final double DEFAULT_STEP = 0.1; + + public CoolingThresholdTemperatureCharacteristic( + double minValue, + double maxValue, + double step, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000000D-0000-1000-8000-0026BB765291", + "cooling threshold", + minValue, + maxValue, + step, + "C", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CoolingThresholdTemperatureCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this( + DEFAULT_MIN_VALUE, + DEFAULT_MAX_VALUE, + DEFAULT_STEP, + getter, + setter, + subscriber, + unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentHeatingCoolingStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentHeatingCoolingStateCharacteristic.java new file mode 100644 index 000000000..8c2600a69 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentHeatingCoolingStateCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the current mode of an accessory that supports cooling or heating + */ +public class CurrentHeatingCoolingStateCharacteristic + extends EnumCharacteristic { + + public CurrentHeatingCoolingStateCharacteristic( + CurrentHeatingCoolingStateEnum[] validValues, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000000F-0000-1000-8000-0026BB765291", + "Current heating cooling mode", + validValues, + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentHeatingCoolingStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentHeatingCoolingStateEnum.java new file mode 100644 index 000000000..487262975 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentHeatingCoolingStateEnum.java @@ -0,0 +1,35 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** 0 ”Off.” 1 ”Heat. The Heater is currently on.” 2 ”Cool. Cooler is currently on.” */ +public enum CurrentHeatingCoolingStateEnum implements CharacteristicEnum { + OFF(0), + HEAT(1), + COOL(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(CurrentHeatingCoolingStateEnum.values()) + .collect(Collectors.toMap(CurrentHeatingCoolingStateEnum::getCode, t -> t)); + } + + public static CurrentHeatingCoolingStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + CurrentHeatingCoolingStateEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentTemperatureCharacteristic.java new file mode 100644 index 000000000..f3c2b74ff --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/CurrentTemperatureCharacteristic.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** characteristic describes the current temperature of the environment in Celsius */ +public class CurrentTemperatureCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 100; + public static final double DEFAULT_STEP = 0.1; + + public CurrentTemperatureCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000011-0000-1000-8000-0026BB765291", + "current temperature", + minValue, + maxValue, + minStep, + "C", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CurrentTemperatureCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/HeatingThresholdTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/HeatingThresholdTemperatureCharacteristic.java new file mode 100644 index 000000000..8d7624f8f --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/HeatingThresholdTemperatureCharacteristic.java @@ -0,0 +1,52 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the heating threshold on which heating get turned on. */ +public class HeatingThresholdTemperatureCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 0; + public static final double DEFAULT_MAX_VALUE = 25; + public static final double DEFAULT_STEP = 0.1; + + public HeatingThresholdTemperatureCharacteristic( + double minValue, + double maxValue, + double step, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000012-0000-1000-8000-0026BB765291", + "heating threshold", + minValue, + maxValue, + step, + "C", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public HeatingThresholdTemperatureCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this( + DEFAULT_MIN_VALUE, + DEFAULT_MAX_VALUE, + DEFAULT_STEP, + getter, + setter, + subscriber, + unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetHeatingCoolingStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetHeatingCoolingStateCharacteristic.java new file mode 100644 index 000000000..844df0c67 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetHeatingCoolingStateCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target mode of an accessory that supports heating/cooling, */ +public class TargetHeatingCoolingStateCharacteristic + extends EnumCharacteristic { + + public TargetHeatingCoolingStateCharacteristic( + TargetHeatingCoolingStateEnum[] validValues, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000033-0000-1000-8000-0026BB765291", + "Target heating cooling mode", + validValues, + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetHeatingCoolingStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetHeatingCoolingStateEnum.java new file mode 100644 index 000000000..6120422e5 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetHeatingCoolingStateEnum.java @@ -0,0 +1,41 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 0 ”Off” 1 ”Heat.” 2 ”Cool." 3 ”Auto. Turn on heating or cooling to maintain depending on the + * temperature” + * + * @author Andy Lintner + */ +public enum TargetHeatingCoolingStateEnum implements CharacteristicEnum { + OFF(0), + HEAT(1), + COOL(2), + AUTO(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TargetHeatingCoolingStateEnum.values()) + .collect(Collectors.toMap(t -> t.getCode(), t -> t)); + } + + public static TargetHeatingCoolingStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + private TargetHeatingCoolingStateEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetTemperatureCharacteristic.java new file mode 100644 index 000000000..9a329d383 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TargetTemperatureCharacteristic.java @@ -0,0 +1,55 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.FloatCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the target temperature in Celsius that the accessory is actively + * attempting to reach. + */ +public class TargetTemperatureCharacteristic extends FloatCharacteristic { + public static final double DEFAULT_MIN_VALUE = 10; + public static final double DEFAULT_MAX_VALUE = 38; + public static final double DEFAULT_STEP = 0.1; + + public TargetTemperatureCharacteristic( + double minValue, + double maxValue, + double minStep, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000035-0000-1000-8000-0026BB765291", + "target temperature", + minValue, + maxValue, + minStep, + "C", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public TargetTemperatureCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this( + DEFAULT_MIN_VALUE, + DEFAULT_MAX_VALUE, + DEFAULT_STEP, + getter, + setter, + subscriber, + unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TemperatureDisplayUnitCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TemperatureDisplayUnitCharacteristic.java new file mode 100644 index 000000000..02a23553f --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TemperatureDisplayUnitCharacteristic.java @@ -0,0 +1,32 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes units of temperature used for presentation purposes (e.g. the units + * of temperature displayed on the screen). + */ +public class TemperatureDisplayUnitCharacteristic + extends EnumCharacteristic { + + public TemperatureDisplayUnitCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000036-0000-1000-8000-0026BB765291", + "Temperature units", + TemperatureDisplayUnitEnum.values(), + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TemperatureDisplayUnitEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TemperatureDisplayUnitEnum.java new file mode 100644 index 000000000..dbecc60f0 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/thermostat/TemperatureDisplayUnitEnum.java @@ -0,0 +1,41 @@ +package io.github.hapjava.characteristics.impl.thermostat; + +import io.github.hapjava.accessories.TemperatureSensorAccessory; +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * The temperature unit used by a {@link TemperatureSensorAccessory}. + * + *

0 ”Celsius” 1 ”Fahrenheit” + * + * @author Andy Lintner + */ +public enum TemperatureDisplayUnitEnum implements CharacteristicEnum { + CELSIUS(0), + FAHRENHEIT(1); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(TemperatureDisplayUnitEnum.values()) + .collect(Collectors.toMap(t -> t.getCode(), t -> t)); + } + + static TemperatureDisplayUnitEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + private TemperatureDisplayUnitEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/valve/RemainingDurationCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/valve/RemainingDurationCharacteristic.java new file mode 100644 index 000000000..29409027a --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/valve/RemainingDurationCharacteristic.java @@ -0,0 +1,46 @@ +package io.github.hapjava.characteristics.impl.valve; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This characteristic describes the remaining duration of the active status of an accessory, e.g. + * {@link io.github.hapjava.accessories.ValveAccessory}. This characteristic should only notify + * about changes if it defers from normal countdown. + */ +public class RemainingDurationCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + public static final int DEFAULT_MIN_VALUE = 0; + public static final int DEFAULT_MAX_VALUE = 3600; + + public RemainingDurationCharacteristic( + int minValue, + int maxValue, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000D4-0000-1000-8000-0026BB765291", + "uint32", + "remaining duration", + minValue, + maxValue, + "s", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public RemainingDurationCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/valve/SetDurationCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/valve/SetDurationCharacteristic.java new file mode 100644 index 000000000..109a7bb6e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/valve/SetDurationCharacteristic.java @@ -0,0 +1,45 @@ +package io.github.hapjava.characteristics.impl.valve; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the duration, how long an accessory should be set to "InUse". */ +public class SetDurationCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + public static final int DEFAULT_MIN_VALUE = 0; + public static final int DEFAULT_MAX_VALUE = 3600; + + public SetDurationCharacteristic( + int minValue, + int maxValue, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000D3-0000-1000-8000-0026BB765291", + "uint32", + "set duration", + minValue, + maxValue, + "s", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public SetDurationCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, getter, setter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/valve/ValveTypeCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/valve/ValveTypeCharacteristic.java new file mode 100644 index 000000000..f98e468f4 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/valve/ValveTypeCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.valve; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the type of valve. */ +public class ValveTypeCharacteristic extends EnumCharacteristic { + + public ValveTypeCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "000000D5-0000-1000-8000-0026BB765291", + "Valve type", + ValveTypeEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/valve/ValveTypeEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/valve/ValveTypeEnum.java new file mode 100644 index 000000000..d18d923e2 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/valve/ValveTypeEnum.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.valve; + +import io.github.hapjava.accessories.ValveAccessory; +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * The mode used by a {@link ValveAccessory} + * + *

0 ”Generic valve” 1 ”Irrigation” 2 ”Shower head” 3 ”Water faucet” 4-255 ”Reserved” + * + * @author Tim Harper + */ +public enum ValveTypeEnum implements CharacteristicEnum { + GENERIC(0), + IRRIGATION(1), + SHOWER(2), + WATER_FAUCET(3); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(ValveTypeEnum.values()).collect(Collectors.toMap(t -> t.getCode(), t -> t)); + } + + public static ValveTypeEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + private ValveTypeEnum(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentHorizontalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentHorizontalTiltAngleCharacteristic.java new file mode 100644 index 000000000..272a822f5 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentHorizontalTiltAngleCharacteristic.java @@ -0,0 +1,41 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current angle of horizontal slats. */ +public class CurrentHorizontalTiltAngleCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + public static final int DEFAULT_MIN_VALUE = -90; + public static final int DEFAULT_MAX_VALUE = 90; + + public CurrentHorizontalTiltAngleCharacteristic( + int minValue, + int maxValue, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000006C-0000-1000-8000-0026BB765291", + "current horizontal tilt angle", + minValue, + maxValue, + "arcdegrees", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CurrentHorizontalTiltAngleCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentPositionCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentPositionCharacteristic.java new file mode 100644 index 000000000..d51614615 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentPositionCharacteristic.java @@ -0,0 +1,30 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current position of accessories. */ +public class CurrentPositionCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public CurrentPositionCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000006D-0000-1000-8000-0026BB765291", + "current position", + 0, + 100, + "%", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentVerticalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentVerticalTiltAngleCharacteristic.java new file mode 100644 index 000000000..7d7168973 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/CurrentVerticalTiltAngleCharacteristic.java @@ -0,0 +1,41 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the current angle of vertical slats for accessory. */ +public class CurrentVerticalTiltAngleCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + public static final int DEFAULT_MIN_VALUE = -90; + public static final int DEFAULT_MAX_VALUE = 90; + + public CurrentVerticalTiltAngleCharacteristic( + int minValue, + int maxValue, + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000006E-0000-1000-8000-0026BB765291", + "current vertical tilt angle", + minValue, + maxValue, + "arcdegrees", + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public CurrentVerticalTiltAngleCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, getter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/HoldPositionCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/HoldPositionCharacteristic.java new file mode 100644 index 000000000..7a6455919 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/HoldPositionCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.impl.base.BooleanCharacteristic; +import java.util.Optional; + +/** This characteristic causes the accessories like window covering to stop at its current */ +public class HoldPositionCharacteristic extends BooleanCharacteristic { + + public HoldPositionCharacteristic(ExceptionalConsumer setter) { + super( + "0000006F-0000-1000-8000-0026BB765291", + "Hold Position", + Optional.empty(), + Optional.of(setter), + Optional.empty(), + Optional.empty()); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/PositionStateCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/PositionStateCharacteristic.java new file mode 100644 index 000000000..5b2488f52 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/PositionStateCharacteristic.java @@ -0,0 +1,26 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.EnumCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the state of the position of accessories. */ +public class PositionStateCharacteristic extends EnumCharacteristic { + + public PositionStateCharacteristic( + Supplier> getter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "00000072-0000-1000-8000-0026BB765291", + "Position state", + PositionStateEnum.values(), + Optional.of(getter), + Optional.empty(), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/PositionStateEnum.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/PositionStateEnum.java new file mode 100644 index 000000000..86b9174c8 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/PositionStateEnum.java @@ -0,0 +1,39 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.CharacteristicEnum; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 0 ”Going to the minimum value specified in metadata” 1 ”Going to the maximum value specified in + * metadata” 2 ”Stopped” + */ +public enum PositionStateEnum implements CharacteristicEnum { + DECREASING(0), + INCREASING(1), + STOPPED(2); + + private static final Map reverse; + + static { + reverse = + Arrays.stream(PositionStateEnum.values()) + .collect(Collectors.toMap(PositionStateEnum::getCode, t -> t)); + } + + public static PositionStateEnum fromCode(Integer code) { + return reverse.get(code); + } + + private final int code; + + PositionStateEnum(int code) { + this.code = code; + } + + @Override + public int getCode() { + return code; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetHorizontalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetHorizontalTiltAngleCharacteristic.java new file mode 100644 index 000000000..17639ba6e --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetHorizontalTiltAngleCharacteristic.java @@ -0,0 +1,44 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target angle of horizontal slats for accessories. */ +public class TargetHorizontalTiltAngleCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + public static final int DEFAULT_MIN_VALUE = -90; + public static final int DEFAULT_MAX_VALUE = 90; + + public TargetHorizontalTiltAngleCharacteristic( + int minValue, + int maxValue, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000007B-0000-1000-8000-0026BB765291", + "target horizontal tilt angle", + minValue, + maxValue, + "arcdegrees", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public TargetHorizontalTiltAngleCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, getter, setter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetPositionCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetPositionCharacteristic.java new file mode 100644 index 000000000..6398a0b37 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetPositionCharacteristic.java @@ -0,0 +1,32 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target position of accessories like door, window, blinds. */ +public class TargetPositionCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + + public TargetPositionCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000007C-0000-1000-8000-0026BB765291", + "target position", + 0, + 100, + "%", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetVerticalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetVerticalTiltAngleCharacteristic.java new file mode 100644 index 000000000..03fd7a3f5 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/windowcovering/TargetVerticalTiltAngleCharacteristic.java @@ -0,0 +1,44 @@ +package io.github.hapjava.characteristics.impl.windowcovering; + +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.ExceptionalConsumer; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** This characteristic describes the target angle of vertical slats. */ +public class TargetVerticalTiltAngleCharacteristic extends IntegerCharacteristic + implements EventableCharacteristic { + public static final int DEFAULT_MIN_VALUE = -90; + public static final int DEFAULT_MAX_VALUE = 90; + + public TargetVerticalTiltAngleCharacteristic( + int minValue, + int maxValue, + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + super( + "0000007D-0000-1000-8000-0026BB765291", + "target vertical tilt angle", + minValue, + maxValue, + "arcdegrees", + Optional.of(getter), + Optional.of(setter), + Optional.of(subscriber), + Optional.of(unsubscriber)); + } + + public TargetVerticalTiltAngleCharacteristic( + Supplier> getter, + ExceptionalConsumer setter, + Consumer subscriber, + Runnable unsubscriber) { + this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, getter, setter, subscriber, unsubscriber); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/package-info.java b/src/main/java/io/github/hapjava/characteristics/package-info.java index a0bbf1a3f..955ab73a7 100644 --- a/src/main/java/io/github/hapjava/characteristics/package-info.java +++ b/src/main/java/io/github/hapjava/characteristics/package-info.java @@ -1,4 +1,4 @@ /** - * Contains the basic characteristic types that can be supplied over the Homekit Accessory Protocol. + * Contains the basic characteristic types that can be supplied over the HomeKit Accessory Protocol. */ package io.github.hapjava.characteristics; diff --git a/src/main/java/io/github/hapjava/impl/ExceptionalConsumer.java b/src/main/java/io/github/hapjava/impl/ExceptionalConsumer.java deleted file mode 100644 index 84ab5fd0c..000000000 --- a/src/main/java/io/github/hapjava/impl/ExceptionalConsumer.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.github.hapjava.impl; - -public interface ExceptionalConsumer { - void accept(T t) throws Exception; -} diff --git a/src/main/java/io/github/hapjava/impl/HomekitBridge.java b/src/main/java/io/github/hapjava/impl/HomekitBridge.java deleted file mode 100644 index acce783ce..000000000 --- a/src/main/java/io/github/hapjava/impl/HomekitBridge.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.github.hapjava.impl; - -import io.github.hapjava.Service; -import io.github.hapjava.impl.accessories.Bridge; -import java.util.Collection; -import java.util.Collections; - -public class HomekitBridge implements Bridge { - - private final String label; - private final String serialNumber; - private final String model; - private final String manufacturer; - - public HomekitBridge(String label, String serialNumber, String model, String manufacturer) { - this.label = label; - this.serialNumber = serialNumber; - this.model = model; - this.manufacturer = manufacturer; - } - - @Override - public String getLabel() { - return label; - } - - @Override - public String getSerialNumber() { - return serialNumber; - } - - @Override - public String getModel() { - return model; - } - - @Override - public String getManufacturer() { - return manufacturer; - } - - @Override - public Collection getServices() { - return Collections.emptyList(); - } - - @Override - public int getId() { - return 1; - } -} diff --git a/src/main/java/io/github/hapjava/impl/HomekitRegistry.java b/src/main/java/io/github/hapjava/impl/HomekitRegistry.java deleted file mode 100644 index e3107d44e..000000000 --- a/src/main/java/io/github/hapjava/impl/HomekitRegistry.java +++ /dev/null @@ -1,91 +0,0 @@ -package io.github.hapjava.impl; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.Service; -import io.github.hapjava.characteristics.Characteristic; -import io.github.hapjava.impl.services.AccessoryInformationService; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HomekitRegistry { - - private static final Logger logger = LoggerFactory.getLogger(HomekitRegistry.class); - - private final String label; - private final Map accessories; - private final Map> services = new HashMap<>(); - private final Map> characteristics = - new HashMap<>(); - private boolean isAllowUnauthenticatedRequests = false; - - public HomekitRegistry(String label) { - this.label = label; - this.accessories = new ConcurrentHashMap<>(); - reset(); - } - - public synchronized void reset() { - characteristics.clear(); - services.clear(); - for (HomekitAccessory accessory : accessories.values()) { - int iid = 0; - List newServices; - try { - newServices = new ArrayList<>(2); - newServices.add(new AccessoryInformationService(accessory)); - newServices.addAll(accessory.getServices()); - } catch (Exception e) { - logger.error("Could not instantiate services for accessory " + accessory.getLabel(), e); - services.put(accessory, Collections.emptyList()); - continue; - } - Map newCharacteristics = new HashMap<>(); - services.put(accessory, newServices); - for (Service service : newServices) { - iid++; - for (Characteristic characteristic : service.getCharacteristics()) { - newCharacteristics.put(++iid, characteristic); - } - } - characteristics.put(accessory, newCharacteristics); - } - } - - public String getLabel() { - return label; - } - - public Collection getAccessories() { - return accessories.values(); - } - - public List getServices(Integer aid) { - return Collections.unmodifiableList(services.get(accessories.get(aid))); - } - - public Map getCharacteristics(Integer aid) { - Map characteristics = this.characteristics.get(accessories.get(aid)); - if (characteristics == null) { - return Collections.emptyMap(); - } - return Collections.unmodifiableMap(characteristics); - } - - public void add(HomekitAccessory accessory) { - accessories.put(accessory.getId(), accessory); - } - - public void remove(HomekitAccessory accessory) { - accessories.remove(accessory.getId()); - } - - public boolean isAllowUnauthenticatedRequests() { - return isAllowUnauthenticatedRequests; - } - - public void setAllowUnauthenticatedRequests(boolean allow) { - this.isAllowUnauthenticatedRequests = allow; - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/carbonmonoxide/CarbonMonoxideDetectedCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/carbonmonoxide/CarbonMonoxideDetectedCharacteristic.java deleted file mode 100644 index cf38cc837..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/carbonmonoxide/CarbonMonoxideDetectedCharacteristic.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.hapjava.impl.characteristics.carbonmonoxide; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.CarbonMonoxideSensor; -import io.github.hapjava.accessories.properties.CarbonMonoxideDetectedState; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CarbonMonoxideDetectedCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final CarbonMonoxideSensor carbonMonoxideSensor; - - public CarbonMonoxideDetectedCharacteristic(CarbonMonoxideSensor carbonMonoxideSensor) { - super("00000069-0000-1000-8000-0026BB765291", false, true, "Carbon Monoxide Detected", 1); - this.carbonMonoxideSensor = carbonMonoxideSensor; - } - - @Override - protected CompletableFuture getValue() { - return carbonMonoxideSensor - .getCarbonMonoxideDetectedState() - .thenApply(CarbonMonoxideDetectedState::getCode); - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - carbonMonoxideSensor.subscribeCarbonMonoxideDetectedState(callback); - } - - @Override - public void unsubscribe() { - carbonMonoxideSensor.unsubscribeCarbonMonoxideDetectedState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/ActiveCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/common/ActiveCharacteristic.java deleted file mode 100644 index bdb0f9866..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/ActiveCharacteristic.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.impl.ExceptionalConsumer; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class ActiveCharacteristic extends BooleanCharacteristic implements EventableCharacteristic { - - private final Supplier> getter; - private final ExceptionalConsumer setter; - private final Consumer subscriber; - private final Runnable unsubscriber; - - public ActiveCharacteristic( - Supplier> getter, - ExceptionalConsumer setter, - Consumer subscriber, - Runnable unsubscriber) { - super("000000B0-0000-1000-8000-0026BB765291", true, true, "Active"); - this.getter = getter; - this.setter = setter; - this.subscriber = subscriber; - this.unsubscriber = unsubscriber; - } - - @Override - protected CompletableFuture getValue() { - return getter.get(); - } - - @Override - protected void setValue(Boolean value) throws Exception { - setter.accept(value); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - subscriber.accept(callback); - } - - @Override - public void unsubscribe() { - unsubscriber.run(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/BatteryLevelCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/common/BatteryLevelCharacteristic.java deleted file mode 100644 index d3afac86a..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/BatteryLevelCharacteristic.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * This characteristic is used by a stand-alone BatteryService, which describes a stand-alone - * battery device, not the battery status of a battery operated device such as a motion sensor. - */ -public class BatteryLevelCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final Supplier> getter; - private final Consumer subscriber; - private final Runnable unsubscriber; - - public BatteryLevelCharacteristic( - Supplier> getter, - Consumer subscriber, - Runnable unsubscriber) { - super("00000068-0000-1000-8000-0026BB765291", false, true, "Battery Level", 0, 100, "%"); - this.getter = getter; - this.subscriber = subscriber; - this.unsubscriber = unsubscriber; - } - - @Override - protected CompletableFuture getValue() { - return getter.get(); - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - subscriber.accept(callback); - } - - @Override - public void unsubscribe() { - unsubscriber.run(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/InUseCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/common/InUseCharacteristic.java deleted file mode 100644 index b58b2eea3..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/InUseCharacteristic.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class InUseCharacteristic extends BooleanCharacteristic implements EventableCharacteristic { - - private final Supplier> getter; - private final Consumer subscriber; - private final Runnable unsubscriber; - - public InUseCharacteristic( - Supplier> getter, - Consumer subscriber, - Runnable unsubscriber) { - super("000000D2-0000-1000-8000-0026BB765291", false, true, "InUse"); - this.getter = getter; - this.subscriber = subscriber; - this.unsubscriber = unsubscriber; - } - - @Override - protected CompletableFuture getValue() { - return getter.get(); - } - - @Override - protected void setValue(Boolean value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - subscriber.accept(callback); - } - - @Override - public void unsubscribe() { - unsubscriber.run(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/LowBatteryStatusCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/common/LowBatteryStatusCharacteristic.java deleted file mode 100644 index 28869e3cd..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/LowBatteryStatusCharacteristic.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class LowBatteryStatusCharacteristic extends BooleanCharacteristic - implements EventableCharacteristic { - - private final Supplier> getter; - private final Consumer subscriber; - private final Runnable unsubscriber; - - public LowBatteryStatusCharacteristic( - Supplier> getter, - Consumer subscriber, - Runnable unsubscriber) { - super("00000079-0000-1000-8000-0026BB765291", false, true, "Status Low Battery"); - this.getter = getter; - this.subscriber = subscriber; - this.unsubscriber = unsubscriber; - } - - @Override - protected CompletableFuture getValue() { - return getter.get(); - } - - @Override - protected void setValue(Boolean value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - subscriber.accept(callback); - } - - @Override - public void unsubscribe() { - unsubscriber.run(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/Name.java b/src/main/java/io/github/hapjava/impl/characteristics/common/Name.java deleted file mode 100644 index 35bebcacc..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/Name.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.characteristics.StaticStringCharacteristic; - -public class Name extends StaticStringCharacteristic { - - public Name(String label) { - super("00000023-0000-1000-8000-0026BB765291", "Name of the accessory", label); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/ObstructionDetectedCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/common/ObstructionDetectedCharacteristic.java deleted file mode 100644 index e4d242a8e..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/ObstructionDetectedCharacteristic.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class ObstructionDetectedCharacteristic extends BooleanCharacteristic - implements EventableCharacteristic { - - private final Supplier> getter; - private final Consumer subscriber; - private final Runnable unsubscriber; - - public ObstructionDetectedCharacteristic( - Supplier> getter, - Consumer subscriber, - Runnable unsubscriber) { - super("00000024-0000-1000-8000-0026BB765291", false, true, "An obstruction has been detected"); - this.getter = getter; - this.subscriber = subscriber; - this.unsubscriber = unsubscriber; - } - - @Override - protected void setValue(Boolean value) throws Exception { - // Read Only - } - - @Override - protected CompletableFuture getValue() { - return getter.get(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - subscriber.accept(callback); - } - - @Override - public void unsubscribe() { - unsubscriber.run(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/PowerStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/common/PowerStateCharacteristic.java deleted file mode 100644 index 0b045247c..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/PowerStateCharacteristic.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.impl.ExceptionalConsumer; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class PowerStateCharacteristic extends BooleanCharacteristic - implements EventableCharacteristic { - - private final Supplier> getter; - private final ExceptionalConsumer setter; - private final Consumer subscriber; - private final Runnable unsubscriber; - - public PowerStateCharacteristic( - Supplier> getter, - ExceptionalConsumer setter, - Consumer subscriber, - Runnable unsubscriber) { - super("00000025-0000-1000-8000-0026BB765291", true, true, "Turn on and off"); - this.getter = getter; - this.setter = setter; - this.subscriber = subscriber; - this.unsubscriber = unsubscriber; - } - - @Override - public void setValue(Boolean value) throws Exception { - setter.accept(value); - } - - @Override - protected CompletableFuture getValue() { - return getter.get(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - subscriber.accept(callback); - } - - @Override - public void unsubscribe() { - unsubscriber.run(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/common/RemainingDurationCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/common/RemainingDurationCharacteristic.java deleted file mode 100644 index b5d9f3e4f..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/common/RemainingDurationCharacteristic.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.github.hapjava.impl.characteristics.common; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class RemainingDurationCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final Supplier> getter; - private final Consumer subscriber; - private final Runnable unsubscriber; - - public RemainingDurationCharacteristic( - Supplier> getter, - Consumer subscriber, - Runnable unsubscriber) { - super( - "000000D4-0000-1000-8000-0026BB765291", - false, - true, - "Remaining Duration", - 0, - 3600, - "seconds"); - this.getter = getter; - this.subscriber = subscriber; - this.unsubscriber = unsubscriber; - } - - @Override - protected CompletableFuture getValue() { - return getter.get(); - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - subscriber.accept(callback); - } - - @Override - public void unsubscribe() { - unsubscriber.run(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/contactsensor/ContactSensorStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/contactsensor/ContactSensorStateCharacteristic.java deleted file mode 100644 index e246fa5e7..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/contactsensor/ContactSensorStateCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.contactsensor; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.ContactSensor; -import io.github.hapjava.accessories.properties.ContactState; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class ContactSensorStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final ContactSensor contactSensor; - - public ContactSensorStateCharacteristic(ContactSensor contactSensor) { - super("0000006A-0000-1000-8000-0026BB765291", false, true, "Contact State", 1); - this.contactSensor = contactSensor; - } - - @Override - protected CompletableFuture getValue() { - return contactSensor.getCurrentState().thenApply(ContactState::getCode); - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - contactSensor.subscribeContactState(callback); - } - - @Override - public void unsubscribe() { - contactSensor.unsubscribeContactState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/fan/RotationDirectionCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/fan/RotationDirectionCharacteristic.java deleted file mode 100644 index b545f8210..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/fan/RotationDirectionCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.fan; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.Fan; -import io.github.hapjava.accessories.properties.RotationDirection; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class RotationDirectionCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final Fan fan; - - public RotationDirectionCharacteristic(Fan fan) { - super("00000028-0000-1000-8000-0026BB765291", true, true, "Rotation Direction", 1); - this.fan = fan; - } - - @Override - protected void setValue(Integer value) throws Exception { - fan.setRotationDirection(RotationDirection.fromCode(value)); - } - - @Override - protected CompletableFuture getValue() { - return fan.getRotationDirection().thenApply(s -> s.getCode()); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - fan.subscribeRotationDirection(callback); - } - - @Override - public void unsubscribe() { - fan.unsubscribeRotationDirection(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/fan/RotationSpeedCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/fan/RotationSpeedCharacteristic.java deleted file mode 100644 index 43c905802..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/fan/RotationSpeedCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.fan; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.Fan; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class RotationSpeedCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final Fan fan; - - public RotationSpeedCharacteristic(Fan fan) { - super("00000029-0000-1000-8000-0026BB765291", true, true, "Rotation speed", 0, 100, "%"); - this.fan = fan; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - fan.subscribeRotationSpeed(callback); - } - - @Override - public void unsubscribe() { - fan.unsubscribeRotationSpeed(); - } - - @Override - protected void setValue(Integer value) throws Exception { - fan.setRotationSpeed(value); - } - - @Override - protected CompletableFuture getValue() { - return fan.getRotationSpeed(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/garage/CurrentDoorStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/garage/CurrentDoorStateCharacteristic.java deleted file mode 100644 index 7d6944b96..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/garage/CurrentDoorStateCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.garage; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.GarageDoor; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CurrentDoorStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final GarageDoor door; - - public CurrentDoorStateCharacteristic(GarageDoor door) { - super("0000000E-0000-1000-8000-0026BB765291", false, true, "Current Door State", 4); - this.door = door; - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - protected CompletableFuture getValue() { - return door.getCurrentDoorState().thenApply(s -> s.getCode()); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - door.subscribeCurrentDoorState(callback); - } - - @Override - public void unsubscribe() { - door.unsubscribeCurrentDoorState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/garage/TargetDoorStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/garage/TargetDoorStateCharacteristic.java deleted file mode 100644 index 20e8c30a5..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/garage/TargetDoorStateCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.garage; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.GarageDoor; -import io.github.hapjava.accessories.properties.DoorState; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class TargetDoorStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final GarageDoor door; - - public TargetDoorStateCharacteristic(GarageDoor door) { - super("00000032-0000-1000-8000-0026BB765291", true, true, "Target Door State", 1); - this.door = door; - } - - @Override - protected void setValue(Integer value) throws Exception { - door.setTargetDoorState(DoorState.fromCode(value)); - } - - @Override - protected CompletableFuture getValue() { - return door.getTargetDoorState().thenApply(s -> s.getCode()); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - door.subscribeTargetDoorState(callback); - } - - @Override - public void unsubscribe() { - door.unsubscribeTargetDoorState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/humiditysensor/CurrentRelativeHumidityCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/humiditysensor/CurrentRelativeHumidityCharacteristic.java deleted file mode 100644 index 5dda83acf..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/humiditysensor/CurrentRelativeHumidityCharacteristic.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.github.hapjava.impl.characteristics.humiditysensor; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.HumiditySensor; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.FloatCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CurrentRelativeHumidityCharacteristic extends FloatCharacteristic - implements EventableCharacteristic { - - private final HumiditySensor sensor; - - public CurrentRelativeHumidityCharacteristic(HumiditySensor sensor) { - super( - "00000010-0000-1000-8000-0026BB765291", - false, - true, - "Current relative humidity", - 0, - 100, - 0.1, - "%"); - this.sensor = sensor; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - sensor.subscribeCurrentRelativeHumidity(callback); - } - - @Override - public void unsubscribe() { - sensor.unsubscribeCurrentRelativeHumidity(); - } - - @Override - protected void setValue(Double value) throws Exception { - // Read Only - } - - @Override - protected CompletableFuture getDoubleValue() { - return sensor.getCurrentRelativeHumidity(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/information/Identify.java b/src/main/java/io/github/hapjava/impl/characteristics/information/Identify.java deleted file mode 100644 index 097cda764..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/information/Identify.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.hapjava.impl.characteristics.information; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.characteristics.WriteOnlyBooleanCharacteristic; - -public class Identify extends WriteOnlyBooleanCharacteristic { - - private HomekitAccessory accessory; - - public Identify(HomekitAccessory accessory) throws Exception { - super( - "00000014-0000-1000-8000-0026BB765291", - "Identifies the accessory via a physical action on the accessory"); - this.accessory = accessory; - } - - @Override - public void setValue(Boolean value) throws Exception { - if (value) { - accessory.identify(); - } - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/information/Manufacturer.java b/src/main/java/io/github/hapjava/impl/characteristics/information/Manufacturer.java deleted file mode 100644 index 8a43fce08..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/information/Manufacturer.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.github.hapjava.impl.characteristics.information; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.characteristics.StaticStringCharacteristic; - -public class Manufacturer extends StaticStringCharacteristic { - - public Manufacturer(HomekitAccessory accessory) throws Exception { - super( - "00000020-0000-1000-8000-0026BB765291", - "The name of the manufacturer", - accessory.getManufacturer()); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/information/Model.java b/src/main/java/io/github/hapjava/impl/characteristics/information/Model.java deleted file mode 100644 index aa4235900..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/information/Model.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.github.hapjava.impl.characteristics.information; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.characteristics.StaticStringCharacteristic; - -public class Model extends StaticStringCharacteristic { - - public Model(HomekitAccessory accessory) throws Exception { - super("00000021-0000-1000-8000-0026BB765291", "The name of the model", accessory.getModel()); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/information/SerialNumber.java b/src/main/java/io/github/hapjava/impl/characteristics/information/SerialNumber.java deleted file mode 100644 index a4f90564b..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/information/SerialNumber.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.github.hapjava.impl.characteristics.information; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.characteristics.StaticStringCharacteristic; - -public class SerialNumber extends StaticStringCharacteristic { - - public SerialNumber(HomekitAccessory accessory) throws Exception { - super( - "00000030-0000-1000-8000-0026BB765291", - "The serial number of the accessory", - accessory.getSerialNumber()); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/leaksensor/LeakDetectedStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/leaksensor/LeakDetectedStateCharacteristic.java deleted file mode 100644 index ba29c1dbc..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/leaksensor/LeakDetectedStateCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.leaksensor; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.LeakSensor; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class LeakDetectedStateCharacteristic extends BooleanCharacteristic - implements EventableCharacteristic { - - private final LeakSensor leakSensor; - - public LeakDetectedStateCharacteristic(LeakSensor leakSensor) { - super("00000070-0000-1000-8000-0026BB765291", false, true, "Leak Detected"); - this.leakSensor = leakSensor; - } - - @Override - protected CompletableFuture getValue() { - return leakSensor.getLeakDetected(); - } - - @Override - protected void setValue(Boolean value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - leakSensor.subscribeLeakDetected(callback); - } - - @Override - public void unsubscribe() { - leakSensor.unsubscribeLeakDetected(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/light/AmbientLightLevelCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/light/AmbientLightLevelCharacteristic.java deleted file mode 100644 index b280ceb05..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/light/AmbientLightLevelCharacteristic.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.github.hapjava.impl.characteristics.light; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.LightSensor; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.FloatCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class AmbientLightLevelCharacteristic extends FloatCharacteristic - implements EventableCharacteristic { - - private final LightSensor lightSensor; - - public AmbientLightLevelCharacteristic(LightSensor lightSensor) { - super( - "0000006B-0000-1000-8000-0026BB765291", - false, - true, - "Current ambient light level", - 0.0001, - 100000, - 0.0001, - "lux"); - this.lightSensor = lightSensor; - } - - @Override - protected void setValue(Double value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - lightSensor.subscribeCurrentAmbientLightLevel(callback); - } - - @Override - public void unsubscribe() { - lightSensor.unsubscribeCurrentAmbientLightLevel(); - } - - @Override - protected CompletableFuture getDoubleValue() { - return lightSensor.getCurrentAmbientLightLevel(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/BrightnessCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/BrightnessCharacteristic.java deleted file mode 100644 index 7dc85c619..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/BrightnessCharacteristic.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.impl.characteristics.lightbulb; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.DimmableLightbulb; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class BrightnessCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final DimmableLightbulb lightbulb; - - public BrightnessCharacteristic(DimmableLightbulb lightbulb) { - super( - "00000008-0000-1000-8000-0026BB765291", - true, - true, - "Adjust brightness of the light", - 0, - 100, - "%"); - this.lightbulb = lightbulb; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - lightbulb.subscribeBrightness(callback); - } - - @Override - public void unsubscribe() { - lightbulb.unsubscribeBrightness(); - } - - @Override - protected void setValue(Integer value) throws Exception { - lightbulb.setBrightness(value); - } - - @Override - protected CompletableFuture getValue() { - return lightbulb.getBrightness(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/HueCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/HueCharacteristic.java deleted file mode 100644 index ea9df9457..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/HueCharacteristic.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.impl.characteristics.lightbulb; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.ColorfulLightbulb; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.FloatCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class HueCharacteristic extends FloatCharacteristic implements EventableCharacteristic { - - private final ColorfulLightbulb lightbulb; - - public HueCharacteristic(ColorfulLightbulb lightbulb) { - super( - "00000013-0000-1000-8000-0026BB765291", - true, - true, - "Adjust hue of the light", - 0, - 360, - 1, - "arcdegrees"); - this.lightbulb = lightbulb; - } - - @Override - protected void setValue(Double value) throws Exception { - lightbulb.setHue(value); - } - - @Override - protected CompletableFuture getDoubleValue() { - return lightbulb.getHue(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - lightbulb.subscribeHue(callback); - } - - @Override - public void unsubscribe() { - lightbulb.unsubscribeHue(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/SaturationCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/SaturationCharacteristic.java deleted file mode 100644 index ca48a31f0..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/lightbulb/SaturationCharacteristic.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.github.hapjava.impl.characteristics.lightbulb; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.ColorfulLightbulb; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.FloatCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class SaturationCharacteristic extends FloatCharacteristic - implements EventableCharacteristic { - - private final ColorfulLightbulb lightbulb; - - public SaturationCharacteristic(ColorfulLightbulb lightbulb) { - super( - "0000002F-0000-1000-8000-0026BB765291", - true, - true, - "Adjust saturation of the light", - 0, - 100, - 1, - "%"); - this.lightbulb = lightbulb; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - lightbulb.subscribeSaturation(callback); - } - - @Override - public void unsubscribe() { - lightbulb.unsubscribeSaturation(); - } - - @Override - protected void setValue(Double value) throws Exception { - lightbulb.setSaturation(value); - } - - @Override - protected CompletableFuture getDoubleValue() { - return lightbulb.getSaturation(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/lock/mechanism/CurrentLockMechanismStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/lock/mechanism/CurrentLockMechanismStateCharacteristic.java deleted file mode 100644 index 1182c43e9..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/lock/mechanism/CurrentLockMechanismStateCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.lock.mechanism; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.LockMechanism; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CurrentLockMechanismStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final LockMechanism lock; - - public CurrentLockMechanismStateCharacteristic(LockMechanism lock) { - super("0000001D-0000-1000-8000-0026BB765291", false, true, "Current lock state", 3); - this.lock = lock; - } - - @Override - protected void setValue(Integer value) throws Exception { - // Not writable - } - - @Override - protected CompletableFuture getValue() { - return lock.getCurrentMechanismState().thenApply(s -> s.getCode()); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - lock.subscribeCurrentMechanismState(callback); - } - - @Override - public void unsubscribe() { - lock.unsubscribeCurrentMechanismState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/lock/mechanism/TargetLockMechanismStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/lock/mechanism/TargetLockMechanismStateCharacteristic.java deleted file mode 100644 index e351c4c0b..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/lock/mechanism/TargetLockMechanismStateCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.lock.mechanism; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.LockableLockMechanism; -import io.github.hapjava.accessories.properties.LockMechanismState; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class TargetLockMechanismStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final LockableLockMechanism lock; - - public TargetLockMechanismStateCharacteristic(LockableLockMechanism lock) { - super("0000001E-0000-1000-8000-0026BB765291", true, true, "Current lock state", 3); - this.lock = lock; - } - - @Override - protected void setValue(Integer value) throws Exception { - lock.setTargetMechanismState(LockMechanismState.fromCode(value)); - } - - @Override - protected CompletableFuture getValue() { - return lock.getTargetMechanismState().thenApply(s -> s.getCode()); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - lock.subscribeTargetMechanismState(callback); - } - - @Override - public void unsubscribe() { - lock.unsubscribeTargetMechanismState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/motionsensor/MotionDetectedStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/motionsensor/MotionDetectedStateCharacteristic.java deleted file mode 100644 index 1c451fe32..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/motionsensor/MotionDetectedStateCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.motionsensor; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.MotionSensor; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class MotionDetectedStateCharacteristic extends BooleanCharacteristic - implements EventableCharacteristic { - - private final MotionSensor motionSensor; - - public MotionDetectedStateCharacteristic(MotionSensor motionSensor) { - super("00000022-0000-1000-8000-0026BB765291", false, true, "Motion Detected"); - this.motionSensor = motionSensor; - } - - @Override - protected CompletableFuture getValue() { - return motionSensor.getMotionDetected(); - } - - @Override - protected void setValue(Boolean value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - motionSensor.subscribeMotionDetected(callback); - } - - @Override - public void unsubscribe() { - motionSensor.unsubscribeMotionDetected(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/occupancysensor/OccupancyDetectedStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/occupancysensor/OccupancyDetectedStateCharacteristic.java deleted file mode 100644 index 813101039..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/occupancysensor/OccupancyDetectedStateCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.occupancysensor; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.OccupancySensor; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class OccupancyDetectedStateCharacteristic extends BooleanCharacteristic - implements EventableCharacteristic { - - private final OccupancySensor occupancySensor; - - public OccupancyDetectedStateCharacteristic(OccupancySensor occupancySensor) { - super("00000071-0000-1000-8000-0026BB765291", false, true, "Occupancy Detected"); - this.occupancySensor = occupancySensor; - } - - @Override - protected CompletableFuture getValue() { - return occupancySensor.getOccupancyDetected(); - } - - @Override - protected void setValue(Boolean value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - occupancySensor.subscribeOccupancyDetected(callback); - } - - @Override - public void unsubscribe() { - occupancySensor.unsubscribeOccupancyDetected(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/outlet/OutletInUseCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/outlet/OutletInUseCharacteristic.java deleted file mode 100644 index 98bd2108b..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/outlet/OutletInUseCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.outlet; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.Outlet; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class OutletInUseCharacteristic extends BooleanCharacteristic - implements EventableCharacteristic { - - private final Outlet outlet; - - public OutletInUseCharacteristic(Outlet outlet) { - super("00000026-0000-1000-8000-0026BB765291", false, true, "The outlet is in use"); - this.outlet = outlet; - } - - @Override - protected void setValue(Boolean value) throws Exception { - // Read Only - } - - @Override - protected CompletableFuture getValue() { - return outlet.getOutletInUse(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - outlet.subscribeOutletInUse(callback); - } - - @Override - public void unsubscribe() { - outlet.unsubscribeOutletInUse(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/CurrentSecuritySystemStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/CurrentSecuritySystemStateCharacteristic.java deleted file mode 100644 index 0d0b1b23e..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/CurrentSecuritySystemStateCharacteristic.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.hapjava.impl.characteristics.securitysystem; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.SecuritySystem; -import io.github.hapjava.accessories.properties.CurrentSecuritySystemState; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CurrentSecuritySystemStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final SecuritySystem securitySystem; - - public CurrentSecuritySystemStateCharacteristic(SecuritySystem securitySystem) { - super("00000066-0000-1000-8000-0026BB765291", false, true, "Current security system state", 4); - this.securitySystem = securitySystem; - } - - @Override - protected CompletableFuture getValue() { - return securitySystem - .getCurrentSecuritySystemState() - .thenApply(CurrentSecuritySystemState::getCode); - } - - @Override - protected void setValue(Integer value) throws Exception { - // Not writable - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - securitySystem.subscribeCurrentSecuritySystemState(callback); - } - - @Override - public void unsubscribe() { - securitySystem.unsubscribeCurrentSecuritySystemState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/SecuritySystemAlarmTypeCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/SecuritySystemAlarmTypeCharacteristic.java deleted file mode 100644 index 772943ba9..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/SecuritySystemAlarmTypeCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.securitysystem; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.SecuritySystem; -import io.github.hapjava.accessories.properties.SecuritySystemAlarmType; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class SecuritySystemAlarmTypeCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final SecuritySystem securitySystem; - - public SecuritySystemAlarmTypeCharacteristic(SecuritySystem securitySystem) { - super("0000008E-0000-1000-8000-0026BB765291", false, true, "Security system alarm type", 1); - this.securitySystem = securitySystem; - } - - @Override - protected CompletableFuture getValue() { - return securitySystem.getAlarmTypeState().thenApply(SecuritySystemAlarmType::getCode); - } - - @Override - protected void setValue(Integer value) throws Exception { - // Not writable - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - securitySystem.subscribeAlarmTypeState(callback); - } - - @Override - public void unsubscribe() { - securitySystem.unsubscribeAlarmTypeState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/TargetSecuritySystemStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/TargetSecuritySystemStateCharacteristic.java deleted file mode 100644 index 7357b43cd..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/securitysystem/TargetSecuritySystemStateCharacteristic.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.hapjava.impl.characteristics.securitysystem; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.SecuritySystem; -import io.github.hapjava.accessories.properties.TargetSecuritySystemState; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class TargetSecuritySystemStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final SecuritySystem securitySystem; - - public TargetSecuritySystemStateCharacteristic(SecuritySystem securitySystem) { - super("00000067-0000-1000-8000-0026BB765291", true, true, "Target security system state", 3); - this.securitySystem = securitySystem; - } - - @Override - protected CompletableFuture getValue() { - return securitySystem - .getTargetSecuritySystemState() - .thenApply(TargetSecuritySystemState::getCode); - } - - @Override - protected void setValue(Integer value) throws Exception { - securitySystem.setTargetSecuritySystemState(TargetSecuritySystemState.fromCode(value)); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - securitySystem.subscribeTargetSecuritySystemState(callback); - } - - @Override - public void unsubscribe() { - securitySystem.unsubscribeTargetSecuritySystemState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/smokesensor/SmokeDetectedCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/smokesensor/SmokeDetectedCharacteristic.java deleted file mode 100644 index e9823292d..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/smokesensor/SmokeDetectedCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.smokesensor; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.SmokeSensor; -import io.github.hapjava.accessories.properties.SmokeDetectedState; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class SmokeDetectedCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final SmokeSensor smokeSensor; - - public SmokeDetectedCharacteristic(SmokeSensor smokeSensor) { - super("00000076-0000-1000-8000-0026BB765291", false, true, "Smoke Detected", 1); - this.smokeSensor = smokeSensor; - } - - @Override - protected CompletableFuture getValue() { - return smokeSensor.getSmokeDetectedState().thenApply(SmokeDetectedState::getCode); - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - smokeSensor.subscribeSmokeDetectedState(callback); - } - - @Override - public void unsubscribe() { - smokeSensor.unsubscribeSmokeDetectedState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/AbstractHeatingCoolingModeCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/AbstractHeatingCoolingModeCharacteristic.java deleted file mode 100644 index e28ffddbe..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/AbstractHeatingCoolingModeCharacteristic.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.accessories.properties.ThermostatMode; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -abstract class AbstractHeatingCoolingModeCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - public AbstractHeatingCoolingModeCharacteristic( - String type, boolean isWritable, String description) { - super(type, isWritable, true, description, 3); - } - - @Override - protected final void setValue(Integer value) throws Exception { - setModeValue(ThermostatMode.fromCode(value)); - } - - @Override - protected final CompletableFuture getValue() { - return getModeValue().thenApply(t -> t.getCode()); - } - - protected abstract void setModeValue(ThermostatMode mode) throws Exception; - - protected abstract CompletableFuture getModeValue(); -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/AbstractTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/AbstractTemperatureCharacteristic.java deleted file mode 100644 index 5f1dc7f1c..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/AbstractTemperatureCharacteristic.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.accessories.TemperatureSensor; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.FloatCharacteristic; - -public abstract class AbstractTemperatureCharacteristic extends FloatCharacteristic - implements EventableCharacteristic { - - public AbstractTemperatureCharacteristic( - String type, boolean isWritable, String description, TemperatureSensor sensor) { - super( - type, - isWritable, - true, - description, - sensor.getMinimumTemperature(), - sensor.getMaximumTemperature(), - 0.1, - "celsius"); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CoolingThresholdTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CoolingThresholdTemperatureCharacteristic.java deleted file mode 100644 index 0b2d1b4f8..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CoolingThresholdTemperatureCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.thermostat.CoolingThermostat; -import java.util.concurrent.CompletableFuture; - -public class CoolingThresholdTemperatureCharacteristic extends AbstractTemperatureCharacteristic { - - private final CoolingThermostat thermostat; - - public CoolingThresholdTemperatureCharacteristic(CoolingThermostat thermostat) { - super( - "0000000D-0000-1000-8000-0026BB765291", - true, - "Temperature above which cooling will be active", - thermostat); - this.thermostat = thermostat; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - thermostat.subscribeCoolingThresholdTemperature(callback); - } - - @Override - public void unsubscribe() { - thermostat.unsubscribeCoolingThresholdTemperature(); - } - - @Override - protected CompletableFuture getDoubleValue() { - return thermostat.getCoolingThresholdTemperature(); - } - - @Override - protected void setValue(Double value) throws Exception { - thermostat.setCoolingThresholdTemperature(value); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CurrentHeatingCoolingModeCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CurrentHeatingCoolingModeCharacteristic.java deleted file mode 100644 index 26c4ac987..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CurrentHeatingCoolingModeCharacteristic.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.properties.ThermostatMode; -import io.github.hapjava.accessories.thermostat.BasicThermostat; -import java.util.concurrent.CompletableFuture; - -public class CurrentHeatingCoolingModeCharacteristic - extends AbstractHeatingCoolingModeCharacteristic { - - private final BasicThermostat thermostat; - - public CurrentHeatingCoolingModeCharacteristic(BasicThermostat thermostat) { - super("0000000F-0000-1000-8000-0026BB765291", false, "Current Mode"); - this.thermostat = thermostat; - } - - @Override - protected void setModeValue(ThermostatMode mode) throws Exception { - // Not writable - } - - @Override - protected CompletableFuture getModeValue() { - return thermostat.getCurrentMode(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - thermostat.subscribeCurrentMode(callback); - } - - @Override - public void unsubscribe() { - thermostat.unsubscribeCurrentMode(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CurrentTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CurrentTemperatureCharacteristic.java deleted file mode 100644 index 7745c56cc..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/CurrentTemperatureCharacteristic.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.TemperatureSensor; -import java.util.concurrent.CompletableFuture; - -public class CurrentTemperatureCharacteristic extends AbstractTemperatureCharacteristic { - - private final TemperatureSensor sensor; - - public CurrentTemperatureCharacteristic(TemperatureSensor thermostat) { - super("00000011-0000-1000-8000-0026BB765291", false, "Current Temperature", thermostat); - this.sensor = thermostat; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - sensor.subscribeCurrentTemperature(callback); - } - - @Override - public void unsubscribe() { - sensor.unsubscribeCurrentTemperature(); - } - - @Override - protected CompletableFuture getDoubleValue() { - return sensor.getCurrentTemperature(); - } - - @Override - protected void setValue(Double value) throws Exception { - // Not writable - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/HeatingThresholdTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/HeatingThresholdTemperatureCharacteristic.java deleted file mode 100644 index dba7af9a2..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/HeatingThresholdTemperatureCharacteristic.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.thermostat.HeatingThermostat; -import java.util.concurrent.CompletableFuture; - -public class HeatingThresholdTemperatureCharacteristic extends AbstractTemperatureCharacteristic { - - private final HeatingThermostat thermostat; - - public HeatingThresholdTemperatureCharacteristic(HeatingThermostat thermostat) { - super( - "00000012-0000-1000-8000-0026BB765291", - true, - "Temperature below which heating will be active", - thermostat); - this.thermostat = thermostat; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - thermostat.subscribeHeatingThresholdTemperature(callback); - } - - @Override - public void unsubscribe() { - thermostat.unsubscribeHeatingThresholdTemperature(); - } - - @Override - protected CompletableFuture getDoubleValue() { - return thermostat.getHeatingThresholdTemperature(); - } - - @Override - protected void setValue(Double value) throws Exception { - thermostat.setHeatingThresholdTemperature(value); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TargetHeatingCoolingModeCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TargetHeatingCoolingModeCharacteristic.java deleted file mode 100644 index 238af49ab..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TargetHeatingCoolingModeCharacteristic.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.properties.ThermostatMode; -import io.github.hapjava.accessories.thermostat.BasicThermostat; -import java.util.concurrent.CompletableFuture; - -public class TargetHeatingCoolingModeCharacteristic - extends AbstractHeatingCoolingModeCharacteristic { - - private final BasicThermostat thermostat; - - public TargetHeatingCoolingModeCharacteristic(BasicThermostat thermostat) { - super("00000033-0000-1000-8000-0026BB765291", true, "Target Mode"); - this.thermostat = thermostat; - } - - @Override - protected void setModeValue(ThermostatMode mode) throws Exception { - thermostat.setTargetMode(mode); - } - - @Override - protected CompletableFuture getModeValue() { - return thermostat.getTargetMode(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - thermostat.subscribeTargetMode(callback); - } - - @Override - public void unsubscribe() { - thermostat.unsubscribeTargetMode(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TargetTemperatureCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TargetTemperatureCharacteristic.java deleted file mode 100644 index 1c7f9274e..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TargetTemperatureCharacteristic.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.thermostat.BasicThermostat; -import java.util.concurrent.CompletableFuture; - -public class TargetTemperatureCharacteristic extends AbstractTemperatureCharacteristic { - - private final BasicThermostat thermostat; - - public TargetTemperatureCharacteristic(BasicThermostat thermostat) { - super("00000035-0000-1000-8000-0026BB765291", true, "Target Temperature", thermostat); - this.thermostat = thermostat; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - thermostat.subscribeTargetTemperature(callback); - } - - @Override - public void unsubscribe() { - thermostat.unsubscribeTargetTemperature(); - } - - @Override - protected CompletableFuture getDoubleValue() { - return thermostat.getTargetTemperature(); - } - - @Override - protected void setValue(Double value) throws Exception { - thermostat.setTargetTemperature(value); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TemperatureUnitsCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TemperatureUnitsCharacteristic.java deleted file mode 100644 index a24a5fc74..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/thermostat/TemperatureUnitsCharacteristic.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.hapjava.impl.characteristics.thermostat; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.properties.TemperatureUnit; -import io.github.hapjava.accessories.thermostat.BasicThermostat; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class TemperatureUnitsCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final BasicThermostat thermostat; - - public TemperatureUnitsCharacteristic(BasicThermostat thermostat) { - super("00000036-0000-1000-8000-0026BB765291", true, true, "The temperature unit", 1); - this.thermostat = thermostat; - } - - @Override - protected void setValue(Integer value) throws Exception { - thermostat.setTemperatureUnit( - value == 1 ? TemperatureUnit.FAHRENHEIT : TemperatureUnit.CELSIUS); - } - - @Override - protected CompletableFuture getValue() { - return CompletableFuture.completedFuture(thermostat.getTemperatureUnit().getCode()); - } - - @Override - public void subscribe(final HomekitCharacteristicChangeCallback callback) { - thermostat.subscribeTemperatureUnit(callback); - } - - @Override - public void unsubscribe() { - thermostat.unsubscribeTemperatureUnit(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/valve/SetDurationCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/valve/SetDurationCharacteristic.java deleted file mode 100644 index 75feae8c2..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/valve/SetDurationCharacteristic.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.hapjava.impl.characteristics.valve; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.ValveWithTimer; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class SetDurationCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - private final ValveWithTimer valve; - - public SetDurationCharacteristic(ValveWithTimer valve) { - super("000000D3-0000-1000-8000-0026BB765291", true, true, "Set Duration", 0, 3600, "seconds"); - this.valve = valve; - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - valve.subscribeSetDuration(callback); - } - - @Override - public void unsubscribe() { - valve.unsubscribeSetDuration(); - } - - @Override - protected void setValue(Integer value) throws Exception { - valve.setSetDuration(value); - } - - @Override - protected CompletableFuture getValue() { - return valve.getSetDuration(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/valve/ValveTypeCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/valve/ValveTypeCharacteristic.java deleted file mode 100644 index 3fe6b0aeb..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/valve/ValveTypeCharacteristic.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.hapjava.impl.characteristics.valve; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.Valve; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class ValveTypeCharacteristic extends EnumCharacteristic implements EventableCharacteristic { - - private final Valve valve; - - public ValveTypeCharacteristic(Valve valve) { - super("000000D5-0000-1000-8000-0026BB765291", false, true, "Valve Type", 3); - this.valve = valve; - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read only - } - - @Override - protected CompletableFuture getValue() { - return valve.getValveType().thenApply(v -> v.getCode()); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - valve.subscribeValveType(callback); - } - - @Override - public void unsubscribe() { - valve.unsubscribeValveType(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentHorizontalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentHorizontalTiltAngleCharacteristic.java deleted file mode 100644 index d4b57acb0..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentHorizontalTiltAngleCharacteristic.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.HorizontalTiltingWindowCovering; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CurrentHorizontalTiltAngleCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final HorizontalTiltingWindowCovering windowCovering; - - public CurrentHorizontalTiltAngleCharacteristic(HorizontalTiltingWindowCovering windowCovering) { - super( - "0000006C-0000-1000-8000-0026BB765291", - false, - true, - "The current horizontal tilt angle", - -90, - 90, - "Arc Degree"); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - protected CompletableFuture getValue() { - return windowCovering.getCurrentHorizontalTiltAngle(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - windowCovering.subscribeCurrentHorizontalTiltAngle(callback); - } - - @Override - public void unsubscribe() { - windowCovering.unsubscribeCurrentHorizontalTiltAngle(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentPositionCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentPositionCharacteristic.java deleted file mode 100644 index 22fbfd171..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentPositionCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.BasicWindowCovering; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CurrentPositionCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final BasicWindowCovering windowCovering; - - public CurrentPositionCharacteristic(BasicWindowCovering windowCovering) { - super("0000006D-0000-1000-8000-0026BB765291", false, true, "The current position", 0, 100, "%"); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - protected CompletableFuture getValue() { - return windowCovering.getCurrentPosition(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - windowCovering.subscribeCurrentPosition(callback); - } - - @Override - public void unsubscribe() { - windowCovering.unsubscribeCurrentPosition(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentVerticalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentVerticalTiltAngleCharacteristic.java deleted file mode 100644 index 371e5939b..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/CurrentVerticalTiltAngleCharacteristic.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.VerticalTiltingWindowCovering; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class CurrentVerticalTiltAngleCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final VerticalTiltingWindowCovering windowCovering; - - public CurrentVerticalTiltAngleCharacteristic(VerticalTiltingWindowCovering windowCovering) { - super( - "0000006E-0000-1000-8000-0026BB765291", - false, - true, - "The current vertical tilt angle", - -90, - 90, - "Arc Degree"); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read Only - } - - @Override - protected CompletableFuture getValue() { - return windowCovering.getCurrentVerticalTiltAngle(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - windowCovering.subscribeCurrentVerticalTiltAngle(callback); - } - - @Override - public void unsubscribe() { - windowCovering.unsubscribeCurrentVerticalTiltAngle(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/HoldPositionCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/HoldPositionCharacteristic.java deleted file mode 100644 index 09edf8b11..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/HoldPositionCharacteristic.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.accessories.HoldPositionWindowCovering; -import io.github.hapjava.characteristics.BooleanCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class HoldPositionCharacteristic extends BooleanCharacteristic { - - private final HoldPositionWindowCovering windowCovering; - - public HoldPositionCharacteristic(HoldPositionWindowCovering windowCovering) { - super("0000006F-0000-1000-8000-0026BB765291", true, false, "Whether or not to hold position"); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Boolean value) throws Exception { - this.windowCovering.setHoldPosition(value); - } - - @Override - protected CompletableFuture getValue() { - // Write only - return CompletableFuture.completedFuture(null); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/PositionStateCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/PositionStateCharacteristic.java deleted file mode 100644 index 80e87ad01..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/PositionStateCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.BasicWindowCovering; -import io.github.hapjava.characteristics.EnumCharacteristic; -import io.github.hapjava.characteristics.EventableCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class PositionStateCharacteristic extends EnumCharacteristic - implements EventableCharacteristic { - - private final BasicWindowCovering windowCovering; - - public PositionStateCharacteristic(BasicWindowCovering windowCovering) { - super("00000072-0000-1000-8000-0026BB765291", false, true, "The position state", 2); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Integer value) throws Exception { - // Read only - } - - @Override - protected CompletableFuture getValue() { - return windowCovering.getPositionState().thenApply(v -> v.getCode()); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - windowCovering.subscribePositionState(callback); - } - - @Override - public void unsubscribe() { - windowCovering.unsubscribePositionState(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetHorizontalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetHorizontalTiltAngleCharacteristic.java deleted file mode 100644 index 835ec6449..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetHorizontalTiltAngleCharacteristic.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.HorizontalTiltingWindowCovering; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class TargetHorizontalTiltAngleCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final HorizontalTiltingWindowCovering windowCovering; - - public TargetHorizontalTiltAngleCharacteristic(HorizontalTiltingWindowCovering windowCovering) { - super( - "0000007B-0000-1000-8000-0026BB765291", - true, - true, - "The target horizontal tilt angle", - -90, - 90, - "Arc Degree"); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Integer value) throws Exception { - windowCovering.setTargetHorizontalTiltAngle(value); - } - - @Override - protected CompletableFuture getValue() { - return windowCovering.getTargetHorizontalTiltAngle(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - windowCovering.subscribeTargetHorizontalTiltAngle(callback); - } - - @Override - public void unsubscribe() { - windowCovering.unsubscribeTargetHorizontalTiltAngle(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetPositionCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetPositionCharacteristic.java deleted file mode 100644 index 0db8fe6df..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetPositionCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.BasicWindowCovering; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class TargetPositionCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final BasicWindowCovering windowCovering; - - public TargetPositionCharacteristic(BasicWindowCovering windowCovering) { - super("0000007C-0000-1000-8000-0026BB765291", true, true, "The target position", 0, 100, "%"); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Integer value) throws Exception { - windowCovering.setTargetPosition(value); - } - - @Override - protected CompletableFuture getValue() { - return windowCovering.getTargetPosition(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - windowCovering.subscribeTargetPosition(callback); - } - - @Override - public void unsubscribe() { - windowCovering.unsubscribeTargetPosition(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetVerticalTiltAngleCharacteristic.java b/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetVerticalTiltAngleCharacteristic.java deleted file mode 100644 index 20472689e..000000000 --- a/src/main/java/io/github/hapjava/impl/characteristics/windowcovering/TargetVerticalTiltAngleCharacteristic.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.hapjava.impl.characteristics.windowcovering; - -import io.github.hapjava.HomekitCharacteristicChangeCallback; -import io.github.hapjava.accessories.VerticalTiltingWindowCovering; -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.characteristics.IntegerCharacteristic; -import java.util.concurrent.CompletableFuture; - -public class TargetVerticalTiltAngleCharacteristic extends IntegerCharacteristic - implements EventableCharacteristic { - - private final VerticalTiltingWindowCovering windowCovering; - - public TargetVerticalTiltAngleCharacteristic(VerticalTiltingWindowCovering windowCovering) { - super( - "0000007D-0000-1000-8000-0026BB765291", - true, - true, - "The target vertical tilt angle", - -90, - 90, - "Arc Degree"); - this.windowCovering = windowCovering; - } - - @Override - protected void setValue(Integer value) throws Exception { - windowCovering.setTargetVerticalTiltAngle(value); - } - - @Override - protected CompletableFuture getValue() { - return windowCovering.getTargetVerticalTiltAngle(); - } - - @Override - public void subscribe(HomekitCharacteristicChangeCallback callback) { - windowCovering.subscribeTargetVerticalTiltAngle(callback); - } - - @Override - public void unsubscribe() { - windowCovering.unsubscribeTargetVerticalTiltAngle(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/connections/SubscriptionManager.java b/src/main/java/io/github/hapjava/impl/connections/SubscriptionManager.java deleted file mode 100644 index 2a2fc693d..000000000 --- a/src/main/java/io/github/hapjava/impl/connections/SubscriptionManager.java +++ /dev/null @@ -1,149 +0,0 @@ -package io.github.hapjava.impl.connections; - -import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.impl.http.HomekitClientConnection; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.json.EventController; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SubscriptionManager { - - private static final Logger LOGGER = LoggerFactory.getLogger(SubscriptionManager.class); - - private final ConcurrentMap> subscriptions = - new ConcurrentHashMap<>(); - private final ConcurrentMap> reverse = - new ConcurrentHashMap<>(); - private final ConcurrentMap> - pendingNotifications = new ConcurrentHashMap<>(); - private int nestedBatches = 0; - - public synchronized void addSubscription( - int aid, - int iid, - EventableCharacteristic characteristic, - HomekitClientConnection connection) { - synchronized (this) { - if (!subscriptions.containsKey(characteristic)) { - subscriptions.putIfAbsent(characteristic, newSet()); - } - subscriptions.get(characteristic).add(connection); - if (subscriptions.get(characteristic).size() == 1) { - characteristic.subscribe( - () -> { - publish(aid, iid, characteristic); - }); - } - - if (!reverse.containsKey(connection)) { - reverse.putIfAbsent(connection, newSet()); - } - reverse.get(connection).add(characteristic); - LOGGER.info( - "Added subscription to " + characteristic.getClass() + " for " + connection.hashCode()); - } - } - - public synchronized void removeSubscription( - EventableCharacteristic characteristic, HomekitClientConnection connection) { - Set subscriptions = this.subscriptions.get(characteristic); - if (subscriptions != null) { - subscriptions.remove(connection); - if (subscriptions.size() == 0) { - characteristic.unsubscribe(); - } - } - - Set reverse = this.reverse.get(connection); - if (reverse != null) { - reverse.remove(characteristic); - } - LOGGER.info( - "Removed subscription to " + characteristic.getClass() + " for " + connection.hashCode()); - } - - public synchronized void removeConnection(HomekitClientConnection connection) { - Set characteristics = reverse.remove(connection); - pendingNotifications.remove(connection); - if (characteristics != null) { - for (EventableCharacteristic characteristic : characteristics) { - Set characteristicSubscriptions = - subscriptions.get(characteristic); - characteristicSubscriptions.remove(connection); - if (characteristicSubscriptions.isEmpty()) { - LOGGER.debug("Unsubscribing from characteristic as all subscriptions are closed"); - characteristic.unsubscribe(); - subscriptions.remove(characteristic); - } - } - } - LOGGER.debug("Removed connection {}", connection.hashCode()); - } - - private Set newSet() { - return Collections.newSetFromMap(new ConcurrentHashMap()); - } - - public synchronized void batchUpdate() { - ++this.nestedBatches; - } - - public synchronized void completeUpdateBatch() { - if (--this.nestedBatches == 0 && !pendingNotifications.isEmpty()) { - LOGGER.info("Publishing batched changes"); - for (ConcurrentMap.Entry> entry : - pendingNotifications.entrySet()) { - try { - HttpResponse message = new EventController().getMessage(entry.getValue()); - entry.getKey().outOfBand(message); - } catch (Exception e) { - LOGGER.error("Faled to create new event message", e); - } - } - pendingNotifications.clear(); - } - } - - public synchronized void publish(int accessoryId, int iid, EventableCharacteristic changed) { - if (nestedBatches != 0) { - LOGGER.info("Batching change for " + accessoryId); - PendingNotification notification = new PendingNotification(accessoryId, iid, changed); - for (HomekitClientConnection connection : subscriptions.get(changed)) { - if (!pendingNotifications.containsKey(connection)) { - pendingNotifications.put(connection, new ArrayList()); - } - pendingNotifications.get(connection).add(notification); - } - return; - } - - try { - HttpResponse message = new EventController().getMessage(accessoryId, iid, changed); - LOGGER.info("Publishing change for " + accessoryId); - for (HomekitClientConnection connection : subscriptions.get(changed)) { - connection.outOfBand(message); - } - } catch (Exception e) { - LOGGER.error("Failed to create new event message", e); - } - } - - /** Remove all existing subscriptions */ - public void removeAll() { - LOGGER.debug("Removing {} reverse connections from subscription manager", reverse.size()); - Iterator i = reverse.keySet().iterator(); - while (i.hasNext()) { - HomekitClientConnection connection = i.next(); - LOGGER.debug("Removing connection {}", connection.hashCode()); - removeConnection(connection); - } - LOGGER.debug("Subscription sizes are {} and {}", reverse.size(), subscriptions.size()); - } -} diff --git a/src/main/java/io/github/hapjava/impl/crypto/ChachaDecoder.java b/src/main/java/io/github/hapjava/impl/crypto/ChachaDecoder.java deleted file mode 100644 index 73a09b945..000000000 --- a/src/main/java/io/github/hapjava/impl/crypto/ChachaDecoder.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.github.hapjava.impl.crypto; - -import java.io.IOException; -import org.bouncycastle.crypto.engines.ChaChaEngine; -import org.bouncycastle.crypto.generators.Poly1305KeyGenerator; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; -import org.bouncycastle.crypto.tls.AlertDescription; -import org.bouncycastle.crypto.tls.TlsFatalAlert; -import org.bouncycastle.util.Arrays; - -public class ChachaDecoder { - - private final ChaChaEngine decryptCipher; - - public ChachaDecoder(byte[] key, byte[] nonce) throws IOException { - - this.decryptCipher = new ChaChaEngine(20); - - this.decryptCipher.init(false, new ParametersWithIV(new KeyParameter(key), nonce)); - } - - public byte[] decodeCiphertext(byte[] receivedMAC, byte[] additionalData, byte[] ciphertext) - throws IOException { - - KeyParameter macKey = initRecordMAC(decryptCipher); - - byte[] calculatedMAC = PolyKeyCreator.create(macKey, additionalData, ciphertext); - - if (!Arrays.constantTimeAreEqual(calculatedMAC, receivedMAC)) { - throw new TlsFatalAlert(AlertDescription.bad_record_mac); - } - - byte[] output = new byte[ciphertext.length]; - decryptCipher.processBytes(ciphertext, 0, ciphertext.length, output, 0); - - return output; - } - - public byte[] decodeCiphertext(byte[] receivedMAC, byte[] ciphertext) throws IOException { - return decodeCiphertext(receivedMAC, null, ciphertext); - } - - private KeyParameter initRecordMAC(ChaChaEngine cipher) { - byte[] firstBlock = new byte[64]; - cipher.processBytes(firstBlock, 0, firstBlock.length, firstBlock, 0); - - // NOTE: The BC implementation puts 'r' after 'k' - System.arraycopy(firstBlock, 0, firstBlock, 32, 16); - KeyParameter macKey = new KeyParameter(firstBlock, 16, 32); - Poly1305KeyGenerator.clamp(macKey.getKey()); - return macKey; - } -} diff --git a/src/main/java/io/github/hapjava/impl/crypto/ChachaEncoder.java b/src/main/java/io/github/hapjava/impl/crypto/ChachaEncoder.java deleted file mode 100644 index aab841877..000000000 --- a/src/main/java/io/github/hapjava/impl/crypto/ChachaEncoder.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.github.hapjava.impl.crypto; - -import java.io.IOException; -import org.bouncycastle.crypto.engines.ChaChaEngine; -import org.bouncycastle.crypto.generators.Poly1305KeyGenerator; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; - -public class ChachaEncoder { - - private final ChaChaEngine encryptCipher; - - public ChachaEncoder(byte[] key, byte[] nonce) throws IOException { - - this.encryptCipher = new ChaChaEngine(20); - - this.encryptCipher.init(true, new ParametersWithIV(new KeyParameter(key), nonce)); - } - - public byte[] encodeCiphertext(byte[] plaintext) throws IOException { - return encodeCiphertext(plaintext, null); - } - - public byte[] encodeCiphertext(byte[] plaintext, byte[] additionalData) throws IOException { - KeyParameter macKey = initRecordMAC(encryptCipher); - - byte[] ciphertext = new byte[plaintext.length]; - encryptCipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0); - - byte[] calculatedMAC = PolyKeyCreator.create(macKey, additionalData, ciphertext); - - byte[] ret = new byte[ciphertext.length + 16]; - System.arraycopy(ciphertext, 0, ret, 0, ciphertext.length); - System.arraycopy(calculatedMAC, 0, ret, ciphertext.length, 16); - return ret; - } - - private KeyParameter initRecordMAC(ChaChaEngine cipher) { - byte[] firstBlock = new byte[64]; - cipher.processBytes(firstBlock, 0, firstBlock.length, firstBlock, 0); - - // NOTE: The BC implementation puts 'r' after 'k' - System.arraycopy(firstBlock, 0, firstBlock, 32, 16); - KeyParameter macKey = new KeyParameter(firstBlock, 16, 32); - Poly1305KeyGenerator.clamp(macKey.getKey()); - return macKey; - } -} diff --git a/src/main/java/io/github/hapjava/impl/http/impl/LoggingHandler.java b/src/main/java/io/github/hapjava/impl/http/impl/LoggingHandler.java deleted file mode 100644 index 1bae4fa9f..000000000 --- a/src/main/java/io/github/hapjava/impl/http/impl/LoggingHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.github.hapjava.impl.http.impl; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.*; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import org.apache.commons.io.HexDump; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LoggingHandler extends ChannelDuplexHandler { - - private static final Logger logger = LoggerFactory.getLogger(NettyHomekitHttpService.class); - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if (logger.isTraceEnabled() && msg instanceof ByteBuf) { - logBytes("READ", (ByteBuf) msg, ctx); - } - super.channelRead(ctx, msg); - } - - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) - throws Exception { - if (logger.isTraceEnabled() && msg instanceof ByteBuf) { - logBytes("WRITE", (ByteBuf) msg, ctx); - } - super.write(ctx, msg, promise); - } - - private void logBytes(String type, ByteBuf buf, ChannelHandlerContext ctx) throws IOException { - if (buf.readableBytes() > 0) { - try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - byte[] bytes = new byte[buf.readableBytes()]; - buf.getBytes(0, bytes, 0, bytes.length); - HexDump.dump(bytes, 0, stream, 0); - stream.flush(); - logger.trace( - String.format( - "%s %s [%s]:%n%s%n", - type, - buf, - ctx.channel().remoteAddress().toString(), - stream.toString(StandardCharsets.UTF_8.name()))); - } - } - } -} diff --git a/src/main/java/io/github/hapjava/impl/jmdns/JmdnsHomekitAdvertiser.java b/src/main/java/io/github/hapjava/impl/jmdns/JmdnsHomekitAdvertiser.java deleted file mode 100644 index 062536708..000000000 --- a/src/main/java/io/github/hapjava/impl/jmdns/JmdnsHomekitAdvertiser.java +++ /dev/null @@ -1,93 +0,0 @@ -package io.github.hapjava.impl.jmdns; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; -import javax.jmdns.JmDNS; -import javax.jmdns.ServiceInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class JmdnsHomekitAdvertiser { - - private static final String SERVICE_TYPE = "_hap._tcp.local."; - - private final JmDNS jmdns; - private boolean discoverable = true; - private static final Logger logger = LoggerFactory.getLogger(JmdnsHomekitAdvertiser.class); - private boolean isAdvertising = false; - - private String label; - private String mac; - private int port; - private int configurationIndex; - - public JmdnsHomekitAdvertiser(InetAddress localAddress) throws UnknownHostException, IOException { - jmdns = JmDNS.create(localAddress); - } - - public synchronized void advertise(String label, String mac, int port, int configurationIndex) - throws Exception { - if (isAdvertising) { - throw new IllegalStateException("Homekit advertiser is already running"); - } - this.label = label; - this.mac = mac; - this.port = port; - this.configurationIndex = configurationIndex; - - logger.info("Advertising accessory " + label); - - registerService(); - - Runtime.getRuntime() - .addShutdownHook( - new Thread( - () -> { - logger.info("Stopping advertising in response to shutdown."); - jmdns.unregisterAllServices(); - })); - isAdvertising = true; - } - - public synchronized void stop() { - jmdns.unregisterAllServices(); - } - - public synchronized void setDiscoverable(boolean discoverable) throws IOException { - if (this.discoverable != discoverable) { - this.discoverable = discoverable; - if (isAdvertising) { - logger.info("Re-creating service due to change in discoverability to " + discoverable); - jmdns.unregisterAllServices(); - registerService(); - } - } - } - - public synchronized void setConfigurationIndex(int revision) throws IOException { - if (this.configurationIndex != revision) { - this.configurationIndex = revision; - if (isAdvertising) { - logger.info("Re-creating service due to change in configuration index to " + revision); - jmdns.unregisterAllServices(); - registerService(); - } - } - } - - private void registerService() throws IOException { - logger.info("Registering " + SERVICE_TYPE + " on port " + port); - Map props = new HashMap<>(); - props.put("sf", discoverable ? "1" : "0"); - props.put("id", mac); - props.put("md", label); - props.put("c#", Integer.toString(configurationIndex)); - props.put("s#", "1"); - props.put("ff", "0"); - props.put("ci", "1"); - jmdns.registerService(ServiceInfo.create(SERVICE_TYPE, label, port, 1, 1, props)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/pairing/PairSetupRequest.java b/src/main/java/io/github/hapjava/impl/pairing/PairSetupRequest.java deleted file mode 100644 index a7d7a0445..000000000 --- a/src/main/java/io/github/hapjava/impl/pairing/PairSetupRequest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.github.hapjava.impl.pairing; - -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.DecodeResult; -import java.math.BigInteger; - -abstract class PairSetupRequest { - - private static final short VALUE_STAGE_1 = 1; - private static final short VALUE_STAGE_2 = 3; - private static final short VALUE_STAGE_3 = 5; - - public static PairSetupRequest of(byte[] content) throws Exception { - DecodeResult d = TypeLengthValueUtils.decode(content); - short stage = d.getByte(MessageType.STATE); - switch (stage) { - case VALUE_STAGE_1: - return new Stage1Request(); - - case VALUE_STAGE_2: - return new Stage2Request(d); - - case VALUE_STAGE_3: - return new Stage3Request(d); - - default: - throw new Exception("Unknown pair process stage: " + stage); - } - } - - public abstract Stage getStage(); - - public static class Stage1Request extends PairSetupRequest { - @Override - public Stage getStage() { - return Stage.ONE; - } - } - - public static class Stage2Request extends PairSetupRequest { - - private final BigInteger a; - private final BigInteger m1; - - public Stage2Request(DecodeResult d) { - a = d.getBigInt(MessageType.PUBLIC_KEY); - m1 = d.getBigInt(MessageType.PROOF); - } - - public BigInteger getA() { - return a; - } - - public BigInteger getM1() { - return m1; - } - - @Override - public Stage getStage() { - return Stage.TWO; - } - } - - static class Stage3Request extends PairSetupRequest { - - private final byte[] messageData; - private final byte[] authTagData; - - public Stage3Request(DecodeResult d) { - messageData = new byte[d.getLength(MessageType.ENCRYPTED_DATA) - 16]; - authTagData = new byte[16]; - d.getBytes(MessageType.ENCRYPTED_DATA, messageData, 0); - d.getBytes(MessageType.ENCRYPTED_DATA, authTagData, messageData.length); - } - - public byte[] getMessageData() { - return messageData; - } - - public byte[] getAuthTagData() { - return authTagData; - } - - @Override - public Stage getStage() { - return Stage.THREE; - } - } -} diff --git a/src/main/java/io/github/hapjava/impl/pairing/PairingManager.java b/src/main/java/io/github/hapjava/impl/pairing/PairingManager.java deleted file mode 100644 index 934181309..000000000 --- a/src/main/java/io/github/hapjava/impl/pairing/PairingManager.java +++ /dev/null @@ -1,65 +0,0 @@ -package io.github.hapjava.impl.pairing; - -import io.github.hapjava.HomekitAuthInfo; -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.http.HttpRequest; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.responses.NotFoundResponse; -import io.github.hapjava.impl.responses.UnauthorizedResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PairingManager { - - private static final Logger logger = LoggerFactory.getLogger(PairingManager.class); - - private final HomekitAuthInfo authInfo; - private final HomekitRegistry registry; - - private SrpHandler srpHandler; - - public PairingManager(HomekitAuthInfo authInfo, HomekitRegistry registry) { - this.authInfo = authInfo; - this.registry = registry; - } - - public HttpResponse handle(HttpRequest httpRequest) throws Exception { - PairSetupRequest req = PairSetupRequest.of(httpRequest.getBody()); - - if (req.getStage() == Stage.ONE) { - logger.info("Starting pair for " + registry.getLabel()); - srpHandler = new SrpHandler(authInfo.getPin(), authInfo.getSalt()); - return srpHandler.handle(req); - } else if (req.getStage() == Stage.TWO) { - logger.debug("Entering second stage of pair for " + registry.getLabel()); - if (srpHandler == null) { - logger.warn("Received unexpected stage 2 request for " + registry.getLabel()); - return new UnauthorizedResponse(); - } else { - try { - return srpHandler.handle(req); - } catch (Exception e) { - srpHandler = null; // You don't get to try again - need a new key - logger.error("Exception encountered while processing pairing request", e); - return new UnauthorizedResponse(); - } - } - } else if (req.getStage() == Stage.THREE) { - logger.debug("Entering third stage of pair for " + registry.getLabel()); - if (srpHandler == null) { - logger.warn("Received unexpected stage 3 request for " + registry.getLabel()); - return new UnauthorizedResponse(); - } else { - FinalPairHandler handler = new FinalPairHandler(srpHandler.getK(), authInfo); - try { - return handler.handle(req); - } catch (Exception e) { - logger.error("Exception while finalizing pairing", e); - return new UnauthorizedResponse(); - } - } - } - - return new NotFoundResponse(); - } -} diff --git a/src/main/java/io/github/hapjava/impl/pairing/PairingResponse.java b/src/main/java/io/github/hapjava/impl/pairing/PairingResponse.java deleted file mode 100644 index 1291f66ee..000000000 --- a/src/main/java/io/github/hapjava/impl/pairing/PairingResponse.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.github.hapjava.impl.pairing; - -import io.github.hapjava.impl.responses.OkResponse; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -class PairingResponse extends OkResponse { - - private static final Map headers = - Collections.unmodifiableMap( - new HashMap() { - private static final long serialVersionUID = 1L; - - { - put("Content-type", "application/pairing+tlv8"); - } - }); - - public PairingResponse(byte[] body) { - super(body); - } - - @Override - public Map getHeaders() { - return headers; - } -} diff --git a/src/main/java/io/github/hapjava/impl/pairing/PairingUpdateController.java b/src/main/java/io/github/hapjava/impl/pairing/PairingUpdateController.java deleted file mode 100644 index 6eabd6992..000000000 --- a/src/main/java/io/github/hapjava/impl/pairing/PairingUpdateController.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.hapjava.impl.pairing; - -import io.github.hapjava.HomekitAuthInfo; -import io.github.hapjava.impl.http.HttpRequest; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.jmdns.JmdnsHomekitAdvertiser; -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.DecodeResult; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -public class PairingUpdateController { - - private final HomekitAuthInfo authInfo; - private final JmdnsHomekitAdvertiser advertiser; - - public PairingUpdateController(HomekitAuthInfo authInfo, JmdnsHomekitAdvertiser advertiser) { - this.authInfo = authInfo; - this.advertiser = advertiser; - } - - public HttpResponse handle(HttpRequest request) throws IOException { - DecodeResult d = TypeLengthValueUtils.decode(request.getBody()); - - int method = d.getByte(MessageType.METHOD); - if (method == 3) { // Add pairing - byte[] username = d.getBytes(MessageType.USERNAME); - byte[] ltpk = d.getBytes(MessageType.PUBLIC_KEY); - authInfo.createUser(authInfo.getMac() + new String(username, StandardCharsets.UTF_8), ltpk); - } else if (method == 4) { // Remove pairing - byte[] username = d.getBytes(MessageType.USERNAME); - authInfo.removeUser(authInfo.getMac() + new String(username, StandardCharsets.UTF_8)); - if (!authInfo.hasUser()) { - advertiser.setDiscoverable(true); - } - } else { - throw new RuntimeException("Unrecognized method: " + method); - } - return new PairingResponse(new byte[] {0x06, 0x01, 0x02}); - } -} diff --git a/src/main/java/io/github/hapjava/impl/pairing/Stage.java b/src/main/java/io/github/hapjava/impl/pairing/Stage.java deleted file mode 100644 index 1d5d3ef7d..000000000 --- a/src/main/java/io/github/hapjava/impl/pairing/Stage.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.github.hapjava.impl.pairing; - -public enum Stage { - ONE, - TWO, - THREE -} diff --git a/src/main/java/io/github/hapjava/impl/services/AbstractServiceImpl.java b/src/main/java/io/github/hapjava/impl/services/AbstractServiceImpl.java deleted file mode 100644 index 6898a5a0d..000000000 --- a/src/main/java/io/github/hapjava/impl/services/AbstractServiceImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.Service; -import io.github.hapjava.accessories.BatteryAccessory; -import io.github.hapjava.accessories.BatteryStatusAccessory; -import io.github.hapjava.characteristics.Characteristic; -import io.github.hapjava.impl.characteristics.common.BatteryLevelCharacteristic; -import io.github.hapjava.impl.characteristics.common.LowBatteryStatusCharacteristic; -import io.github.hapjava.impl.characteristics.common.Name; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -abstract class AbstractServiceImpl implements Service { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final String type; - private final List characteristics = new LinkedList<>(); - - /** - * This constructor has been deprecated and replaced with {@link #AbstractServiceImpl(String, - * HomekitAccessory, String)}. Usages of this constructor will need to manually configure {@link - * Name} characteristic and {@link BatteryLevelCharacteristic} if needed. - * - * @param type unique UUID of the service. This information can be obtained from HomeKit Accessory - * Simulator. - */ - @Deprecated - public AbstractServiceImpl(String type) { - this(type, null, null); - } - - /** - * Creates a new instance of this class with the specified UUID and {@link HomekitAccessory}. - * Download and install HomeKit Accessory Simulator to discover the corresponding UUID for - * the specific service. - * - *

The new service will automatically add {@link Name} characteristic. If the accessory is - * battery operated then it must implement {@link BatteryAccessory} and {@link - * BatteryLevelCharacteristic} will be added too. - * - * @param type unique UUID of the service. This information can be obtained from HomeKit Accessory - * Simulator. - * @param accessory HomeKit accessory exposed as a service. - * @param serviceName name of the service. This information is usually the name of the accessory. - */ - public AbstractServiceImpl(String type, HomekitAccessory accessory, String serviceName) { - this.type = type; - - if (accessory != null) { - // Add name characteristic - addCharacteristic(new Name(serviceName)); - - // If battery operated accessory then add BatteryLevelCharacteristic - if (accessory instanceof BatteryAccessory) { - logger.warn( - "Accessory {} implements BatteryAccessory, which was incorrectly used to advertise battery state and is not recognized by HomeKit. " - + "Battery-powered devices should report their battery status using LowBatteryStatusAccessory", - accessory.getClass()); - } - - // If battery operated accessory then add LowBatteryStatusAccessory - if (accessory instanceof BatteryStatusAccessory) { - BatteryStatusAccessory batteryStatusAccessory = (BatteryStatusAccessory) accessory; - addCharacteristic( - new LowBatteryStatusCharacteristic( - batteryStatusAccessory::getLowBatteryState, - batteryStatusAccessory::subscribeLowBatteryState, - batteryStatusAccessory::unsubscribeLowBatteryState)); - } - } - } - - @Override - public List getCharacteristics() { - return Collections.unmodifiableList(characteristics); - } - - @Override - public String getType() { - return type; - } - - protected void addCharacteristic(Characteristic characteristic) { - this.characteristics.add(characteristic); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/AccessoryInformationService.java b/src/main/java/io/github/hapjava/impl/services/AccessoryInformationService.java deleted file mode 100644 index eb464b4d0..000000000 --- a/src/main/java/io/github/hapjava/impl/services/AccessoryInformationService.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.impl.characteristics.information.Identify; -import io.github.hapjava.impl.characteristics.information.Manufacturer; -import io.github.hapjava.impl.characteristics.information.Model; -import io.github.hapjava.impl.characteristics.information.SerialNumber; - -public class AccessoryInformationService extends AbstractServiceImpl { - - public AccessoryInformationService(HomekitAccessory accessory) throws Exception { - this(accessory, accessory.getLabel()); - } - - public AccessoryInformationService(HomekitAccessory accessory, String serviceName) - throws Exception { - super("0000003E-0000-1000-8000-0026BB765291", accessory, serviceName); - addCharacteristic(new Manufacturer(accessory)); - addCharacteristic(new Model(accessory)); - addCharacteristic(new SerialNumber(accessory)); - addCharacteristic(new Identify(accessory)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/CarbonMonoxideSensorService.java b/src/main/java/io/github/hapjava/impl/services/CarbonMonoxideSensorService.java deleted file mode 100644 index 0225ab0e4..000000000 --- a/src/main/java/io/github/hapjava/impl/services/CarbonMonoxideSensorService.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.CarbonMonoxideSensor; -import io.github.hapjava.impl.characteristics.carbonmonoxide.CarbonMonoxideDetectedCharacteristic; - -public class CarbonMonoxideSensorService extends AbstractServiceImpl { - - public CarbonMonoxideSensorService(CarbonMonoxideSensor carbonMonoxideSensor) { - this(carbonMonoxideSensor, carbonMonoxideSensor.getLabel()); - } - - public CarbonMonoxideSensorService( - CarbonMonoxideSensor carbonMonoxideSensor, String serviceName) { - super("0000007F-0000-1000-8000-0026BB765291", carbonMonoxideSensor, serviceName); - addCharacteristic(new CarbonMonoxideDetectedCharacteristic(carbonMonoxideSensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/ContactSensorService.java b/src/main/java/io/github/hapjava/impl/services/ContactSensorService.java deleted file mode 100644 index b4df03fc2..000000000 --- a/src/main/java/io/github/hapjava/impl/services/ContactSensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.ContactSensor; -import io.github.hapjava.impl.characteristics.contactsensor.ContactSensorStateCharacteristic; - -public class ContactSensorService extends AbstractServiceImpl { - - public ContactSensorService(ContactSensor contactSensor) { - this(contactSensor, contactSensor.getLabel()); - } - - public ContactSensorService(ContactSensor contactSensor, String serviceName) { - super("00000080-0000-1000-8000-0026BB765291", contactSensor, serviceName); - addCharacteristic(new ContactSensorStateCharacteristic(contactSensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/FanService.java b/src/main/java/io/github/hapjava/impl/services/FanService.java deleted file mode 100644 index 86bbb701c..000000000 --- a/src/main/java/io/github/hapjava/impl/services/FanService.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.Fan; -import io.github.hapjava.impl.characteristics.common.PowerStateCharacteristic; -import io.github.hapjava.impl.characteristics.fan.RotationDirectionCharacteristic; -import io.github.hapjava.impl.characteristics.fan.RotationSpeedCharacteristic; - -public class FanService extends AbstractServiceImpl { - - public FanService(Fan fan) { - this(fan, fan.getLabel()); - } - - public FanService(Fan fan, String serviceName) { - super("00000040-0000-1000-8000-0026BB765291", fan, serviceName); - addCharacteristic( - new PowerStateCharacteristic( - () -> fan.getFanPower(), - v -> fan.setFanPower(v), - c -> fan.subscribeFanPower(c), - () -> fan.unsubscribeFanPower())); - addCharacteristic(new RotationDirectionCharacteristic(fan)); - addCharacteristic(new RotationSpeedCharacteristic(fan)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/GarageDoorService.java b/src/main/java/io/github/hapjava/impl/services/GarageDoorService.java deleted file mode 100644 index 1296a9b7d..000000000 --- a/src/main/java/io/github/hapjava/impl/services/GarageDoorService.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.GarageDoor; -import io.github.hapjava.impl.characteristics.common.ObstructionDetectedCharacteristic; -import io.github.hapjava.impl.characteristics.garage.CurrentDoorStateCharacteristic; -import io.github.hapjava.impl.characteristics.garage.TargetDoorStateCharacteristic; - -public class GarageDoorService extends AbstractServiceImpl { - - public GarageDoorService(GarageDoor door) { - this(door, door.getLabel()); - } - - public GarageDoorService(GarageDoor door, String serviceName) { - super("00000041-0000-1000-8000-0026BB765291", door, serviceName); - addCharacteristic(new CurrentDoorStateCharacteristic(door)); - addCharacteristic(new TargetDoorStateCharacteristic(door)); - addCharacteristic( - new ObstructionDetectedCharacteristic( - () -> door.getObstructionDetected(), - c -> door.subscribeObstructionDetected(c), - () -> door.unsubscribeObstructionDetected())); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/HumiditySensorService.java b/src/main/java/io/github/hapjava/impl/services/HumiditySensorService.java deleted file mode 100644 index 99b1c716f..000000000 --- a/src/main/java/io/github/hapjava/impl/services/HumiditySensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.HumiditySensor; -import io.github.hapjava.impl.characteristics.humiditysensor.CurrentRelativeHumidityCharacteristic; - -public class HumiditySensorService extends AbstractServiceImpl { - - public HumiditySensorService(HumiditySensor sensor) { - this(sensor, sensor.getLabel()); - } - - public HumiditySensorService(HumiditySensor sensor, String serviceName) { - super("00000082-0000-1000-8000-0026BB765291", sensor, serviceName); - addCharacteristic(new CurrentRelativeHumidityCharacteristic(sensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/LeakSensorService.java b/src/main/java/io/github/hapjava/impl/services/LeakSensorService.java deleted file mode 100644 index 89eab8bf6..000000000 --- a/src/main/java/io/github/hapjava/impl/services/LeakSensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.LeakSensor; -import io.github.hapjava.impl.characteristics.leaksensor.LeakDetectedStateCharacteristic; - -public class LeakSensorService extends AbstractServiceImpl { - - public LeakSensorService(LeakSensor leakSensor) { - this(leakSensor, leakSensor.getLabel()); - } - - public LeakSensorService(LeakSensor leakSensor, String serviceName) { - super("00000083-0000-1000-8000-0026BB765291", leakSensor, serviceName); - addCharacteristic(new LeakDetectedStateCharacteristic(leakSensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/LightSensorService.java b/src/main/java/io/github/hapjava/impl/services/LightSensorService.java deleted file mode 100644 index 3b41e4d9b..000000000 --- a/src/main/java/io/github/hapjava/impl/services/LightSensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.LightSensor; -import io.github.hapjava.impl.characteristics.light.AmbientLightLevelCharacteristic; - -public class LightSensorService extends AbstractServiceImpl { - - public LightSensorService(LightSensor lightSensor) { - this(lightSensor, lightSensor.getLabel()); - } - - public LightSensorService(LightSensor lightSensor, String serviceName) { - super("00000084-0000-1000-8000-0026BB765291", lightSensor, serviceName); - addCharacteristic(new AmbientLightLevelCharacteristic(lightSensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/LightbulbService.java b/src/main/java/io/github/hapjava/impl/services/LightbulbService.java deleted file mode 100644 index a3b55a141..000000000 --- a/src/main/java/io/github/hapjava/impl/services/LightbulbService.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.ColorfulLightbulb; -import io.github.hapjava.accessories.DimmableLightbulb; -import io.github.hapjava.accessories.Lightbulb; -import io.github.hapjava.impl.characteristics.common.PowerStateCharacteristic; -import io.github.hapjava.impl.characteristics.lightbulb.BrightnessCharacteristic; -import io.github.hapjava.impl.characteristics.lightbulb.HueCharacteristic; -import io.github.hapjava.impl.characteristics.lightbulb.SaturationCharacteristic; - -public class LightbulbService extends AbstractServiceImpl { - - public LightbulbService(Lightbulb lightbulb) { - this(lightbulb, lightbulb.getLabel()); - } - - public LightbulbService(Lightbulb lightbulb, String serviceName) { - super("00000043-0000-1000-8000-0026BB765291", lightbulb, serviceName); - addCharacteristic( - new PowerStateCharacteristic( - () -> lightbulb.getLightbulbPowerState(), - v -> lightbulb.setLightbulbPowerState(v), - c -> lightbulb.subscribeLightbulbPowerState(c), - () -> lightbulb.unsubscribeLightbulbPowerState())); - - if (lightbulb instanceof DimmableLightbulb) { - addCharacteristic(new BrightnessCharacteristic((DimmableLightbulb) lightbulb)); - } - - if (lightbulb instanceof ColorfulLightbulb) { - addCharacteristic(new HueCharacteristic((ColorfulLightbulb) lightbulb)); - addCharacteristic(new SaturationCharacteristic((ColorfulLightbulb) lightbulb)); - } - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/LockMechanismService.java b/src/main/java/io/github/hapjava/impl/services/LockMechanismService.java deleted file mode 100644 index a0b1346f4..000000000 --- a/src/main/java/io/github/hapjava/impl/services/LockMechanismService.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.LockMechanism; -import io.github.hapjava.accessories.LockableLockMechanism; -import io.github.hapjava.impl.characteristics.lock.mechanism.CurrentLockMechanismStateCharacteristic; -import io.github.hapjava.impl.characteristics.lock.mechanism.TargetLockMechanismStateCharacteristic; - -public class LockMechanismService extends AbstractServiceImpl { - - public LockMechanismService(LockMechanism lock) { - this(lock, lock.getLabel()); - } - - public LockMechanismService(LockMechanism lock, String serviceName) { - super("00000045-0000-1000-8000-0026BB765291", lock, serviceName); - addCharacteristic(new CurrentLockMechanismStateCharacteristic(lock)); - - if (lock instanceof LockableLockMechanism) { - addCharacteristic(new TargetLockMechanismStateCharacteristic((LockableLockMechanism) lock)); - } - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/MotionSensorService.java b/src/main/java/io/github/hapjava/impl/services/MotionSensorService.java deleted file mode 100644 index 354650973..000000000 --- a/src/main/java/io/github/hapjava/impl/services/MotionSensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.MotionSensor; -import io.github.hapjava.impl.characteristics.motionsensor.MotionDetectedStateCharacteristic; - -public class MotionSensorService extends AbstractServiceImpl { - - public MotionSensorService(MotionSensor motionSensor) { - this(motionSensor, motionSensor.getLabel()); - } - - public MotionSensorService(MotionSensor motionSensor, String serviceName) { - super("00000085-0000-1000-8000-0026BB765291", motionSensor, serviceName); - addCharacteristic(new MotionDetectedStateCharacteristic(motionSensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/OccupancySensorService.java b/src/main/java/io/github/hapjava/impl/services/OccupancySensorService.java deleted file mode 100644 index 35965a9d2..000000000 --- a/src/main/java/io/github/hapjava/impl/services/OccupancySensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.OccupancySensor; -import io.github.hapjava.impl.characteristics.occupancysensor.OccupancyDetectedStateCharacteristic; - -public class OccupancySensorService extends AbstractServiceImpl { - - public OccupancySensorService(OccupancySensor occupancySensor) { - this(occupancySensor, occupancySensor.getLabel()); - } - - public OccupancySensorService(OccupancySensor occupancySensor, String serviceName) { - super("00000086-0000-1000-8000-0026BB765291", occupancySensor, serviceName); - addCharacteristic(new OccupancyDetectedStateCharacteristic(occupancySensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/OutletService.java b/src/main/java/io/github/hapjava/impl/services/OutletService.java deleted file mode 100644 index 3d03a7331..000000000 --- a/src/main/java/io/github/hapjava/impl/services/OutletService.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.Outlet; -import io.github.hapjava.impl.characteristics.common.PowerStateCharacteristic; -import io.github.hapjava.impl.characteristics.outlet.OutletInUseCharacteristic; - -public class OutletService extends AbstractServiceImpl { - - public OutletService(Outlet outlet) { - this(outlet, outlet.getLabel()); - } - - public OutletService(Outlet outlet, String serviceName) { - super("00000047-0000-1000-8000-0026BB765291", outlet, serviceName); - addCharacteristic( - new PowerStateCharacteristic( - () -> outlet.getPowerState(), - v -> outlet.setPowerState(v), - c -> outlet.subscribePowerState(c), - () -> outlet.unsubscribePowerState())); - addCharacteristic(new OutletInUseCharacteristic(outlet)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/SecuritySystemService.java b/src/main/java/io/github/hapjava/impl/services/SecuritySystemService.java deleted file mode 100644 index 855f027e7..000000000 --- a/src/main/java/io/github/hapjava/impl/services/SecuritySystemService.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.SecuritySystem; -import io.github.hapjava.impl.characteristics.securitysystem.CurrentSecuritySystemStateCharacteristic; -import io.github.hapjava.impl.characteristics.securitysystem.SecuritySystemAlarmTypeCharacteristic; -import io.github.hapjava.impl.characteristics.securitysystem.TargetSecuritySystemStateCharacteristic; - -public class SecuritySystemService extends AbstractServiceImpl { - - public SecuritySystemService(SecuritySystem securitySystem) { - this(securitySystem, securitySystem.getLabel()); - } - - public SecuritySystemService(SecuritySystem securitySystem, String serviceName) { - super("0000007E-0000-1000-8000-0026BB765291", securitySystem, serviceName); - addCharacteristic(new CurrentSecuritySystemStateCharacteristic(securitySystem)); - addCharacteristic(new TargetSecuritySystemStateCharacteristic(securitySystem)); - addCharacteristic(new SecuritySystemAlarmTypeCharacteristic(securitySystem)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/SmokeSensorService.java b/src/main/java/io/github/hapjava/impl/services/SmokeSensorService.java deleted file mode 100644 index ad846c8b8..000000000 --- a/src/main/java/io/github/hapjava/impl/services/SmokeSensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.SmokeSensor; -import io.github.hapjava.impl.characteristics.smokesensor.SmokeDetectedCharacteristic; - -public class SmokeSensorService extends AbstractServiceImpl { - - public SmokeSensorService(SmokeSensor smokeSensor) { - this(smokeSensor, smokeSensor.getLabel()); - } - - public SmokeSensorService(SmokeSensor smokeSensor, String serviceName) { - super("00000087-0000-1000-8000-0026BB765291", smokeSensor, serviceName); - addCharacteristic(new SmokeDetectedCharacteristic(smokeSensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/SwitchService.java b/src/main/java/io/github/hapjava/impl/services/SwitchService.java deleted file mode 100644 index a297a2cec..000000000 --- a/src/main/java/io/github/hapjava/impl/services/SwitchService.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.Switch; -import io.github.hapjava.impl.characteristics.common.PowerStateCharacteristic; - -public class SwitchService extends AbstractServiceImpl { - - public SwitchService(Switch switchAccessory) { - this(switchAccessory, switchAccessory.getLabel()); - } - - public SwitchService(Switch switchAccessory, String serviceName) { - super("00000049-0000-1000-8000-0026BB765291", switchAccessory, serviceName); - addCharacteristic( - new PowerStateCharacteristic( - () -> switchAccessory.getSwitchState(), - v -> switchAccessory.setSwitchState(v), - c -> switchAccessory.subscribeSwitchState(c), - () -> switchAccessory.unsubscribeSwitchState())); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/TemperatureSensorService.java b/src/main/java/io/github/hapjava/impl/services/TemperatureSensorService.java deleted file mode 100644 index 5a59513aa..000000000 --- a/src/main/java/io/github/hapjava/impl/services/TemperatureSensorService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.TemperatureSensor; -import io.github.hapjava.impl.characteristics.thermostat.CurrentTemperatureCharacteristic; - -public class TemperatureSensorService extends AbstractServiceImpl { - - public TemperatureSensorService(TemperatureSensor sensor) { - this(sensor, sensor.getLabel()); - } - - public TemperatureSensorService(TemperatureSensor sensor, String serviceName) { - super("0000008A-0000-1000-8000-0026BB765291", sensor, serviceName); - addCharacteristic(new CurrentTemperatureCharacteristic(sensor)); - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/ThermostatService.java b/src/main/java/io/github/hapjava/impl/services/ThermostatService.java deleted file mode 100644 index e679680ae..000000000 --- a/src/main/java/io/github/hapjava/impl/services/ThermostatService.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.thermostat.BasicThermostat; -import io.github.hapjava.accessories.thermostat.CoolingThermostat; -import io.github.hapjava.accessories.thermostat.HeatingThermostat; -import io.github.hapjava.impl.characteristics.thermostat.*; - -public class ThermostatService extends AbstractServiceImpl { - - public ThermostatService(BasicThermostat thermostat) { - this(thermostat, thermostat.getLabel()); - } - - public ThermostatService(BasicThermostat thermostat, String serviceName) { - super("0000004A-0000-1000-8000-0026BB765291", thermostat, serviceName); - addCharacteristic(new CurrentHeatingCoolingModeCharacteristic(thermostat)); - addCharacteristic(new CurrentTemperatureCharacteristic(thermostat)); - addCharacteristic(new TargetHeatingCoolingModeCharacteristic(thermostat)); - addCharacteristic(new TargetTemperatureCharacteristic(thermostat)); - addCharacteristic(new TemperatureUnitsCharacteristic(thermostat)); - if (thermostat instanceof HeatingThermostat) { - addCharacteristic( - new HeatingThresholdTemperatureCharacteristic((HeatingThermostat) thermostat)); - } - if (thermostat instanceof CoolingThermostat) { - addCharacteristic( - new CoolingThresholdTemperatureCharacteristic((CoolingThermostat) thermostat)); - } - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/ValveService.java b/src/main/java/io/github/hapjava/impl/services/ValveService.java deleted file mode 100644 index c1c14ff88..000000000 --- a/src/main/java/io/github/hapjava/impl/services/ValveService.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.Valve; -import io.github.hapjava.accessories.ValveWithTimer; -import io.github.hapjava.impl.characteristics.common.ActiveCharacteristic; -import io.github.hapjava.impl.characteristics.common.InUseCharacteristic; -import io.github.hapjava.impl.characteristics.common.RemainingDurationCharacteristic; -import io.github.hapjava.impl.characteristics.valve.SetDurationCharacteristic; -import io.github.hapjava.impl.characteristics.valve.ValveTypeCharacteristic; - -public class ValveService extends AbstractServiceImpl { - - public ValveService(Valve valve) { - this(valve, valve.getLabel()); - } - - public ValveService(Valve valve, String serviceName) { - super("000000D0-0000-1000-8000-0026BB765291", valve, serviceName); - addCharacteristic( - new ActiveCharacteristic( - valve::getValveActive, - a -> valve.setValveActive(a), - valve::subscribeValveActive, - valve::unsubscribeValveActive)); - addCharacteristic(new ValveTypeCharacteristic(valve)); - addCharacteristic( - new InUseCharacteristic( - valve::getValveInUse, valve::subscribeValveInUse, valve::unsubscribeValveInUse)); - - if (valve instanceof ValveWithTimer) { - ValveWithTimer vwt = (ValveWithTimer) valve; - addCharacteristic(new SetDurationCharacteristic(vwt)); - addCharacteristic( - new RemainingDurationCharacteristic( - vwt::getRemainingDuration, - vwt::subscribeRemainingDuration, - vwt::unsubscribeRemainingDuration)); - } - } -} diff --git a/src/main/java/io/github/hapjava/impl/services/WindowCoveringService.java b/src/main/java/io/github/hapjava/impl/services/WindowCoveringService.java deleted file mode 100644 index 001863da1..000000000 --- a/src/main/java/io/github/hapjava/impl/services/WindowCoveringService.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.hapjava.impl.services; - -import io.github.hapjava.accessories.BasicWindowCovering; -import io.github.hapjava.accessories.HoldPositionWindowCovering; -import io.github.hapjava.accessories.HorizontalTiltingWindowCovering; -import io.github.hapjava.accessories.ObstructionDetectedWindowCovering; -import io.github.hapjava.accessories.VerticalTiltingWindowCovering; -import io.github.hapjava.impl.characteristics.common.ObstructionDetectedCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.CurrentHorizontalTiltAngleCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.CurrentPositionCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.CurrentVerticalTiltAngleCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.HoldPositionCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.PositionStateCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.TargetHorizontalTiltAngleCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.TargetPositionCharacteristic; -import io.github.hapjava.impl.characteristics.windowcovering.TargetVerticalTiltAngleCharacteristic; - -public class WindowCoveringService extends AbstractServiceImpl { - - public WindowCoveringService(BasicWindowCovering windowCovering) { - this(windowCovering, windowCovering.getLabel()); - } - - public WindowCoveringService(BasicWindowCovering windowCovering, String serviceName) { - super("0000008C-0000-1000-8000-0026BB765291", windowCovering, serviceName); - addCharacteristic(new CurrentPositionCharacteristic(windowCovering)); - addCharacteristic(new PositionStateCharacteristic(windowCovering)); - addCharacteristic(new TargetPositionCharacteristic(windowCovering)); - - if (windowCovering instanceof HorizontalTiltingWindowCovering) { - addCharacteristic( - new CurrentHorizontalTiltAngleCharacteristic( - (HorizontalTiltingWindowCovering) windowCovering)); - addCharacteristic( - new TargetHorizontalTiltAngleCharacteristic( - (HorizontalTiltingWindowCovering) windowCovering)); - } - if (windowCovering instanceof VerticalTiltingWindowCovering) { - addCharacteristic( - new CurrentVerticalTiltAngleCharacteristic( - (VerticalTiltingWindowCovering) windowCovering)); - addCharacteristic( - new TargetVerticalTiltAngleCharacteristic( - (VerticalTiltingWindowCovering) windowCovering)); - } - if (windowCovering instanceof HoldPositionWindowCovering) { - HoldPositionWindowCovering hpwc = (HoldPositionWindowCovering) windowCovering; - addCharacteristic(new HoldPositionCharacteristic(hpwc)); - } - if (windowCovering instanceof ObstructionDetectedWindowCovering) { - ObstructionDetectedWindowCovering wc = (ObstructionDetectedWindowCovering) windowCovering; - addCharacteristic( - new ObstructionDetectedCharacteristic( - () -> wc.getObstructionDetected(), - c -> wc.subscribeObstructionDetected(c), - () -> wc.unsubscribeObstructionDetected())); - } - } -} diff --git a/src/main/java/io/github/hapjava/package-info.java b/src/main/java/io/github/hapjava/package-info.java deleted file mode 100644 index b4b98ad13..000000000 --- a/src/main/java/io/github/hapjava/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Base package for implementing the Homekit Accessory Protocol. Start with {@link - * io.github.hapjava.HomekitServer}. - */ -package io.github.hapjava; diff --git a/src/main/java/io/github/hapjava/server/HomekitAccessoryCategories.java b/src/main/java/io/github/hapjava/server/HomekitAccessoryCategories.java new file mode 100644 index 000000000..05768a947 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/HomekitAccessoryCategories.java @@ -0,0 +1,40 @@ +package io.github.hapjava.server; + +public final class HomekitAccessoryCategories { + public static final int OTHER = 1; + public static final int BRIDGES = 2; + public static final int FANS = 3; + public static final int GARAGE_DOOR_OPENERS = 4; + public static final int LIGHTING = 5; + public static final int LOCKS = 6; + public static final int OUTLETS = 7; + public static final int SWITCHES = 8; + public static final int THERMOSTATS = 9; + public static final int SENSORS = 10; + public static final int SECURITY_SYSTEMS = 11; + public static final int DOORS = 12; + public static final int WINDOWS = 13; + public static final int WINDOW_COVERINGS = 14; + public static final int PROGRAMMABLE_SWITCHES = 15; + public static final int RANGE_EXTENDER = 16; + public static final int IP_CAMERAS = 17; + public static final int VIDEO_DOORBELLS = 18; + public static final int AIR_PURIFIERS = 19; + public static final int HEATERS = 20; + public static final int AIR_CONDITIONERS = 21; + public static final int HUMIDIFIERS = 22; + public static final int DEHUMIDIFIERS = 23; + public static final int APPLE_TV = 24; + public static final int HOMEPOD = 25; + public static final int SPEAKER = 26; + public static final int AIRPORT = 27; + public static final int SPRINKLERS = 28; + public static final int FAUCETS = 29; + public static final int SHOWER_SYSTEMS = 30; + public static final int TELEVISION = 31; + public static final int REMOTES = 32; + public static final int ROUTER = 33; + public static final int AUDIO_RECEIVER = 34; + public static final int TV_SET_TOP_BOX = 35; + public static final int TV_STREAMING_STICK = 36; +} diff --git a/src/main/java/io/github/hapjava/HomekitAuthInfo.java b/src/main/java/io/github/hapjava/server/HomekitAuthInfo.java similarity index 66% rename from src/main/java/io/github/hapjava/HomekitAuthInfo.java rename to src/main/java/io/github/hapjava/server/HomekitAuthInfo.java index 3326c8bae..6441962d7 100644 --- a/src/main/java/io/github/hapjava/HomekitAuthInfo.java +++ b/src/main/java/io/github/hapjava/server/HomekitAuthInfo.java @@ -1,6 +1,10 @@ -package io.github.hapjava; +package io.github.hapjava.server; +import io.github.hapjava.server.impl.HomekitServer; +import io.github.hapjava.server.impl.crypto.HAPSetupCodeUtils; import java.math.BigInteger; +import java.util.Collection; +import java.util.List; /** * Authentication info that must be provided when constructing a new {@link HomekitServer}. You will @@ -21,7 +25,17 @@ public interface HomekitAuthInfo { String getPin(); /** - * A unique MAC address to be advertised with the Homekit information. This does not have to be + * A setup Id used for pairing the device using QR Code. It can be any alphanumeric combination of + * the length of 4. + * + * @return setup id + */ + default String getSetupId() { + return HAPSetupCodeUtils.generateSetupId(); + } + + /** + * A unique MAC address to be advertised with the HomeKit information. This does not have to be * the MAC address of the network interface. You can generate this using {@link * HomekitServer#generateMac()}. * @@ -53,8 +67,23 @@ public interface HomekitAuthInfo { * @param username the iOS device's username. The value will not be meaningful to anything but * iOS. * @param publicKey the iOS device's public key. + * @param isAdmin if the user is an admin, authorized to and/remove other users + */ + default void createUser(String username, byte[] publicKey, boolean isAdmin) { + createUser(username, publicKey); + } + + /** + * Deprecated method to add a user, assuming all users are admins. + * + *

At least one of the createUser methods must be implemented. + * + * @param username the iOS device's username. + * @param publicKey the iOS device's public key. */ - void createUser(String username, byte[] publicKey); + default void createUser(String username, byte[] publicKey) { + createUser(username, publicKey, true); + } /** * Called when an iOS device needs to remove an existing pairing. Subsequent calls to {@link @@ -64,6 +93,15 @@ public interface HomekitAuthInfo { */ void removeUser(String username); + /** + * List all users which have been authenticated. + * + * @return the previously stored list of users. + */ + default Collection listUsers() { + return List.of(); + } + /** * Called when an already paired iOS device is re-connecting. The public key returned by this * method will be compared with the signature of the pair verification request to validate the @@ -74,6 +112,16 @@ public interface HomekitAuthInfo { */ byte[] getUserPublicKey(String username); + /** + * Determine if the specified user is an admin. + * + * @param username the username of the iOS device to retrieve permissions for. + * @return the previously stored permissions. + */ + default boolean userIsAdmin(String username) { + return true; + } + /** * Called to check if a user has been created. The homekit accessory advertises whether the * accessory has already been paired. At this time, it's unclear whether multiple users can be diff --git a/src/main/java/io/github/hapjava/impl/HomekitWebHandler.java b/src/main/java/io/github/hapjava/server/HomekitWebHandler.java similarity index 67% rename from src/main/java/io/github/hapjava/impl/HomekitWebHandler.java rename to src/main/java/io/github/hapjava/server/HomekitWebHandler.java index 5c7693a29..d66a843c4 100644 --- a/src/main/java/io/github/hapjava/impl/HomekitWebHandler.java +++ b/src/main/java/io/github/hapjava/server/HomekitWebHandler.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl; +package io.github.hapjava.server; -import io.github.hapjava.impl.http.HomekitClientConnectionFactory; +import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory; import java.util.concurrent.CompletableFuture; public interface HomekitWebHandler { diff --git a/src/main/java/io/github/hapjava/server/impl/HomekitBridge.java b/src/main/java/io/github/hapjava/server/impl/HomekitBridge.java new file mode 100644 index 000000000..11efb0d37 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/HomekitBridge.java @@ -0,0 +1,67 @@ +package io.github.hapjava.server.impl; + +import io.github.hapjava.accessories.Bridge; +import io.github.hapjava.services.Service; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +public class HomekitBridge implements Bridge { + + private final String label; + private final String serialNumber; + private final String model; + private final String manufacturer; + private final String firmwareRevision; + private final String hardwareRevision; + + public HomekitBridge( + String label, + String serialNumber, + String model, + String manufacturer, + String firmwareRevision, + String hardwareRevision) { + this.label = label; + this.serialNumber = serialNumber; + this.model = model; + this.manufacturer = manufacturer; + this.firmwareRevision = firmwareRevision; + this.hardwareRevision = hardwareRevision; + } + + @Override + public CompletableFuture getName() { + return CompletableFuture.completedFuture(label); + } + + @Override + public CompletableFuture getSerialNumber() { + return CompletableFuture.completedFuture(serialNumber); + } + + @Override + public CompletableFuture getModel() { + return CompletableFuture.completedFuture(model); + } + + @Override + public CompletableFuture getManufacturer() { + return CompletableFuture.completedFuture(manufacturer); + } + + @Override + public CompletableFuture getFirmwareRevision() { + return CompletableFuture.completedFuture(firmwareRevision); + } + + @Override + public Collection getServices() { + return Collections.emptyList(); + } + + @Override + public int getId() { + return 1; + } +} diff --git a/src/main/java/io/github/hapjava/server/impl/HomekitRegistry.java b/src/main/java/io/github/hapjava/server/impl/HomekitRegistry.java new file mode 100644 index 000000000..3c70cfb9e --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/HomekitRegistry.java @@ -0,0 +1,109 @@ +package io.github.hapjava.server.impl; + +import io.github.hapjava.accessories.HomekitAccessory; +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.server.impl.connections.SubscriptionManager; +import io.github.hapjava.services.Service; +import io.github.hapjava.services.impl.AccessoryInformationService; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HomekitRegistry { + + private static final Logger logger = LoggerFactory.getLogger(HomekitRegistry.class); + + private final String label; + private final SubscriptionManager subscriptions; + private final Map accessories; + private final Map> services = new HashMap<>(); + private final Map> characteristics = + new HashMap<>(); + private boolean isAllowUnauthenticatedRequests = false; + + public HomekitRegistry(String label, SubscriptionManager subscriptions) { + this.label = label; + this.subscriptions = subscriptions; + this.accessories = new ConcurrentHashMap<>(); + reset(); + } + + public synchronized void reset() { + characteristics.clear(); + services.clear(); + for (HomekitAccessory accessory : accessories.values()) { + int iid = 0; + List newServices; + try { + newServices = new ArrayList<>(2); + Collection services = accessory.getServices(); + if (!services.stream() + .anyMatch(s -> s.getType().equals(AccessoryInformationService.TYPE))) { + newServices.add(new AccessoryInformationService(accessory)); + } + for (Service service : services) { + newServices.add(service); + newServices.addAll(service.getLinkedServices()); + } + } catch (Exception e) { + logger.warn("Could not instantiate services for accessory " + accessory.getName(), e); + services.put(accessory, Collections.emptyMap()); + continue; + } + + Map newCharacteristicsByInterfaceId = new HashMap<>(); + Map newServicesByInterfaceId = new HashMap<>(); + for (Service service : newServices) { + newServicesByInterfaceId.put(++iid, service); + for (Characteristic characteristic : service.getCharacteristics()) { + newCharacteristicsByInterfaceId.put(++iid, characteristic); + } + } + services.put(accessory, newServicesByInterfaceId); + characteristics.put(accessory, newCharacteristicsByInterfaceId); + } + subscriptions.resync(this); + } + + public String getLabel() { + return label; + } + + public Collection getAccessories() { + return accessories.values(); + } + + public Map getServices(Integer aid) { + return Collections.unmodifiableMap(services.get(accessories.get(aid))); + } + + public Map getCharacteristics(Integer aid) { + Map characteristics = this.characteristics.get(accessories.get(aid)); + if (characteristics == null) { + return Collections.emptyMap(); + } + return Collections.unmodifiableMap(characteristics); + } + + public void add(HomekitAccessory accessory) { + accessories.put(accessory.getId(), accessory); + } + + public boolean remove(HomekitAccessory accessory) { + return accessories.remove(accessory.getId()) != null; + } + + public boolean isAllowUnauthenticatedRequests() { + return isAllowUnauthenticatedRequests; + } + + public void setAllowUnauthenticatedRequests(boolean allow) { + this.isAllowUnauthenticatedRequests = allow; + } +} diff --git a/src/main/java/io/github/hapjava/HomekitRoot.java b/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java similarity index 54% rename from src/main/java/io/github/hapjava/HomekitRoot.java rename to src/main/java/io/github/hapjava/server/impl/HomekitRoot.java index 29ed0113c..36bfeefa2 100644 --- a/src/main/java/io/github/hapjava/HomekitRoot.java +++ b/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java @@ -1,46 +1,63 @@ -package io.github.hapjava; - -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.HomekitWebHandler; -import io.github.hapjava.impl.accessories.Bridge; -import io.github.hapjava.impl.connections.HomekitClientConnectionFactoryImpl; -import io.github.hapjava.impl.connections.SubscriptionManager; -import io.github.hapjava.impl.jmdns.JmdnsHomekitAdvertiser; +package io.github.hapjava.server.impl; + +import io.github.hapjava.accessories.Bridge; +import io.github.hapjava.accessories.HomekitAccessory; +import io.github.hapjava.server.HomekitAccessoryCategories; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.HomekitWebHandler; +import io.github.hapjava.server.impl.connections.HomekitClientConnectionFactoryImpl; +import io.github.hapjava.server.impl.connections.SubscriptionManager; +import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser; import java.io.IOException; import java.net.InetAddress; +import javax.jmdns.JmDNS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Provides advertising and handling for Homekit accessories. This class handles the advertising of - * Homekit accessories and contains one or more accessories. When implementing a bridge accessory, + * Provides advertising and handling for HomeKit accessories. This class handles the advertising of + * HomeKit accessories and contains one or more accessories. When implementing a bridge accessory, * you will interact with this class directly. Instantiate it via {@link - * HomekitServer#createBridge(HomekitAuthInfo, String, String, String, String)}. For single - * accessories, this is composed by {@link HomekitStandaloneAccessoryServer}. + * HomekitServer#createBridge(HomekitAuthInfo, String, String, String, String, String, String)}. For + * single accessories, this is composed by {@link HomekitStandaloneAccessoryServer}. * * @author Andy Lintner */ public class HomekitRoot { private static final Logger logger = LoggerFactory.getLogger(HomekitRoot.class); - + private static final int DEFAULT_ACCESSORY_CATEGORY = HomekitAccessoryCategories.OTHER; private final JmdnsHomekitAdvertiser advertiser; private final HomekitWebHandler webHandler; private final HomekitAuthInfo authInfo; private final String label; + private final int category; private final HomekitRegistry registry; private final SubscriptionManager subscriptions = new SubscriptionManager(); private boolean started = false; private int configurationIndex = 1; + private int nestedBatches = 0; + private boolean madeChanges = false; HomekitRoot( - String label, HomekitWebHandler webHandler, InetAddress localhost, HomekitAuthInfo authInfo) + String label, HomekitWebHandler webHandler, InetAddress host, HomekitAuthInfo authInfo) throws IOException { - this(label, webHandler, authInfo, new JmdnsHomekitAdvertiser(localhost)); + this(label, DEFAULT_ACCESSORY_CATEGORY, webHandler, authInfo, new JmdnsHomekitAdvertiser(host)); } HomekitRoot( String label, + int category, + HomekitWebHandler webHandler, + InetAddress host, + HomekitAuthInfo authInfo) + throws IOException { + this(label, category, webHandler, authInfo, new JmdnsHomekitAdvertiser(host)); + } + + HomekitRoot( + String label, + int category, HomekitWebHandler webHandler, HomekitAuthInfo authInfo, JmdnsHomekitAdvertiser advertiser) @@ -49,14 +66,46 @@ public class HomekitRoot { this.webHandler = webHandler; this.authInfo = authInfo; this.label = label; - this.registry = new HomekitRegistry(label); + this.category = category; + this.registry = new HomekitRegistry(label, subscriptions); + } + + HomekitRoot( + String label, + int category, + HomekitWebHandler webHandler, + JmDNS jmdns, + HomekitAuthInfo authInfo) + throws IOException { + this(label, category, webHandler, authInfo, new JmdnsHomekitAdvertiser(jmdns)); + } + + HomekitRoot(String label, HomekitWebHandler webHandler, JmDNS jmdns, HomekitAuthInfo authInfo) + throws IOException { + this( + label, DEFAULT_ACCESSORY_CATEGORY, webHandler, authInfo, new JmdnsHomekitAdvertiser(jmdns)); } /** - * Add an accessory to be handled and advertised by this root. Any existing Homekit connections - * will be terminated to allow the clients to reconnect and see the updated accessory list. When - * using this for a bridge, the ID of the accessory must be greater than 1, as that ID is reserved - * for the Bridge itself. + * Begin a batch update of accessories. + * + *

After calling this, you can call addAccessory() and removeAccessory() multiple times without + * causing HAP-Java to re-publishing the metadata to HomeKit. You'll need to call + * completeUpdateBatch in order to publish all accumulated changes. + */ + public synchronized void batchUpdate() { + if (this.nestedBatches == 0) madeChanges = false; + ++this.nestedBatches; + } + + /** Publish accumulated accessory changes since batchUpdate() was called. */ + public synchronized void completeUpdateBatch() { + if (--this.nestedBatches == 0 && madeChanges) registry.reset(); + } + + /** + * Add an accessory to be handled and advertised by this root. When using this for a bridge, the + * ID of the accessory must be greater than 1, as that ID is reserved for the Bridge itself. * * @param accessory to advertise and handle. */ @@ -76,37 +125,43 @@ public void addAccessory(HomekitAccessory accessory) { */ void addAccessorySkipRangeCheck(HomekitAccessory accessory) { this.registry.add(accessory); - logger.info("Added accessory " + accessory.getLabel()); - if (started) { + if (logger.isTraceEnabled()) { + accessory.getName().thenAccept(name -> logger.trace("Added accessory {}", name)); + } + madeChanges = true; + if (started && nestedBatches == 0) { registry.reset(); - webHandler.resetConnections(); } } /** - * Removes an accessory from being handled or advertised by this root. Any existing Homekit - * connections will be terminated to allow the clients to reconnect and see the updated accessory - * list. + * Removes an accessory from being handled or advertised by this root. * * @param accessory accessory to cease advertising and handling */ public void removeAccessory(HomekitAccessory accessory) { - this.registry.remove(accessory); - logger.info("Removed accessory " + accessory.getLabel()); - if (started) { - registry.reset(); - webHandler.resetConnections(); + if (this.registry.remove(accessory)) { + if (logger.isTraceEnabled()) { + accessory.getName().thenAccept(name -> logger.trace("Removed accessory {}", name)); + } + madeChanges = true; + if (started && nestedBatches == 0) { + registry.reset(); + } + } else { + accessory.getName().thenAccept(name -> logger.warn("Could not remove accessory {}", name)); } } /** - * Starts advertising and handling the previously added Homekit accessories. You should try to + * Starts advertising and handling the previously added HomeKit accessories. You should try to * call this after you have used the {@link #addAccessory(HomekitAccessory)} method to add all the - * initial accessories you plan on advertising, as any later additions will cause the Homekit + * initial accessories you plan on advertising, as any later additions will cause the HomeKit * clients to reconnect. */ public void start() { started = true; + madeChanges = false; registry.reset(); webHandler .start( @@ -115,14 +170,20 @@ public void start() { port -> { try { refreshAuthInfo(); - advertiser.advertise(label, authInfo.getMac(), port, configurationIndex); + advertiser.advertise( + label, + category, + authInfo.getMac(), + port, + configurationIndex, + authInfo.getSetupId()); } catch (Exception e) { throw new RuntimeException(e); } }); } - /** Stops advertising and handling the Homekit accessories. */ + /** Stops advertising and handling the HomeKit accessories. */ public void stop() { advertiser.stop(); webHandler.stop(); @@ -136,6 +197,7 @@ public void stop() { * @throws IOException if there is an error in the underlying protocol, such as a TCP error */ public void refreshAuthInfo() throws IOException { + advertiser.setMac(authInfo.getMac()); advertiser.setDiscoverable(!authInfo.hasUser()); } diff --git a/src/main/java/io/github/hapjava/HomekitServer.java b/src/main/java/io/github/hapjava/server/impl/HomekitServer.java similarity index 68% rename from src/main/java/io/github/hapjava/HomekitServer.java rename to src/main/java/io/github/hapjava/server/impl/HomekitServer.java index 96b64fbdc..7728896a2 100644 --- a/src/main/java/io/github/hapjava/HomekitServer.java +++ b/src/main/java/io/github/hapjava/server/impl/HomekitServer.java @@ -1,24 +1,26 @@ -package io.github.hapjava; +package io.github.hapjava.server.impl; -import io.github.hapjava.impl.HomekitBridge; -import io.github.hapjava.impl.HomekitUtils; -import io.github.hapjava.impl.http.impl.HomekitHttpServer; +import io.github.hapjava.accessories.HomekitAccessory; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.http.impl.HomekitHttpServer; import java.io.IOException; import java.math.BigInteger; import java.net.InetAddress; import java.security.InvalidAlgorithmParameterException; +import java.util.concurrent.ExecutionException; +import javax.jmdns.JmDNS; /** - * The main entry point for hap-java. Creating an instance of this class will listen for Homekit + * The main entry point for hap-java. Creating an instance of this class will listen for HomeKit * connections on the supplied port. Only a single root accessory can be added for each unique * instance and port, however, that accessory may be a {@link #createBridge(HomekitAuthInfo, String, - * String, String, String) bridge accessory} containing child accessories. + * String, String, String, String, String) bridge accessory} containing child accessories. * *

The {@link HomekitAuthInfo HomekitAuthInfo} argument when creating accessories should be an * implementation supplied by your application. Several of the values needed for your implementation * are provided by this class, specifically {@link #generateKey() generateKey}, {@link * #generateMac() generateMac}, and {@link #generateSalt()}. It is important that you provide these - * same values on each start of your application or Homekit will fail to recognize your device as + * same values on each start of your application or HomeKit will fail to recognize your device as * being the same. * * @author Andy Lintner @@ -27,6 +29,7 @@ public class HomekitServer { private final HomekitHttpServer http; private final InetAddress localAddress; + private final JmDNS jmdns; /** * Constructor. Contains an argument indicating the number of threads to use in the http server. @@ -40,9 +43,24 @@ public class HomekitServer { */ public HomekitServer(InetAddress localAddress, int port, int nThreads) throws IOException { this.localAddress = localAddress; + this.jmdns = null; http = new HomekitHttpServer(localAddress, port, nThreads); } + /** + * Constructor + * + * @param jmdns mdns service to register with + * @param port local port to bind to + * @param nThreads number of threads to use in the http server + * @throws IOException when the server cannot bind to the supplied port + */ + public HomekitServer(JmDNS jmdns, int port, int nThreads) throws IOException { + this.jmdns = jmdns; + this.localAddress = null; + http = new HomekitHttpServer(jmdns.getInetAddress(), port, nThreads); + } + /** * Constructor * @@ -54,6 +72,16 @@ public HomekitServer(InetAddress localAddress, int port) throws IOException { this(localAddress, port, Runtime.getRuntime().availableProcessors()); } + /** + * Constructor + * + * @param jmdns mdns service to register with + * @param port local port to bind to + * @throws IOException when the server cannot bind to the supplied port + */ + public HomekitServer(JmDNS jmdns, int port) throws IOException { + this(jmdns, port, Runtime.getRuntime().availableProcessors()); + } /** * Constructor * @@ -81,8 +109,24 @@ public void stop() { * @throws IOException when mDNS cannot connect to the network */ public HomekitStandaloneAccessoryServer createStandaloneAccessory( - HomekitAuthInfo authInfo, HomekitAccessory accessory) throws IOException { - return new HomekitStandaloneAccessoryServer(accessory, http, localAddress, authInfo); + HomekitAuthInfo authInfo, HomekitAccessory accessory) + throws IOException, ExecutionException, InterruptedException { + if (jmdns != null) { + return new HomekitStandaloneAccessoryServer(accessory, http, jmdns, authInfo); + } else { + return new HomekitStandaloneAccessoryServer(accessory, http, localAddress, authInfo); + } + } + + public HomekitStandaloneAccessoryServer createStandaloneAccessory( + HomekitAuthInfo authInfo, HomekitAccessory accessory, int category) + throws IOException, ExecutionException, InterruptedException { + if (jmdns != null) { + return new HomekitStandaloneAccessoryServer(accessory, http, jmdns, authInfo, category); + } else { + return new HomekitStandaloneAccessoryServer( + accessory, http, localAddress, authInfo, category); + } } /** @@ -97,6 +141,8 @@ public HomekitStandaloneAccessoryServer createStandaloneAccessory( * purposes. * @param model model of the bridge. This is also exposed to iOS for unknown purposes. * @param serialNumber serial number of the bridge. Also exposed. Purposes also unknown. + * @param firmwareRevision firmware revision of the bridge. + * @param hardwareRevision hardware revision of the brigde. * @return the bridge, from which you can {@link HomekitRoot#addAccessory add accessories} and * then {@link HomekitRoot#start start} handling requests. * @throws IOException when mDNS cannot connect to the network @@ -104,12 +150,22 @@ public HomekitStandaloneAccessoryServer createStandaloneAccessory( public HomekitRoot createBridge( HomekitAuthInfo authInfo, String label, + int category, String manufacturer, String model, - String serialNumber) + String serialNumber, + String firmwareRevision, + String hardwareRevision) throws IOException { - HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo); - root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer)); + HomekitRoot root; + if (jmdns != null) { + root = new HomekitRoot(label, category, http, jmdns, authInfo); + } else { + root = new HomekitRoot(label, category, http, localAddress, authInfo); + } + root.addAccessory( + new HomekitBridge( + label, serialNumber, model, manufacturer, firmwareRevision, hardwareRevision)); return root; } @@ -152,7 +208,7 @@ public static String generateMac() { /** * Generates a value to supply in {@link HomekitAuthInfo#getPin() HomekitAuthInfo.getPin()}. This - * is used as the Pin a user enters into their Homekit device in order to confirm pairing. + * is used as the Pin a user enters into their HomeKit device in order to confirm pairing. * * @return the generated Pin */ diff --git a/src/main/java/io/github/hapjava/server/impl/HomekitStandaloneAccessoryServer.java b/src/main/java/io/github/hapjava/server/impl/HomekitStandaloneAccessoryServer.java new file mode 100644 index 000000000..4a5dbabee --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/HomekitStandaloneAccessoryServer.java @@ -0,0 +1,70 @@ +package io.github.hapjava.server.impl; + +import io.github.hapjava.accessories.HomekitAccessory; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.HomekitWebHandler; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.concurrent.ExecutionException; +import javax.jmdns.JmDNS; + +/** + * A server for exposing standalone HomeKit accessory (as opposed to a Bridge accessory which + * contains multiple accessories). Each standalone accessory will have its own pairing information, + * port, and pin. Instantiate this class via {@link + * HomekitServer#createStandaloneAccessory(HomekitAuthInfo, HomekitAccessory)}. + * + * @author Andy Lintner + */ +public class HomekitStandaloneAccessoryServer { + + private final HomekitRoot root; + + HomekitStandaloneAccessoryServer( + HomekitAccessory accessory, + HomekitWebHandler webHandler, + InetAddress localhost, + HomekitAuthInfo authInfo) + throws UnknownHostException, IOException, ExecutionException, InterruptedException { + root = new HomekitRoot(accessory.getName().get(), webHandler, localhost, authInfo); + root.addAccessory(accessory); + } + + HomekitStandaloneAccessoryServer( + HomekitAccessory accessory, + HomekitWebHandler webHandler, + JmDNS jmdns, + HomekitAuthInfo authInfo) + throws UnknownHostException, IOException, ExecutionException, InterruptedException { + root = new HomekitRoot(accessory.getName().get(), webHandler, jmdns, authInfo); + root.addAccessory(accessory); + } + + HomekitStandaloneAccessoryServer( + HomekitAccessory accessory, + HomekitWebHandler webHandler, + InetAddress localhost, + HomekitAuthInfo authInfo, + int category) + throws UnknownHostException, IOException, ExecutionException, InterruptedException { + root = new HomekitRoot(accessory.getName().get(), category, webHandler, localhost, authInfo); + root.addAccessory(accessory); + } + + HomekitStandaloneAccessoryServer( + HomekitAccessory accessory, + HomekitWebHandler webHandler, + JmDNS jmdns, + HomekitAuthInfo authInfo, + int category) + throws UnknownHostException, IOException, ExecutionException, InterruptedException { + root = new HomekitRoot(accessory.getName().get(), category, webHandler, jmdns, authInfo); + root.addAccessory(accessory); + } + + /** Begins advertising and handling requests for this accessory. */ + public void start() { + root.start(); + } +} diff --git a/src/main/java/io/github/hapjava/impl/HomekitUtils.java b/src/main/java/io/github/hapjava/server/impl/HomekitUtils.java similarity index 98% rename from src/main/java/io/github/hapjava/impl/HomekitUtils.java rename to src/main/java/io/github/hapjava/server/impl/HomekitUtils.java index 614515993..9b5b2b8ee 100644 --- a/src/main/java/io/github/hapjava/impl/HomekitUtils.java +++ b/src/main/java/io/github/hapjava/server/impl/HomekitUtils.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl; +package io.github.hapjava.server.impl; import com.nimbusds.srp6.SRP6Routines; import java.math.BigInteger; diff --git a/src/main/java/io/github/hapjava/impl/connections/ConnectionImpl.java b/src/main/java/io/github/hapjava/server/impl/connections/ConnectionImpl.java similarity index 84% rename from src/main/java/io/github/hapjava/impl/connections/ConnectionImpl.java rename to src/main/java/io/github/hapjava/server/impl/connections/ConnectionImpl.java index 8751a9652..759506722 100644 --- a/src/main/java/io/github/hapjava/impl/connections/ConnectionImpl.java +++ b/src/main/java/io/github/hapjava/server/impl/connections/ConnectionImpl.java @@ -1,12 +1,14 @@ -package io.github.hapjava.impl.connections; +package io.github.hapjava.server.impl.connections; -import io.github.hapjava.HomekitAuthInfo; -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.crypto.ChachaDecoder; -import io.github.hapjava.impl.crypto.ChachaEncoder; -import io.github.hapjava.impl.http.*; -import io.github.hapjava.impl.jmdns.JmdnsHomekitAdvertiser; -import io.github.hapjava.impl.pairing.UpgradeResponse; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.crypto.ChachaDecoder; +import io.github.hapjava.server.impl.crypto.ChachaEncoder; +import io.github.hapjava.server.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser; +import io.github.hapjava.server.impl.pairing.UpgradeResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; @@ -25,6 +27,7 @@ class ConnectionImpl implements HomekitClientConnection { private int outboundBinaryMessageCount = 0; private byte[] readKey; private byte[] writeKey; + private String username; private boolean isUpgraded = false; private final Consumer outOfBandMessageCallback; private final SubscriptionManager subscriptions; @@ -56,8 +59,9 @@ private HttpResponse doHandleRequest(HttpRequest request) throws IOException { isUpgraded = true; readKey = ((UpgradeResponse) response).getReadKey().array(); writeKey = ((UpgradeResponse) response).getWriteKey().array(); + username = ((UpgradeResponse) response).getUsername(); } - LOGGER.info(response.getStatusCode() + " " + request.getUri()); + LOGGER.trace("{} {} {}", response.getStatusCode(), request.getMethod(), request.getUri()); return response; } @@ -143,4 +147,9 @@ public void close() { public void outOfBand(HttpResponse message) { outOfBandMessageCallback.accept(message); } + + @Override + public String getUsername() { + return username; + } } diff --git a/src/main/java/io/github/hapjava/impl/connections/HomekitClientConnectionFactoryImpl.java b/src/main/java/io/github/hapjava/server/impl/connections/HomekitClientConnectionFactoryImpl.java similarity index 67% rename from src/main/java/io/github/hapjava/impl/connections/HomekitClientConnectionFactoryImpl.java rename to src/main/java/io/github/hapjava/server/impl/connections/HomekitClientConnectionFactoryImpl.java index b4b304b1a..9c8ad9fc0 100644 --- a/src/main/java/io/github/hapjava/impl/connections/HomekitClientConnectionFactoryImpl.java +++ b/src/main/java/io/github/hapjava/server/impl/connections/HomekitClientConnectionFactoryImpl.java @@ -1,11 +1,11 @@ -package io.github.hapjava.impl.connections; +package io.github.hapjava.server.impl.connections; -import io.github.hapjava.HomekitAuthInfo; -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.http.HomekitClientConnection; -import io.github.hapjava.impl.http.HomekitClientConnectionFactory; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.jmdns.JmdnsHomekitAdvertiser; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser; import java.util.function.Consumer; public class HomekitClientConnectionFactoryImpl implements HomekitClientConnectionFactory { diff --git a/src/main/java/io/github/hapjava/impl/connections/HttpSession.java b/src/main/java/io/github/hapjava/server/impl/connections/HttpSession.java similarity index 67% rename from src/main/java/io/github/hapjava/impl/connections/HttpSession.java rename to src/main/java/io/github/hapjava/server/impl/connections/HttpSession.java index 4a7efe7d9..f1c97c62c 100644 --- a/src/main/java/io/github/hapjava/impl/connections/HttpSession.java +++ b/src/main/java/io/github/hapjava/server/impl/connections/HttpSession.java @@ -1,19 +1,19 @@ -package io.github.hapjava.impl.connections; - -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.HomekitAuthInfo; -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.http.HomekitClientConnection; -import io.github.hapjava.impl.http.HttpRequest; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.jmdns.JmdnsHomekitAdvertiser; -import io.github.hapjava.impl.json.AccessoryController; -import io.github.hapjava.impl.json.CharacteristicsController; -import io.github.hapjava.impl.pairing.PairVerificationManager; -import io.github.hapjava.impl.pairing.PairingManager; -import io.github.hapjava.impl.pairing.PairingUpdateController; -import io.github.hapjava.impl.responses.InternalServerErrorResponse; -import io.github.hapjava.impl.responses.NotFoundResponse; +package io.github.hapjava.server.impl.connections; + +import io.github.hapjava.accessories.HomekitAccessory; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser; +import io.github.hapjava.server.impl.json.AccessoryController; +import io.github.hapjava.server.impl.json.CharacteristicsController; +import io.github.hapjava.server.impl.pairing.PairSetupManager; +import io.github.hapjava.server.impl.pairing.PairVerifyManager; +import io.github.hapjava.server.impl.pairing.PairingsManager; +import io.github.hapjava.server.impl.responses.InternalServerErrorResponse; +import io.github.hapjava.server.impl.responses.NotFoundResponse; import java.io.IOException; import java.net.InetAddress; import org.slf4j.Logger; @@ -21,8 +21,8 @@ class HttpSession { - private volatile PairingManager pairingManager; - private volatile PairVerificationManager pairVerificationManager; + private volatile PairSetupManager pairSetupManager; + private volatile PairVerifyManager pairVerifyManager; private volatile AccessoryController accessoryController; private volatile CharacteristicsController characteristicsController; @@ -59,7 +59,7 @@ public HttpResponse handleRequest(HttpRequest request) throws IOException { if (registry.isAllowUnauthenticatedRequests()) { return handleAuthenticatedRequest(request); } else { - logger.info("Unrecognized request for " + request.getUri()); + logger.warn("Unrecognized request for " + request.getUri()); return new NotFoundResponse(); } } @@ -67,7 +67,7 @@ public HttpResponse handleRequest(HttpRequest request) throws IOException { public HttpResponse handleAuthenticatedRequest(HttpRequest request) throws IOException { advertiser.setDiscoverable( - false); // brigde is already bound and should not be discoverable anymore + false); // bridge is already bound and should not be discoverable anymore try { switch (request.getUri()) { case "/accessories": @@ -79,54 +79,54 @@ public HttpResponse handleAuthenticatedRequest(HttpRequest request) throws IOExc return getCharacteristicsController().put(request, connection); default: - logger.info("Unrecognized method for " + request.getUri()); + logger.warn("Unrecognized method for " + request.getUri()); return new NotFoundResponse(); } case "/pairings": - return new PairingUpdateController(authInfo, advertiser).handle(request); + return new PairingsManager(authInfo, advertiser).handle(request); default: if (request.getUri().startsWith("/characteristics?")) { return getCharacteristicsController().get(request); } - logger.info("Unrecognized request for " + request.getUri()); + logger.warn("Unrecognized request for " + request.getUri()); return new NotFoundResponse(); } } catch (Exception e) { - logger.error("Could not handle request", e); + logger.warn("Could not handle request", e); return new InternalServerErrorResponse(e); } } private HttpResponse handlePairSetup(HttpRequest request) { - if (pairingManager == null) { + if (pairSetupManager == null) { synchronized (HttpSession.class) { - if (pairingManager == null) { - pairingManager = new PairingManager(authInfo, registry); + if (pairSetupManager == null) { + pairSetupManager = new PairSetupManager(authInfo, registry); } } } try { - return pairingManager.handle(request); + return pairSetupManager.handle(request); } catch (Exception e) { - logger.error("Exception encountered during pairing", e); + logger.warn("Exception encountered during pairing", e); return new InternalServerErrorResponse(e); } } private HttpResponse handlePairVerify(HttpRequest request) { - if (pairVerificationManager == null) { + if (pairVerifyManager == null) { synchronized (HttpSession.class) { - if (pairVerificationManager == null) { - pairVerificationManager = new PairVerificationManager(authInfo, registry); + if (pairVerifyManager == null) { + pairVerifyManager = new PairVerifyManager(authInfo, registry); } } } try { - return pairVerificationManager.handle(request); + return pairVerifyManager.handle(request); } catch (Exception e) { - logger.error("Excepton encountered while verifying pairing", e); + logger.warn("Exception encountered while verifying pairing", e); return new InternalServerErrorResponse(e); } } diff --git a/src/main/java/io/github/hapjava/impl/connections/LengthPrefixedByteArrayProcessor.java b/src/main/java/io/github/hapjava/server/impl/connections/LengthPrefixedByteArrayProcessor.java similarity index 92% rename from src/main/java/io/github/hapjava/impl/connections/LengthPrefixedByteArrayProcessor.java rename to src/main/java/io/github/hapjava/server/impl/connections/LengthPrefixedByteArrayProcessor.java index d84194685..34ec3a41c 100644 --- a/src/main/java/io/github/hapjava/impl/connections/LengthPrefixedByteArrayProcessor.java +++ b/src/main/java/io/github/hapjava/server/impl/connections/LengthPrefixedByteArrayProcessor.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.connections; +package io.github.hapjava.server.impl.connections; import java.io.ByteArrayOutputStream; import java.util.Collection; @@ -21,9 +21,9 @@ public synchronized Collection handle(byte[] data) { int pos = 0; LOGGER.trace( "Received message of length {}. Existing buffer is {}", data.length, buffer.size()); - if (buffer.size() == 0) { + if (buffer.size() == 0 && firstLengthByteBuffer == null) { while (data.length - pos > 18) { - int targetLength = (data[0] & 0xFF) + (data[1] & 0xFF) * 256 + 16 + 2; + int targetLength = (data[pos] & 0xFF) + (data[pos + 1] & 0xFF) * 256 + 16 + 2; LOGGER.trace("Attempting to read message of length {}", targetLength); if (data.length >= pos + targetLength) { byte[] b = new byte[targetLength - 2]; @@ -56,6 +56,7 @@ private void step(byte[] data, int pos, Collection results) { if (targetLength == 0) { if (firstLengthByteBuffer != null) { targetLength = (firstLengthByteBuffer & 0xFF) + (data[pos] & 0xFF) * 256 + 16; + firstLengthByteBuffer = null; pos += 1; LOGGER.trace( "Received the second byte after storing the first byte. New length is {}", diff --git a/src/main/java/io/github/hapjava/impl/connections/PendingNotification.java b/src/main/java/io/github/hapjava/server/impl/connections/PendingNotification.java similarity index 87% rename from src/main/java/io/github/hapjava/impl/connections/PendingNotification.java rename to src/main/java/io/github/hapjava/server/impl/connections/PendingNotification.java index 8cd65a4b9..ea9c69305 100644 --- a/src/main/java/io/github/hapjava/impl/connections/PendingNotification.java +++ b/src/main/java/io/github/hapjava/server/impl/connections/PendingNotification.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.connections; +package io.github.hapjava.server.impl.connections; import io.github.hapjava.characteristics.EventableCharacteristic; diff --git a/src/main/java/io/github/hapjava/server/impl/connections/SubscriptionManager.java b/src/main/java/io/github/hapjava/server/impl/connections/SubscriptionManager.java new file mode 100644 index 000000000..9399295fb --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/connections/SubscriptionManager.java @@ -0,0 +1,257 @@ +package io.github.hapjava.server.impl.connections; + +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.json.EventController; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SubscriptionManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(SubscriptionManager.class); + + private static class ConnectionsWithIds { + Set connections; + int aid, iid; + + ConnectionsWithIds(int aid, int iid) { + this.aid = aid; + this.iid = iid; + this.connections = new HashSet<>(); + } + } + + private final Map subscriptions = new HashMap<>(); + private final Map> reverse = + new HashMap<>(); + private final Map> pendingNotifications = + new HashMap<>(); + private int nestedBatches = 0; + + public synchronized void addSubscription( + int aid, + int iid, + EventableCharacteristic characteristic, + HomekitClientConnection connection) { + synchronized (this) { + ConnectionsWithIds subscribers; + if (subscriptions.containsKey(characteristic)) { + subscribers = subscriptions.get(characteristic); + } else { + subscribers = new ConnectionsWithIds(aid, iid); + subscriptions.put(characteristic, subscribers); + subscribe(aid, iid, characteristic); + } + subscribers.connections.add(connection); + + if (!reverse.containsKey(connection)) { + reverse.put(connection, new HashSet<>()); + } + reverse.get(connection).add(characteristic); + LOGGER.trace( + "Added subscription to {}:{} ({}) for {}", + aid, + iid, + characteristic.getClass().getSimpleName(), + connection.hashCode()); + } + } + + public synchronized void removeSubscription( + EventableCharacteristic characteristic, HomekitClientConnection connection) { + ConnectionsWithIds subscribers = subscriptions.get(characteristic); + if (subscribers != null) { + subscribers.connections.remove(connection); + if (subscribers.connections.isEmpty()) { + LOGGER.trace("Unsubscribing from characteristic as all subscriptions are closed"); + characteristic.unsubscribe(); + subscriptions.remove(characteristic); + } + + // Remove pending notifications for this no-longer-subscribed characteristic + List connectionNotifications = pendingNotifications.get(connection); + if (connectionNotifications != null) { + connectionNotifications.removeIf(n -> n.aid == subscribers.aid && n.iid == subscribers.iid); + if (connectionNotifications.isEmpty()) pendingNotifications.remove(connection); + } + + LOGGER.trace( + "Removed subscription from {}:{} ({}) for {}", + subscribers.aid, + subscribers.iid, + characteristic.getClass().getSimpleName(), + connection.hashCode()); + } + + Set reverse = this.reverse.get(connection); + if (reverse != null) { + reverse.remove(characteristic); + if (reverse.isEmpty()) this.reverse.remove(connection); + } + } + + public synchronized void removeConnection(HomekitClientConnection connection) { + removeConnection(connection, reverse.remove(connection)); + } + + private void removeConnection( + HomekitClientConnection connection, Set characteristics) { + pendingNotifications.remove(connection); + if (characteristics != null) { + for (EventableCharacteristic characteristic : characteristics) { + removeSubscription(characteristic, connection); + } + } + LOGGER.trace("Removed connection {}", connection.hashCode()); + } + + public synchronized void batchUpdate() { + ++this.nestedBatches; + } + + public synchronized void completeUpdateBatch() { + if (--this.nestedBatches == 0) flushUpdateBatch(); + } + + private void flushUpdateBatch() { + if (pendingNotifications.isEmpty()) return; + + LOGGER.trace("Publishing batched changes"); + for (Map.Entry> entry : + pendingNotifications.entrySet()) { + try { + HttpResponse message = new EventController().getMessage(entry.getValue()); + entry.getKey().outOfBand(message); + } catch (Exception e) { + LOGGER.warn("Failed to create new event message", e); + } + } + pendingNotifications.clear(); + } + + public synchronized void publish(int accessoryId, int iid, EventableCharacteristic changed) { + final ConnectionsWithIds subscribers = subscriptions.get(changed); + if (subscribers == null || subscribers.connections.isEmpty()) { + LOGGER.trace("No subscribers to characteristic {} at accessory {} ", changed, accessoryId); + return; // no subscribers + } + if (nestedBatches != 0) { + LOGGER.trace("Batching change for accessory {} and characteristic {} " + accessoryId, iid); + PendingNotification notification = new PendingNotification(accessoryId, iid, changed); + for (HomekitClientConnection connection : subscribers.connections) { + if (!pendingNotifications.containsKey(connection)) { + pendingNotifications.put(connection, new ArrayList()); + } + pendingNotifications.get(connection).add(notification); + } + return; + } + + try { + HttpResponse message = new EventController().getMessage(accessoryId, iid, changed); + LOGGER.trace("Publishing change for " + accessoryId); + for (HomekitClientConnection connection : subscribers.connections) { + connection.outOfBand(message); + } + } catch (Exception e) { + LOGGER.warn("Failed to create new event message", e); + } + } + + /** + * The accessory registry has changed; go through all subscriptions and link to any new/changed + * characteristics + */ + public synchronized void resync(HomekitRegistry registry) { + LOGGER.trace("Resyncing subscriptions"); + flushUpdateBatch(); + + Map newSubscriptions = new HashMap<>(); + Iterator> i = + subscriptions.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = i.next(); + EventableCharacteristic oldCharacteristic = entry.getKey(); + ConnectionsWithIds subscribers = entry.getValue(); + Characteristic newCharacteristic = + registry.getCharacteristics(subscribers.aid).get(subscribers.iid); + if (newCharacteristic == null || newCharacteristic.getType() != oldCharacteristic.getType()) { + // characteristic is gone or has completely changed; drop all subscriptions for it + LOGGER.trace( + "{}:{} ({}) has gone missing; dropping subscriptions.", + subscribers.aid, + subscribers.iid, + oldCharacteristic.getClass().getSimpleName()); + i.remove(); + for (HomekitClientConnection conn : subscribers.connections) { + removeSubscription(oldCharacteristic, conn); + } + } else if (newCharacteristic != oldCharacteristic) { + EventableCharacteristic newEventableCharacteristic = + (EventableCharacteristic) newCharacteristic; + LOGGER.trace( + "{}:{} has been replaced by a compatible characteristic; re-connecting subscriptions", + subscribers.aid, + subscribers.iid); + // characteristic has been replaced by another instance of the same thing; + // re-connect subscriptions + i.remove(); + oldCharacteristic.unsubscribe(); + subscribe(subscribers.aid, subscribers.iid, newEventableCharacteristic); + // we can't replace the key, and we can't add to the map while we're iterating, + // so save it off to a temporary map that we'll add them all at the end + newSubscriptions.put(newEventableCharacteristic, subscribers); + + for (HomekitClientConnection conn : subscribers.connections) { + Set subscribedCharacteristics = reverse.get(conn); + subscribedCharacteristics.remove(oldCharacteristic); + subscribedCharacteristics.add(newEventableCharacteristic); + + // and also update references for any pending notifications, so they'll get the proper + // value + List connectionPendingNotifications = pendingNotifications.get(conn); + if (connectionPendingNotifications != null) { + for (PendingNotification notification : connectionPendingNotifications) { + if (notification.characteristic == oldCharacteristic) { + notification.characteristic = newEventableCharacteristic; + } + } + } + } + } + } + subscriptions.putAll(newSubscriptions); + } + + private void subscribe(int aid, int iid, EventableCharacteristic characteristic) { + characteristic.subscribe( + () -> { + publish(aid, iid, characteristic); + }); + } + + /** Remove all existing subscriptions */ + public synchronized void removeAll() { + LOGGER.trace("Removing {} reverse connections from subscription manager", reverse.size()); + Iterator>> i = + reverse.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry> entry = i.next(); + HomekitClientConnection connection = entry.getKey(); + LOGGER.trace("Removing connection {}", connection.hashCode()); + i.remove(); + removeConnection(connection, entry.getValue()); + } + LOGGER.trace("Subscription sizes are {} and {}", reverse.size(), subscriptions.size()); + } +} diff --git a/src/main/java/io/github/hapjava/server/impl/crypto/ChachaDecoder.java b/src/main/java/io/github/hapjava/server/impl/crypto/ChachaDecoder.java new file mode 100755 index 000000000..014f4b500 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/crypto/ChachaDecoder.java @@ -0,0 +1,98 @@ +package io.github.hapjava.server.impl.crypto; + +import java.io.IOException; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.modes.ChaCha20Poly1305; +import org.bouncycastle.crypto.params.AEADParameters; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.tls.AlertDescription; +import org.bouncycastle.tls.TlsFatalAlert; + +public class ChachaDecoder { + + private final ChaCha20Poly1305 cipher; + private final byte[] key; + private final byte[] nonce; + + public ChachaDecoder(byte[] key, byte[] nonce) throws IOException { + this.key = key; + // ChaCha20-Poly1305 requires exactly 12 bytes (96 bits) for nonce + this.nonce = ensureNonceSize(nonce); + this.cipher = new ChaCha20Poly1305(); + } + + private byte[] ensureNonceSize(byte[] nonce) { + if (nonce == null) { + return new byte[12]; // Default to zero nonce if null + } + + // For HomeKit pairing messages, handle Apple's string-based nonces + if (nonce.length == 8) { + // Apple's HomeKit implementation uses a specific nonce format + // Based on RFC 7539 and Apple's implementation, the nonce should be: + // - 4 bytes constant (0x00000000) + // - 8 bytes nonce string + // This matches ChaCha20's 96-bit nonce requirement + byte[] adjustedNonce = new byte[12]; + // Put the 8-byte nonce at the END (bytes 4-11), not at the beginning + System.arraycopy(nonce, 0, adjustedNonce, 4, 8); + // First 4 bytes remain zero (counter initialization) + return adjustedNonce; + } + + if (nonce.length == 12) { + return nonce; // Already correct size + } + + // For other nonce lengths, pad or truncate to 12 bytes + byte[] adjustedNonce = new byte[12]; + if (nonce.length < 12) { + // Pad with zeros if too short - put nonce at beginning + System.arraycopy(nonce, 0, adjustedNonce, 0, nonce.length); + // Remaining bytes are already zero + } else { + // Truncate if too long - take first 12 bytes + System.arraycopy(nonce, 0, adjustedNonce, 0, 12); + } + + return adjustedNonce; + } + + public byte[] decodeCiphertext(byte[] receivedMAC, byte[] additionalData, byte[] ciphertext) + throws IOException { + + try { + byte[] ciphertextWithTag = new byte[ciphertext.length + receivedMAC.length]; + System.arraycopy(ciphertext, 0, ciphertextWithTag, 0, ciphertext.length); + System.arraycopy(receivedMAC, 0, ciphertextWithTag, ciphertext.length, receivedMAC.length); + + ChaCha20Poly1305 cipher1 = new ChaCha20Poly1305(); + AEADParameters params = new AEADParameters(new KeyParameter(key), 128, nonce, additionalData); + cipher1.init(false, params); + + byte[] output = new byte[cipher1.getOutputSize(ciphertextWithTag.length)]; + int len = cipher1.processBytes(ciphertextWithTag, 0, ciphertextWithTag.length, output, 0); + len += cipher1.doFinal(output, len); + + byte[] result = new byte[len]; + System.arraycopy(output, 0, result, 0, len); + + return result; + + } catch (InvalidCipherTextException e) { + throw new TlsFatalAlert(AlertDescription.bad_record_mac); + } + } + + private static String bytesToHex(byte[] bytes) { + StringBuilder result = new StringBuilder(); + for (byte b : bytes) { + result.append(String.format("%02x", b)); + } + return result.toString(); + } + + public byte[] decodeCiphertext(byte[] receivedMAC, byte[] ciphertext) throws IOException { + return decodeCiphertext(receivedMAC, null, ciphertext); + } +} diff --git a/src/main/java/io/github/hapjava/server/impl/crypto/ChachaEncoder.java b/src/main/java/io/github/hapjava/server/impl/crypto/ChachaEncoder.java new file mode 100755 index 000000000..889c9ca86 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/crypto/ChachaEncoder.java @@ -0,0 +1,93 @@ +package io.github.hapjava.server.impl.crypto; + +import java.io.IOException; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.modes.ChaCha20Poly1305; +import org.bouncycastle.crypto.params.AEADParameters; +import org.bouncycastle.crypto.params.KeyParameter; + +public class ChachaEncoder { + + private final ChaCha20Poly1305 cipher; + private final byte[] key; + private final byte[] nonce; + + public ChachaEncoder(byte[] key, byte[] nonce) throws IOException { + this.key = key; + // ChaCha20-Poly1305 requires exactly 12 bytes (96 bits) for nonce + this.nonce = ensureNonceSize(nonce); + this.cipher = new ChaCha20Poly1305(); + } + + private byte[] ensureNonceSize(byte[] nonce) { + if (nonce == null) { + return new byte[12]; // Default to zero nonce if null + } + + // For HomeKit pairing messages, handle Apple's string-based nonces + if (nonce.length == 8) { + // Apple's HomeKit implementation uses a specific nonce format + // Based on RFC 7539 and Apple's implementation, the nonce should be: + // - 4 bytes constant (0x00000000) + // - 8 bytes nonce string + // This matches ChaCha20's 96-bit nonce requirement and ChachaDecoder format + byte[] adjustedNonce = new byte[12]; + // Put the 8-byte nonce at the END (bytes 4-11), not at the beginning + System.arraycopy(nonce, 0, adjustedNonce, 4, 8); + // First 4 bytes remain zero (counter initialization) + return adjustedNonce; + } + + if (nonce.length == 12) { + return nonce; // Already correct size + } + + byte[] adjustedNonce = new byte[12]; + if (nonce.length < 12) { + // Pad with zeros if too short + System.arraycopy(nonce, 0, adjustedNonce, 0, nonce.length); + } else { + // Truncate if too long + System.arraycopy(nonce, 0, adjustedNonce, 0, 12); + } + return adjustedNonce; + } + + private static String bytesToHex(byte[] bytes) { + StringBuilder result = new StringBuilder(); + for (byte b : bytes) { + result.append(String.format("%02x", b)); + } + return result.toString(); + } + + public byte[] encodeCiphertext(byte[] plaintext) throws IOException { + return encodeCiphertext(plaintext, null); + } + + public byte[] encodeCiphertext(byte[] plaintext, byte[] additionalData) throws IOException { + try { + // Use the nonce provided during construction + AEADParameters params = new AEADParameters(new KeyParameter(key), 128, nonce, additionalData); + cipher.init(true, params); + + byte[] output = new byte[cipher.getOutputSize(plaintext.length)]; + int len = cipher.processBytes(plaintext, 0, plaintext.length, output, 0); + len += cipher.doFinal(output, len); + + // Split the result into ciphertext and MAC + byte[] ciphertext = new byte[plaintext.length]; + byte[] mac = new byte[16]; + System.arraycopy(output, 0, ciphertext, 0, plaintext.length); + System.arraycopy(output, plaintext.length, mac, 0, 16); + + // Return combined ciphertext + MAC as expected by the original interface + byte[] ret = new byte[ciphertext.length + 16]; + System.arraycopy(ciphertext, 0, ret, 0, ciphertext.length); + System.arraycopy(mac, 0, ret, ciphertext.length, 16); + return ret; + } catch (InvalidCipherTextException e) { + throw new IOException("Encryption failed", e); + } + } +} diff --git a/src/main/java/io/github/hapjava/impl/crypto/EdsaSigner.java b/src/main/java/io/github/hapjava/server/impl/crypto/EdsaSigner.java similarity index 96% rename from src/main/java/io/github/hapjava/impl/crypto/EdsaSigner.java rename to src/main/java/io/github/hapjava/server/impl/crypto/EdsaSigner.java index 3c522438b..a1985d186 100644 --- a/src/main/java/io/github/hapjava/impl/crypto/EdsaSigner.java +++ b/src/main/java/io/github/hapjava/server/impl/crypto/EdsaSigner.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.crypto; +package io.github.hapjava.server.impl.crypto; import java.security.InvalidKeyException; import java.security.MessageDigest; diff --git a/src/main/java/io/github/hapjava/impl/crypto/EdsaVerifier.java b/src/main/java/io/github/hapjava/server/impl/crypto/EdsaVerifier.java similarity index 95% rename from src/main/java/io/github/hapjava/impl/crypto/EdsaVerifier.java rename to src/main/java/io/github/hapjava/server/impl/crypto/EdsaVerifier.java index 4ed210a3a..e5ca8e90a 100644 --- a/src/main/java/io/github/hapjava/impl/crypto/EdsaVerifier.java +++ b/src/main/java/io/github/hapjava/server/impl/crypto/EdsaVerifier.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.crypto; +package io.github.hapjava.server.impl.crypto; import java.security.MessageDigest; import java.security.PublicKey; diff --git a/src/main/java/io/github/hapjava/server/impl/crypto/HAPSetupCodeUtils.java b/src/main/java/io/github/hapjava/server/impl/crypto/HAPSetupCodeUtils.java new file mode 100644 index 000000000..ecf4d61de --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/crypto/HAPSetupCodeUtils.java @@ -0,0 +1,68 @@ +package io.github.hapjava.server.impl.crypto; + +import java.util.Base64; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; + +public class HAPSetupCodeUtils { + private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + + public static String randomAlphaNumeric(int count) { + StringBuilder builder = new StringBuilder(); + while (count-- != 0) { + int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length()); + builder.append(ALPHA_NUMERIC_STRING.charAt(character)); + } + return builder.toString(); + } + + public static String generateSetupId() { + return randomAlphaNumeric(4); + } + + private static byte[] calculateHash(final String input, final Digest digest) { + byte[] inputAsBytes = input.getBytes(); + byte[] retValue = new byte[digest.getDigestSize()]; + digest.update(inputAsBytes, 0, inputAsBytes.length); + digest.doFinal(retValue, 0); + return retValue; + } + + /** + * generate SHA52 Hash for given string. The hash is used for mDNS advertisement. + * + * @param value value + * @return hash + */ + public static String generateSHA512Hash(final String value) { + final byte[] hash = calculateHash(value.toUpperCase(), new SHA512Digest()); + final byte[] hashTuncate = new byte[4]; + System.arraycopy(hash, 0, hashTuncate, 0, 4); + String hashStr = Base64.getEncoder().encodeToString(hashTuncate); + return hashStr; + } + + /** + * generate Setup URI which can be used fo QR Code generation. + * + * @param pin PIN number without "-" + * @param setupId alphanumeric string of the length 4 + * @param category accessory category + * @return setup UID + */ + public static String getSetupURI(final String pin, final String setupId, final int category) { + long code = + 0 << 43 // Version + | 0 << 39 // Reserved + | ((long) category) << 31 // Category + | 0 << 29 // BLE support + | 1 << 28 // IP support + | 0 << 27 // Paired / NFC + | Integer.valueOf(pin); // PIN + String payload = Long.toString(code, 36) + setupId; + while (payload.length() < 13) { + payload = '0' + payload; + } + return "X-HM://" + payload.toUpperCase(); + } +} diff --git a/src/main/java/io/github/hapjava/impl/crypto/PolyKeyCreator.java b/src/main/java/io/github/hapjava/server/impl/crypto/PolyKeyCreator.java similarity index 96% rename from src/main/java/io/github/hapjava/impl/crypto/PolyKeyCreator.java rename to src/main/java/io/github/hapjava/server/impl/crypto/PolyKeyCreator.java index 9d314aa5c..ed66342c8 100644 --- a/src/main/java/io/github/hapjava/impl/crypto/PolyKeyCreator.java +++ b/src/main/java/io/github/hapjava/server/impl/crypto/PolyKeyCreator.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.crypto; +package io.github.hapjava.server.impl.crypto; import org.bouncycastle.crypto.macs.Poly1305; import org.bouncycastle.crypto.params.KeyParameter; diff --git a/src/main/java/io/github/hapjava/impl/http/HomekitClientConnection.java b/src/main/java/io/github/hapjava/server/impl/http/HomekitClientConnection.java similarity index 75% rename from src/main/java/io/github/hapjava/impl/http/HomekitClientConnection.java rename to src/main/java/io/github/hapjava/server/impl/http/HomekitClientConnection.java index b91cad70b..2648808bb 100644 --- a/src/main/java/io/github/hapjava/impl/http/HomekitClientConnection.java +++ b/src/main/java/io/github/hapjava/server/impl/http/HomekitClientConnection.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.http; +package io.github.hapjava.server.impl.http; import java.io.IOException; @@ -13,4 +13,8 @@ public interface HomekitClientConnection { void close(); void outOfBand(HttpResponse message); + + default String getUsername() { + return null; + } } diff --git a/src/main/java/io/github/hapjava/impl/http/HomekitClientConnectionFactory.java b/src/main/java/io/github/hapjava/server/impl/http/HomekitClientConnectionFactory.java similarity index 80% rename from src/main/java/io/github/hapjava/impl/http/HomekitClientConnectionFactory.java rename to src/main/java/io/github/hapjava/server/impl/http/HomekitClientConnectionFactory.java index 435d592a6..18c814306 100644 --- a/src/main/java/io/github/hapjava/impl/http/HomekitClientConnectionFactory.java +++ b/src/main/java/io/github/hapjava/server/impl/http/HomekitClientConnectionFactory.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.http; +package io.github.hapjava.server.impl.http; import java.util.function.Consumer; diff --git a/src/main/java/io/github/hapjava/impl/http/HttpMethod.java b/src/main/java/io/github/hapjava/server/impl/http/HttpMethod.java similarity index 52% rename from src/main/java/io/github/hapjava/impl/http/HttpMethod.java rename to src/main/java/io/github/hapjava/server/impl/http/HttpMethod.java index 014bf024a..f4844b667 100644 --- a/src/main/java/io/github/hapjava/impl/http/HttpMethod.java +++ b/src/main/java/io/github/hapjava/server/impl/http/HttpMethod.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.http; +package io.github.hapjava.server.impl.http; public enum HttpMethod { GET, diff --git a/src/main/java/io/github/hapjava/impl/http/HttpRequest.java b/src/main/java/io/github/hapjava/server/impl/http/HttpRequest.java similarity index 69% rename from src/main/java/io/github/hapjava/impl/http/HttpRequest.java rename to src/main/java/io/github/hapjava/server/impl/http/HttpRequest.java index 088050ad9..9921af341 100644 --- a/src/main/java/io/github/hapjava/impl/http/HttpRequest.java +++ b/src/main/java/io/github/hapjava/server/impl/http/HttpRequest.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.http; +package io.github.hapjava.server.impl.http; public interface HttpRequest { diff --git a/src/main/java/io/github/hapjava/impl/http/HttpResponse.java b/src/main/java/io/github/hapjava/server/impl/http/HttpResponse.java similarity index 91% rename from src/main/java/io/github/hapjava/impl/http/HttpResponse.java rename to src/main/java/io/github/hapjava/server/impl/http/HttpResponse.java index 205ff5e56..4871dba99 100644 --- a/src/main/java/io/github/hapjava/impl/http/HttpResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/http/HttpResponse.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.http; +package io.github.hapjava.server.impl.http; import java.nio.ByteBuffer; import java.util.Collections; diff --git a/src/main/java/io/github/hapjava/impl/http/impl/AccessoryHandler.java b/src/main/java/io/github/hapjava/server/impl/http/impl/AccessoryHandler.java similarity index 79% rename from src/main/java/io/github/hapjava/impl/http/impl/AccessoryHandler.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/AccessoryHandler.java index 20d4246ac..6b840c713 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/AccessoryHandler.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/AccessoryHandler.java @@ -1,8 +1,8 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; -import io.github.hapjava.impl.http.HomekitClientConnection; -import io.github.hapjava.impl.http.HomekitClientConnectionFactory; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory; +import io.github.hapjava.server.impl.http.HttpResponse; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; @@ -36,13 +36,13 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { } channel.writeAndFlush(NettyResponseUtil.createResponse(response)); }); - LOGGER.info("New homekit connection from " + ctx.channel().remoteAddress().toString()); + LOGGER.trace("New HomeKit connection from " + ctx.channel().remoteAddress().toString()); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { - LOGGER.info("Terminated homekit connection from " + ctx.channel().remoteAddress().toString()); + LOGGER.trace("Terminated HomeKit connection from " + ctx.channel().remoteAddress().toString()); super.channelInactive(ctx); } @@ -57,7 +57,7 @@ public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws } sendResponse(response, ctx); } catch (Exception e) { - LOGGER.error("Error handling homekit http request", e); + LOGGER.warn("Error handling homekit http request", e); sendResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Error: " + e.getMessage(), ctx); } } @@ -72,9 +72,9 @@ private void sendResponse( HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(responseBody.getBytes(StandardCharsets.UTF_8))); - response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); - response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); - response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); + response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); + response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); + response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); ctx.flush(); } @@ -95,7 +95,7 @@ public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { boolean errorLevel = !(cause instanceof IOException); if (errorLevel) { - LOGGER.error("Exception caught in web handler", cause); + LOGGER.warn("Exception caught in web handler", cause); } else { LOGGER.debug("Exception caught in web handler", cause); } diff --git a/src/main/java/io/github/hapjava/impl/http/impl/BinaryHandler.java b/src/main/java/io/github/hapjava/server/impl/http/impl/BinaryHandler.java similarity index 92% rename from src/main/java/io/github/hapjava/impl/http/impl/BinaryHandler.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/BinaryHandler.java index cb5335ee0..4f4c80788 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/BinaryHandler.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/BinaryHandler.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; -import io.github.hapjava.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HomekitClientConnection; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; @@ -49,7 +49,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) t public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { boolean errorLevel = !(cause instanceof IOException); if (errorLevel) { - logger.error("Exception in binary handler", cause); + logger.warn("Exception in binary handler", cause); } else { logger.debug("Exception in binary handler", cause); } diff --git a/src/main/java/io/github/hapjava/impl/http/impl/DefaultHttpRequestImpl.java b/src/main/java/io/github/hapjava/server/impl/http/impl/DefaultHttpRequestImpl.java similarity index 76% rename from src/main/java/io/github/hapjava/impl/http/impl/DefaultHttpRequestImpl.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/DefaultHttpRequestImpl.java index 1fe33c48f..a124705f1 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/DefaultHttpRequestImpl.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/DefaultHttpRequestImpl.java @@ -1,7 +1,7 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; -import io.github.hapjava.impl.http.HttpMethod; -import io.github.hapjava.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpMethod; +import io.github.hapjava.server.impl.http.HttpRequest; class DefaultHttpRequestImpl implements HttpRequest { @@ -13,7 +13,7 @@ public DefaultHttpRequestImpl(io.netty.handler.codec.http.HttpRequest request) { @Override public String getUri() { - return request.getUri(); + return request.uri(); } @Override @@ -23,7 +23,7 @@ public byte[] getBody() { @Override public HttpMethod getMethod() { - io.netty.handler.codec.http.HttpMethod method = request.getMethod(); + io.netty.handler.codec.http.HttpMethod method = request.method(); if (method.equals(io.netty.handler.codec.http.HttpMethod.GET)) { return HttpMethod.GET; } else if (method.equals(io.netty.handler.codec.http.HttpMethod.POST)) { diff --git a/src/main/java/io/github/hapjava/impl/http/impl/FullRequestHttpRequestImpl.java b/src/main/java/io/github/hapjava/server/impl/http/impl/FullRequestHttpRequestImpl.java similarity index 90% rename from src/main/java/io/github/hapjava/impl/http/impl/FullRequestHttpRequestImpl.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/FullRequestHttpRequestImpl.java index ee82d15f4..088ec9832 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/FullRequestHttpRequestImpl.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/FullRequestHttpRequestImpl.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; import io.netty.handler.codec.http.FullHttpRequest; diff --git a/src/main/java/io/github/hapjava/impl/http/impl/HomekitHttpServer.java b/src/main/java/io/github/hapjava/server/impl/http/impl/HomekitHttpServer.java similarity index 85% rename from src/main/java/io/github/hapjava/impl/http/impl/HomekitHttpServer.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/HomekitHttpServer.java index 3a8773132..085d632cf 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/HomekitHttpServer.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/HomekitHttpServer.java @@ -1,7 +1,7 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; -import io.github.hapjava.impl.HomekitWebHandler; -import io.github.hapjava.impl.http.HomekitClientConnectionFactory; +import io.github.hapjava.server.HomekitWebHandler; +import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory; import java.net.InetAddress; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/io/github/hapjava/impl/http/impl/HttpResponseEncoderAggregate.java b/src/main/java/io/github/hapjava/server/impl/http/impl/HttpResponseEncoderAggregate.java similarity index 92% rename from src/main/java/io/github/hapjava/impl/http/impl/HttpResponseEncoderAggregate.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/HttpResponseEncoderAggregate.java index 23ac740fa..96aee2fe7 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/HttpResponseEncoderAggregate.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/HttpResponseEncoderAggregate.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/src/main/java/io/github/hapjava/server/impl/http/impl/LoggingHandler.java b/src/main/java/io/github/hapjava/server/impl/http/impl/LoggingHandler.java new file mode 100644 index 000000000..5b271dc24 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/LoggingHandler.java @@ -0,0 +1,56 @@ +package io.github.hapjava.server.impl.http.impl; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.*; +import java.io.IOException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LoggingHandler extends ChannelDuplexHandler { + + private static final Logger logger = LoggerFactory.getLogger(LoggingHandler.class); + private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (logger.isTraceEnabled() && msg instanceof ByteBuf) { + logBytes("READ", (ByteBuf) msg, ctx); + } + super.channelRead(ctx, msg); + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) + throws Exception { + if (logger.isTraceEnabled() && msg instanceof ByteBuf) { + logBytes("WRITE", (ByteBuf) msg, ctx); + } + super.write(ctx, msg, promise); + } + + private void logBytes(String type, ByteBuf buf, ChannelHandlerContext ctx) throws IOException { + if (buf.readableBytes() > 0) { + byte[] bytes = new byte[buf.readableBytes()]; + buf.getBytes(0, bytes, 0, bytes.length); + logger.trace( + String.format( + "%s %s [%s]:%n%s%n", + type, buf, ctx.channel().remoteAddress().toString(), bytesToHex(bytes))); + } + } + + /* + This method is licensed under CC-BY-SA and published on Stackoverflow + https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java + from the answer by Melquiades https://stackoverflow.com/users/2964945/melquiades + */ + private String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = HEX_ARRAY[v >>> 4]; + hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; + } + return new String(hexChars); + } +} diff --git a/src/main/java/io/github/hapjava/impl/http/impl/NettyHomekitHttpService.java b/src/main/java/io/github/hapjava/server/impl/http/impl/NettyHomekitHttpService.java similarity index 92% rename from src/main/java/io/github/hapjava/impl/http/impl/NettyHomekitHttpService.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/NettyHomekitHttpService.java index 2bc427d54..aad5d5a13 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/NettyHomekitHttpService.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/NettyHomekitHttpService.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; -import io.github.hapjava.impl.http.HomekitClientConnectionFactory; +import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.group.ChannelGroup; @@ -59,7 +59,7 @@ public void operationComplete(Future future) throws Exception { future.get(); SocketAddress socketAddress = bindFuture.channel().localAddress(); if (socketAddress instanceof InetSocketAddress) { - logger.info("Bound homekit listener to " + socketAddress.toString()); + logger.trace("Bound homekit listener to " + socketAddress.toString()); portFuture.complete(((InetSocketAddress) socketAddress).getPort()); } else { throw new RuntimeException( @@ -79,7 +79,7 @@ public void shutdown() { } public void resetConnections() { - logger.info("Resetting connections"); + logger.trace("Resetting connections"); allChannels.close(); } } diff --git a/src/main/java/io/github/hapjava/impl/http/impl/NettyResponseUtil.java b/src/main/java/io/github/hapjava/server/impl/http/impl/NettyResponseUtil.java similarity index 72% rename from src/main/java/io/github/hapjava/impl/http/impl/NettyResponseUtil.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/NettyResponseUtil.java index c9b141771..9e7963fb3 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/NettyResponseUtil.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/NettyResponseUtil.java @@ -1,10 +1,11 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.http.HttpResponse; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; -import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import java.util.Map.Entry; @@ -25,8 +26,8 @@ public static FullHttpResponse createResponse(HttpResponse homekitResponse) { for (Entry header : homekitResponse.getHeaders().entrySet()) { response.headers().add(header.getKey(), header.getValue()); } - response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); - response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); + response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); + response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); return response; } } diff --git a/src/main/java/io/github/hapjava/impl/http/impl/ServerInitializer.java b/src/main/java/io/github/hapjava/server/impl/http/impl/ServerInitializer.java similarity index 92% rename from src/main/java/io/github/hapjava/impl/http/impl/ServerInitializer.java rename to src/main/java/io/github/hapjava/server/impl/http/impl/ServerInitializer.java index ed447a1af..3c914ffe7 100644 --- a/src/main/java/io/github/hapjava/impl/http/impl/ServerInitializer.java +++ b/src/main/java/io/github/hapjava/server/impl/http/impl/ServerInitializer.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.http.impl; +package io.github.hapjava.server.impl.http.impl; -import io.github.hapjava.impl.http.HomekitClientConnectionFactory; +import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; diff --git a/src/main/java/io/github/hapjava/server/impl/jmdns/JmdnsHomekitAdvertiser.java b/src/main/java/io/github/hapjava/server/impl/jmdns/JmdnsHomekitAdvertiser.java new file mode 100644 index 000000000..1073f9b86 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/jmdns/JmdnsHomekitAdvertiser.java @@ -0,0 +1,158 @@ +package io.github.hapjava.server.impl.jmdns; + +import static io.github.hapjava.server.impl.crypto.HAPSetupCodeUtils.generateSHA512Hash; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Map; +import javax.jmdns.JmDNS; +import javax.jmdns.ServiceInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JmdnsHomekitAdvertiser { + + private static final String SERVICE_TYPE = "_hap._tcp.local."; + + private final JmDNS jmdns; + private final boolean ownsJmdns; + private Thread shutdownHook; + private boolean discoverable = true; + private static final Logger logger = LoggerFactory.getLogger(JmdnsHomekitAdvertiser.class); + private boolean isAdvertising = false; + + private String label; + private String mac; + private String setupId; + private int port; + private int configurationIndex; + private ServiceInfo serviceInfo; + private int category; + + public JmdnsHomekitAdvertiser(JmDNS jmdns) { + this(jmdns, false); + } + + public JmdnsHomekitAdvertiser(InetAddress localAddress) throws UnknownHostException, IOException { + this(JmDNS.create(localAddress), true); + } + + JmdnsHomekitAdvertiser(JmDNS jmdns, boolean ownsJmdns) { + this.jmdns = jmdns; + this.ownsJmdns = ownsJmdns; + } + + public synchronized void advertise( + String label, int category, String mac, int port, int configurationIndex, String setupId) + throws Exception { + if (isAdvertising) { + throw new IllegalStateException("HomeKit advertiser is already running"); + } + this.label = label; + this.mac = mac; + this.port = port; + this.setupId = setupId; + this.category = category; + this.configurationIndex = configurationIndex; + + logger.trace("Advertising accessory " + label); + + registerService(); + + shutdownHook = + new Thread( + () -> { + logger.trace("Stopping advertising in response to shutdown."); + jmdns.unregisterAllServices(); + }); + Runtime.getRuntime().addShutdownHook(shutdownHook); + isAdvertising = true; + } + + public synchronized void stop() { + unregisterService(); + isAdvertising = false; + if (shutdownHook != null) { + try { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } catch (IllegalStateException e) { + // already shutting down + } + } + if (ownsJmdns) { + try { + jmdns.close(); + } catch (IOException e) { + logger.warn("Failed to close mDNS", e); + } + } + } + + public synchronized void setDiscoverable(boolean discoverable) throws IOException { + if (this.discoverable != discoverable) { + this.discoverable = discoverable; + if (isAdvertising) { + logger.trace("Re-creating service due to change in discoverability to " + discoverable); + unregisterService(); + registerService(); + } + } + } + + public synchronized void setMac(String mac) throws IOException { + if (this.mac != mac) { + this.mac = mac; + if (isAdvertising) { + logger.trace("Re-creating service due to change in mac to " + mac); + unregisterService(); + registerService(); + } + } + } + + public synchronized void setConfigurationIndex(int revision) throws IOException { + if (this.configurationIndex != revision) { + this.configurationIndex = revision; + if (isAdvertising) { + logger.trace("Re-creating service due to change in configuration index to " + revision); + unregisterService(); + registerService(); + } + } + } + + private void unregisterService() { + if (serviceInfo != null) { + jmdns.unregisterService(serviceInfo); + serviceInfo = null; + } + } + + private void registerService() throws IOException { + logger.info("Registering " + SERVICE_TYPE + " on port " + port); + if (this.serviceInfo != null) { + throw new AssertionError( + "Registering an already registered service without unregistering first is not allowed"); + } + serviceInfo = buildServiceInfo(); + jmdns.registerService(serviceInfo); + } + + private ServiceInfo buildServiceInfo() { + logger.trace("MAC:" + mac + " Setup Id:" + setupId); + Map props = new HashMap<>(); + props.put("sf", discoverable ? "1" : "0"); + props.put("id", mac); + props.put("md", label); + props.put("sh", generateSHA512Hash(setupId + mac)); + props.put("c#", Integer.toString(configurationIndex)); + props.put("s#", "1"); + props.put("ff", "0"); + props.put("ci", Integer.toString(category)); + props.put("pv", "1.1"); + + return ServiceInfo.create(SERVICE_TYPE, label, port, 1, 1, props); + } +} diff --git a/src/main/java/io/github/hapjava/impl/json/AccessoryController.java b/src/main/java/io/github/hapjava/server/impl/json/AccessoryController.java similarity index 59% rename from src/main/java/io/github/hapjava/impl/json/AccessoryController.java rename to src/main/java/io/github/hapjava/server/impl/json/AccessoryController.java index 66c46bdcf..fdd223ec3 100644 --- a/src/main/java/io/github/hapjava/impl/json/AccessoryController.java +++ b/src/main/java/io/github/hapjava/server/impl/json/AccessoryController.java @@ -1,10 +1,10 @@ -package io.github.hapjava.impl.json; +package io.github.hapjava.server.impl.json; -import io.github.hapjava.HomekitAccessory; -import io.github.hapjava.Service; +import io.github.hapjava.accessories.HomekitAccessory; import io.github.hapjava.characteristics.Characteristic; -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.services.Service; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Collection; @@ -13,10 +13,12 @@ import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; +import javax.json.JsonWriter; public class AccessoryController { @@ -31,12 +33,18 @@ public HttpResponse listing() throws Exception { Map>> accessoryServiceFutures = new HashMap<>(); for (HomekitAccessory accessory : registry.getAccessories()) { - int iid = 0; List> serviceFutures = new ArrayList<>(); - for (Service service : registry.getServices(accessory.getId())) { - serviceFutures.add(toJson(service, iid)); - iid += service.getCharacteristics().size() + 1; + + Map servicesByInterfaceId = registry.getServices(accessory.getId()); + + Map iidLookup = new HashMap<>(); + iidLookup.putAll(swapKeyAndValue(servicesByInterfaceId)); + iidLookup.putAll(swapKeyAndValue(registry.getCharacteristics(accessory.getId()))); + + for (Service service : servicesByInterfaceId.values()) { + serviceFutures.add(toJson(service, iidLookup, accessory.getPrimaryService() == service)); } + accessoryServiceFutures.put(accessory.getId(), serviceFutures); } @@ -57,23 +65,25 @@ public HttpResponse listing() throws Exception { .add("services", serviceArrayBuilders.get(accessory.getId()))); } - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - Json.createWriter(baos) - .write(Json.createObjectBuilder().add("accessories", accessories).build()); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter jsonWriter = Json.createWriter(baos)) { + jsonWriter.write(Json.createObjectBuilder().add("accessories", accessories).build()); return new HapJsonResponse(baos.toByteArray()); } } - private CompletableFuture toJson(Service service, int interfaceId) throws Exception { + private CompletableFuture toJson( + Service service, Map iidLookup, boolean isPrimary) throws Exception { String shortType = service.getType().replaceAll("^0*([0-9a-fA-F]+)-0000-1000-8000-0026BB765291$", "$1"); JsonObjectBuilder builder = - Json.createObjectBuilder().add("iid", ++interfaceId).add("type", shortType); + Json.createObjectBuilder().add("iid", iidLookup.get(service)).add("type", shortType); List characteristics = service.getCharacteristics(); Collection> characteristicFutures = new ArrayList<>(characteristics.size()); for (Characteristic characteristic : characteristics) { - characteristicFutures.add(characteristic.toJson(++interfaceId)); + Integer iid = iidLookup.get(characteristic); + characteristicFutures.add(characteristic.toJson(iid)); } return CompletableFuture.allOf( @@ -85,7 +95,20 @@ private CompletableFuture toJson(Service service, int interfaceId) t .map(future -> future.join()) .forEach(c -> jsonCharacteristics.add(c)); builder.add("characteristics", jsonCharacteristics); + + if (!service.getLinkedServices().isEmpty()) { + JsonArrayBuilder jsonLinkedServices = Json.createArrayBuilder(); + service.getLinkedServices().stream() + .map(iidLookup::get) + .forEach(jsonLinkedServices::add); + builder.add("linked", jsonLinkedServices); + } + builder.add("primary", isPrimary); return builder.build(); }); } + + private Map swapKeyAndValue(Map map) { + return map.entrySet().stream().collect(Collectors.toMap(Entry::getValue, Entry::getKey)); + } } diff --git a/src/main/java/io/github/hapjava/impl/json/CharacteristicsController.java b/src/main/java/io/github/hapjava/server/impl/json/CharacteristicsController.java similarity index 73% rename from src/main/java/io/github/hapjava/impl/json/CharacteristicsController.java rename to src/main/java/io/github/hapjava/server/impl/json/CharacteristicsController.java index 8a85956e7..f5f8bb87c 100644 --- a/src/main/java/io/github/hapjava/impl/json/CharacteristicsController.java +++ b/src/main/java/io/github/hapjava/server/impl/json/CharacteristicsController.java @@ -1,13 +1,13 @@ -package io.github.hapjava.impl.json; +package io.github.hapjava.server.impl.json; import io.github.hapjava.characteristics.Characteristic; import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.connections.SubscriptionManager; -import io.github.hapjava.impl.http.HomekitClientConnection; -import io.github.hapjava.impl.http.HttpRequest; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.responses.NotFoundResponse; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.connections.SubscriptionManager; +import io.github.hapjava.server.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.responses.NotFoundResponse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Map; @@ -36,7 +36,7 @@ public HttpResponse get(HttpRequest request) throws Exception { for (String id : ids) { String[] parts = id.split("\\."); if (parts.length != 2) { - logger.error("Unexpected characteristics request: " + uri); + logger.warn("Unexpected characteristics request: " + uri); return new NotFoundResponse(); } int aid = Integer.parseInt(parts[0]); @@ -51,17 +51,17 @@ public HttpResponse get(HttpRequest request) throws Exception { characteristics.add(characteristic.add("aid", aid).add("iid", iid).build()); } else { logger.warn( - "Accessory " + aid + " does not have characteristic " + iid + "Request: " + uri); + "Accessory " + aid + " does not have characteristic " + iid + ". Request: " + uri); } } else { logger.warn( "Accessory " + aid + " has no characteristics or does not exist. Request: " + uri); } } - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - Json.createWriter(baos) - .write( - Json.createObjectBuilder().add("characteristics", characteristics.build()).build()); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter jsonWriter = Json.createWriter(baos)) { + jsonWriter.write( + Json.createObjectBuilder().add("characteristics", characteristics.build()).build()); return new HapJsonResponse(baos.toByteArray()); } } @@ -77,10 +77,19 @@ public HttpResponse put(HttpRequest request, HomekitClientConnection connection) JsonObject jsonCharacteristic = (JsonObject) value; int aid = jsonCharacteristic.getInt("aid"); int iid = jsonCharacteristic.getInt("iid"); - Characteristic characteristic = registry.getCharacteristics(aid).get(iid); + Map accessory = registry.getCharacteristics(aid); + if (accessory.isEmpty()) { + logger.warn("Accessory {} has no characteristics or does not exist.", aid); + return new HapJsonNoContentResponse(); + } + Characteristic characteristic = accessory.get(iid); + if (characteristic == null) { + logger.warn("Accessory {} does not have characteristic {}.", aid, iid); + return new HapJsonNoContentResponse(); + } if (jsonCharacteristic.containsKey("value")) { - characteristic.setValue(jsonCharacteristic.get("value")); + characteristic.setValue(jsonCharacteristic.get("value"), connection.getUsername()); } if (jsonCharacteristic.containsKey("ev") && characteristic instanceof EventableCharacteristic) { diff --git a/src/main/java/io/github/hapjava/impl/json/EventController.java b/src/main/java/io/github/hapjava/server/impl/json/EventController.java similarity index 77% rename from src/main/java/io/github/hapjava/impl/json/EventController.java rename to src/main/java/io/github/hapjava/server/impl/json/EventController.java index 9322f2507..0c7c2bc7c 100644 --- a/src/main/java/io/github/hapjava/impl/json/EventController.java +++ b/src/main/java/io/github/hapjava/server/impl/json/EventController.java @@ -1,14 +1,15 @@ -package io.github.hapjava.impl.json; +package io.github.hapjava.server.impl.json; import io.github.hapjava.characteristics.EventableCharacteristic; -import io.github.hapjava.impl.connections.PendingNotification; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.connections.PendingNotification; +import io.github.hapjava.server.impl.http.HttpResponse; import java.io.ByteArrayOutputStream; -import java.util.ArrayList; +import java.util.List; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; +import javax.json.JsonWriter; public class EventController { @@ -24,15 +25,16 @@ public HttpResponse getMessage(int accessoryId, int iid, EventableCharacteristic JsonObject data = Json.createObjectBuilder().add("characteristics", characteristics).build(); - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - Json.createWriter(baos).write(data); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter jsonWriter = Json.createWriter(baos)) { + jsonWriter.write(data); byte[] dataBytes = baos.toByteArray(); return new EventResponse(dataBytes); } } - public HttpResponse getMessage(ArrayList notifications) throws Exception { + public HttpResponse getMessage(List notifications) throws Exception { JsonArrayBuilder characteristics = Json.createArrayBuilder(); for (PendingNotification notification : notifications) { @@ -44,9 +46,9 @@ public HttpResponse getMessage(ArrayList notifications) thr } JsonObject data = Json.createObjectBuilder().add("characteristics", characteristics).build(); - - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - Json.createWriter(baos).write(data); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter jsonWriter = Json.createWriter(baos)) { + jsonWriter.write(data); byte[] dataBytes = baos.toByteArray(); return new EventResponse(dataBytes); diff --git a/src/main/java/io/github/hapjava/impl/json/EventResponse.java b/src/main/java/io/github/hapjava/server/impl/json/EventResponse.java similarity index 82% rename from src/main/java/io/github/hapjava/impl/json/EventResponse.java rename to src/main/java/io/github/hapjava/server/impl/json/EventResponse.java index faa4478b3..113582c5b 100644 --- a/src/main/java/io/github/hapjava/impl/json/EventResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/json/EventResponse.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.json; +package io.github.hapjava.server.impl.json; public class EventResponse extends HapJsonResponse { diff --git a/src/main/java/io/github/hapjava/impl/json/HapJsonNoContentResponse.java b/src/main/java/io/github/hapjava/server/impl/json/HapJsonNoContentResponse.java similarity index 81% rename from src/main/java/io/github/hapjava/impl/json/HapJsonNoContentResponse.java rename to src/main/java/io/github/hapjava/server/impl/json/HapJsonNoContentResponse.java index fbb5066bb..be01ebbe3 100644 --- a/src/main/java/io/github/hapjava/impl/json/HapJsonNoContentResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/json/HapJsonNoContentResponse.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.json; +package io.github.hapjava.server.impl.json; class HapJsonNoContentResponse extends HapJsonResponse { diff --git a/src/main/java/io/github/hapjava/impl/json/HapJsonResponse.java b/src/main/java/io/github/hapjava/server/impl/json/HapJsonResponse.java similarity index 84% rename from src/main/java/io/github/hapjava/impl/json/HapJsonResponse.java rename to src/main/java/io/github/hapjava/server/impl/json/HapJsonResponse.java index 1696a7f0a..dbbe7cada 100644 --- a/src/main/java/io/github/hapjava/impl/json/HapJsonResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/json/HapJsonResponse.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.json; +package io.github.hapjava.server.impl.json; -import io.github.hapjava.impl.responses.OkResponse; +import io.github.hapjava.server.impl.responses.OkResponse; import java.util.Collections; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/io/github/hapjava/impl/pairing/ByteUtils.java b/src/main/java/io/github/hapjava/server/impl/pairing/ByteUtils.java similarity index 95% rename from src/main/java/io/github/hapjava/impl/pairing/ByteUtils.java rename to src/main/java/io/github/hapjava/server/impl/pairing/ByteUtils.java index 8f903811b..6516e2e29 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/ByteUtils.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/ByteUtils.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/io/github/hapjava/impl/pairing/ClientEvidenceRoutineImpl.java b/src/main/java/io/github/hapjava/server/impl/pairing/ClientEvidenceRoutineImpl.java similarity index 97% rename from src/main/java/io/github/hapjava/impl/pairing/ClientEvidenceRoutineImpl.java rename to src/main/java/io/github/hapjava/server/impl/pairing/ClientEvidenceRoutineImpl.java index db464b8fb..16c514707 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/ClientEvidenceRoutineImpl.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/ClientEvidenceRoutineImpl.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import com.nimbusds.srp6.*; import java.math.BigInteger; diff --git a/src/main/java/io/github/hapjava/server/impl/pairing/ErrorCode.java b/src/main/java/io/github/hapjava/server/impl/pairing/ErrorCode.java new file mode 100644 index 000000000..90112fc46 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/pairing/ErrorCode.java @@ -0,0 +1,26 @@ +package io.github.hapjava.server.impl.pairing; + +public enum ErrorCode { + OK(0), + UNKNOWN(1), + AUTHENTICATION(2), + BACKOFF(3), + MAX_PEERS(4), + MAX_TRIES(5), + UNAVAILABLE(6), + BUSY(7); + + private final short key; + + ErrorCode(short key) { + this.key = key; + } + + ErrorCode(int key) { + this.key = (short) key; + } + + public short getKey() { + return key; + } +} diff --git a/src/main/java/io/github/hapjava/impl/pairing/FinalPairHandler.java b/src/main/java/io/github/hapjava/server/impl/pairing/ExchangeHandler.java old mode 100644 new mode 100755 similarity index 61% rename from src/main/java/io/github/hapjava/impl/pairing/FinalPairHandler.java rename to src/main/java/io/github/hapjava/server/impl/pairing/ExchangeHandler.java index 29b8b88a3..6bae3ab84 --- a/src/main/java/io/github/hapjava/impl/pairing/FinalPairHandler.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/ExchangeHandler.java @@ -1,24 +1,31 @@ -package io.github.hapjava.impl.pairing; - -import io.github.hapjava.HomekitAuthInfo; -import io.github.hapjava.impl.crypto.*; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.pairing.PairSetupRequest.Stage3Request; -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.DecodeResult; -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.Encoder; +package io.github.hapjava.server.impl.pairing; + +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.crypto.ChachaDecoder; +import io.github.hapjava.server.impl.crypto.ChachaEncoder; +import io.github.hapjava.server.impl.crypto.EdsaSigner; +import io.github.hapjava.server.impl.crypto.EdsaVerifier; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.pairing.PairSetupRequest.ExchangeRequest; +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.DecodeResult; +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.Encoder; import java.nio.charset.StandardCharsets; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.generators.HKDFBytesGenerator; import org.bouncycastle.crypto.params.HKDFParameters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -class FinalPairHandler { +class ExchangeHandler { private final byte[] k; private final HomekitAuthInfo authInfo; private byte[] hkdf_enc_key; - public FinalPairHandler(byte[] k, HomekitAuthInfo authInfo) { + private static final Logger LOGGER = LoggerFactory.getLogger(ExchangeHandler.class); + + public ExchangeHandler(byte[] k, HomekitAuthInfo authInfo) { this.k = k; this.authInfo = authInfo; } @@ -33,12 +40,21 @@ public HttpResponse handle(PairSetupRequest req) throws Exception { byte[] okm = hkdf_enc_key = new byte[32]; hkdf.generateBytes(okm, 0, 32); - return decrypt((Stage3Request) req, okm); + return decrypt((ExchangeRequest) req, okm); + } + + private HttpResponse decrypt(ExchangeRequest req, byte[] key) throws Exception { + try { + ChachaDecoder chacha = new ChachaDecoder(key, "PS-Msg05".getBytes(StandardCharsets.UTF_8)); + byte[] plaintext = chacha.decodeCiphertext(req.getAuthTagData(), req.getMessageData()); + return processDecryptedData(plaintext); + } catch (Exception e) { + LOGGER.error("ExchangeHandler: M5 decryption failed: {}", e.getMessage()); + throw new RuntimeException("HomeKit M5 message decryption failed", e); + } } - private HttpResponse decrypt(Stage3Request req, byte[] key) throws Exception { - ChachaDecoder chacha = new ChachaDecoder(key, "PS-Msg05".getBytes(StandardCharsets.UTF_8)); - byte[] plaintext = chacha.decodeCiphertext(req.getAuthTagData(), req.getMessageData()); + private HttpResponse processDecryptedData(byte[] plaintext) throws Exception { DecodeResult d = TypeLengthValueUtils.decode(plaintext); byte[] username = d.getBytes(MessageType.USERNAME); @@ -47,6 +63,14 @@ private HttpResponse decrypt(Stage3Request req, byte[] key) throws Exception { return createUser(username, ltpk, proof); } + private static String bytesToHex(byte[] bytes) { + StringBuilder result = new StringBuilder(); + for (byte b : bytes) { + result.append(String.format("%02x", b)); + } + return result.toString(); + } + private HttpResponse createUser(byte[] username, byte[] ltpk, byte[] proof) throws Exception { HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA512Digest()); hkdf.init( @@ -60,9 +84,11 @@ private HttpResponse createUser(byte[] username, byte[] ltpk, byte[] proof) thro byte[] completeData = ByteUtils.joinBytes(okm, username, ltpk); if (!new EdsaVerifier(ltpk).verify(completeData, proof)) { - throw new Exception("Invalid signature"); + return new PairingResponse(6, ErrorCode.AUTHENTICATION); } - authInfo.createUser(authInfo.getMac() + new String(username, StandardCharsets.UTF_8), ltpk); + String stringUsername = new String(username, StandardCharsets.UTF_8); + LOGGER.trace("Creating initial user {}", stringUsername); + authInfo.createUser(authInfo.getMac() + stringUsername, ltpk, true); return createResponse(); } diff --git a/src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6Routines.java b/src/main/java/io/github/hapjava/server/impl/pairing/HomekitSRP6Routines.java similarity index 94% rename from src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6Routines.java rename to src/main/java/io/github/hapjava/server/impl/pairing/HomekitSRP6Routines.java index d21adfe8b..44417a91f 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6Routines.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/HomekitSRP6Routines.java @@ -1,11 +1,11 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import java.math.BigInteger; import java.security.SecureRandom; /** * This class is modified from the nimbus SRP library to provide methods that are compatible with - * some pecularities of Homekit. Namely, the need for a 3072 bit private value + * some pecularities of HomeKit. Namely, the need for a 3072 bit private value * * @author Vladimir Dzhuvinov */ diff --git a/src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6ServerSession.java b/src/main/java/io/github/hapjava/server/impl/pairing/HomekitSRP6ServerSession.java similarity index 99% rename from src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6ServerSession.java rename to src/main/java/io/github/hapjava/server/impl/pairing/HomekitSRP6ServerSession.java index a459a5c54..3841d9fb7 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6ServerSession.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/HomekitSRP6ServerSession.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import com.nimbusds.srp6.SRP6ClientEvidenceContext; import com.nimbusds.srp6.SRP6CryptoParams; @@ -11,7 +11,7 @@ /** * This is a slightly modified version of the SRP6ServerSession class included with nimbus. The only - * change made for homekit compatability is a change to the size of the b key. Homekit pairing fails + * change made for homekit compatability is a change to the size of the b key. HomeKit pairing fails * if b is not 3072 bytes. * *

Stateful server-side Secure Remote Password (SRP-6a) authentication session. Handles the diff --git a/src/main/java/io/github/hapjava/impl/pairing/MessageType.java b/src/main/java/io/github/hapjava/server/impl/pairing/MessageType.java similarity index 66% rename from src/main/java/io/github/hapjava/impl/pairing/MessageType.java rename to src/main/java/io/github/hapjava/server/impl/pairing/MessageType.java index 2750264a3..84991d130 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/MessageType.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/MessageType.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; public enum MessageType { METHOD(0), @@ -9,7 +9,12 @@ public enum MessageType { ENCRYPTED_DATA(5), STATE(6), ERROR(7), - SIGNATURE(10); + SIGNATURE(0x0a), + PERMISSIONS(0x0b), + FRAGMENT_DATA(0x0c), + FRAGMENT_LAST(0x0d), + FLAGS(0x13), + SEPARATOR(0xff); private final short key; diff --git a/src/main/java/io/github/hapjava/server/impl/pairing/PairSetupManager.java b/src/main/java/io/github/hapjava/server/impl/pairing/PairSetupManager.java new file mode 100644 index 000000000..05b37b8ab --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/pairing/PairSetupManager.java @@ -0,0 +1,66 @@ +package io.github.hapjava.server.impl.pairing; + +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.responses.NotFoundResponse; +import io.github.hapjava.server.impl.responses.UnauthorizedResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PairSetupManager { + + private static final Logger logger = LoggerFactory.getLogger(PairSetupManager.class); + + private final HomekitAuthInfo authInfo; + private final HomekitRegistry registry; + + private SrpHandler srpHandler; + + public PairSetupManager(HomekitAuthInfo authInfo, HomekitRegistry registry) { + this.authInfo = authInfo; + this.registry = registry; + } + + public HttpResponse handle(HttpRequest httpRequest) throws Exception { + PairSetupRequest req = PairSetupRequest.of(httpRequest.getBody()); + logger.trace("Handling pair-setup request {}", req); + + if (req.getState() == 1) { + logger.trace("Received SRP Start Request " + registry.getLabel()); + srpHandler = new SrpHandler(authInfo.getPin(), authInfo.getSalt()); + return srpHandler.handle(req); + } else if (req.getState() == 3) { + logger.trace("Receive SRP Verify Request for " + registry.getLabel()); + if (srpHandler == null) { + logger.warn("Received unexpected SRP Verify Request for " + registry.getLabel()); + return new UnauthorizedResponse(); + } else { + try { + return srpHandler.handle(req); + } catch (Exception e) { + srpHandler = null; // You don't get to try again - need a new key + logger.warn("Exception encountered while processing SRP Verify Request", e); + return new UnauthorizedResponse(); + } + } + } else if (req.getState() == 5) { + logger.trace("Received Exchange Request for " + registry.getLabel()); + if (srpHandler == null) { + logger.warn("Received unexpected Exchanged Request for " + registry.getLabel()); + return new UnauthorizedResponse(); + } else { + ExchangeHandler handler = new ExchangeHandler(srpHandler.getK(), authInfo); + try { + return handler.handle(req); + } catch (Exception e) { + logger.warn("Exception while finalizing pairing", e); + return new UnauthorizedResponse(); + } + } + } + + return new NotFoundResponse(); + } +} diff --git a/src/main/java/io/github/hapjava/server/impl/pairing/PairSetupRequest.java b/src/main/java/io/github/hapjava/server/impl/pairing/PairSetupRequest.java new file mode 100755 index 000000000..6fa099be4 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/pairing/PairSetupRequest.java @@ -0,0 +1,139 @@ +package io.github.hapjava.server.impl.pairing; + +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.DecodeResult; +import java.math.BigInteger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +abstract class PairSetupRequest { + private static final Logger logger = LoggerFactory.getLogger(PairSetupRequest.class); + + public static PairSetupRequest of(byte[] content) throws Exception { + DecodeResult d = TypeLengthValueUtils.decode(content); + logger.trace("Decoded pair setup request: {}", d); + short stage = d.getByte(MessageType.STATE); + switch (stage) { + case 1: + return new SRPStartRequest(d); + + case 3: + return new SRPVerifyRequest(d); + + case 5: + return new ExchangeRequest(d); + + default: + throw new Exception("Unknown pair process stage: " + stage); + } + } + + // Raw integer. + // State of the pairing process. 1=M1, 2=M2, etc. + public abstract int getState(); + + public static class SRPStartRequest extends PairSetupRequest { + int flags; + + public SRPStartRequest(DecodeResult d) { + flags = 0; + if (d.hasMessage(MessageType.FLAGS)) { + flags = d.getInt(MessageType.FLAGS); + } + } + + @Override + public int getState() { + return 1; + } + + public String toString() { + return ""; + } + } + + public static class SRPVerifyRequest extends PairSetupRequest { + + private final BigInteger a; + private final BigInteger m1; + + public SRPVerifyRequest(DecodeResult d) { + a = d.getBigInt(MessageType.PUBLIC_KEY); + m1 = d.getBigInt(MessageType.PROOF); + } + + public BigInteger getA() { + return a; + } + + public BigInteger getM1() { + return m1; + } + + @Override + public int getState() { + return 3; + } + + public String toString() { + return ""; + } + } + + static class ExchangeRequest extends PairSetupRequest { + + private final byte[] messageData; + private final byte[] authTagData; + + public ExchangeRequest(DecodeResult d) { + // Get the complete encrypted data field + byte[] encryptedData = d.getBytes(MessageType.ENCRYPTED_DATA); + logger.debug("ExchangeRequest: Total encrypted data length: {}", encryptedData.length); + logger.debug("ExchangeRequest: Raw encrypted data: {}", bytesToHex(encryptedData)); + + // For HomeKit M5, the encrypted data contains ciphertext + 16-byte auth tag + // The auth tag is the LAST 16 bytes + if (encryptedData.length < 16) { + throw new RuntimeException( + "Encrypted data too short, expected at least 16 bytes for auth tag"); + } + + int ciphertextLength = encryptedData.length - 16; + messageData = new byte[ciphertextLength]; + authTagData = new byte[16]; + + // Copy ciphertext (everything except last 16 bytes) + System.arraycopy(encryptedData, 0, messageData, 0, ciphertextLength); + // Copy auth tag (last 16 bytes) + System.arraycopy(encryptedData, ciphertextLength, authTagData, 0, 16); + + logger.debug("ExchangeRequest: Parsed ciphertext length: {}", messageData.length); + logger.debug("ExchangeRequest: Parsed ciphertext: {}", bytesToHex(messageData)); + logger.debug("ExchangeRequest: Parsed auth tag: {}", bytesToHex(authTagData)); + } + + private static String bytesToHex(byte[] bytes) { + StringBuilder result = new StringBuilder(); + for (byte b : bytes) { + result.append(String.format("%02x", b)); + } + return result.toString(); + } + + public byte[] getMessageData() { + return messageData; + } + + public byte[] getAuthTagData() { + return authTagData; + } + + @Override + public int getState() { + return 5; + } + + public String toString() { + return ""; + } + } +} diff --git a/src/main/java/io/github/hapjava/impl/pairing/PairVerificationManager.java b/src/main/java/io/github/hapjava/server/impl/pairing/PairVerifyManager.java similarity index 65% rename from src/main/java/io/github/hapjava/impl/pairing/PairVerificationManager.java rename to src/main/java/io/github/hapjava/server/impl/pairing/PairVerifyManager.java index 4c5546745..4960c6f6a 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/PairVerificationManager.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/PairVerifyManager.java @@ -1,17 +1,19 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import djb.Curve25519; -import io.github.hapjava.HomekitAuthInfo; -import io.github.hapjava.impl.HomekitRegistry; -import io.github.hapjava.impl.crypto.*; -import io.github.hapjava.impl.http.HttpRequest; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.pairing.PairVerificationRequest.Stage1Request; -import io.github.hapjava.impl.pairing.PairVerificationRequest.Stage2Request; -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.DecodeResult; -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.Encoder; -import io.github.hapjava.impl.responses.NotFoundResponse; -import io.github.hapjava.impl.responses.OkResponse; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.crypto.ChachaDecoder; +import io.github.hapjava.server.impl.crypto.ChachaEncoder; +import io.github.hapjava.server.impl.crypto.EdsaSigner; +import io.github.hapjava.server.impl.crypto.EdsaVerifier; +import io.github.hapjava.server.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.pairing.PairVerifyRequest.VerifyFinishRequest; +import io.github.hapjava.server.impl.pairing.PairVerifyRequest.VerifyStartRequest; +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.DecodeResult; +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.Encoder; +import io.github.hapjava.server.impl.responses.NotFoundResponse; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import org.bouncycastle.crypto.digests.SHA512Digest; @@ -20,9 +22,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class PairVerificationManager { +public class PairVerifyManager { - private static final Logger logger = LoggerFactory.getLogger(PairVerificationManager.class); + private static final Logger logger = LoggerFactory.getLogger(PairVerifyManager.class); private static volatile SecureRandom secureRandom; private final HomekitAuthInfo authInfo; @@ -33,27 +35,27 @@ public class PairVerificationManager { private byte[] publicKey; private byte[] sharedSecret; - public PairVerificationManager(HomekitAuthInfo authInfo, HomekitRegistry registry) { + public PairVerifyManager(HomekitAuthInfo authInfo, HomekitRegistry registry) { this.authInfo = authInfo; this.registry = registry; } public HttpResponse handle(HttpRequest rawRequest) throws Exception { - PairVerificationRequest request = PairVerificationRequest.of(rawRequest.getBody()); - switch (request.getStage()) { - case ONE: - return stage1((Stage1Request) request); + PairVerifyRequest request = PairVerifyRequest.of(rawRequest.getBody()); + switch (request.getState()) { + case 1: + return handleVerifyStartRequest((VerifyStartRequest) request); - case TWO: - return stage2((Stage2Request) request); + case 3: + return handleVerifyFinishRequest((VerifyFinishRequest) request); default: return new NotFoundResponse(); } } - private HttpResponse stage1(Stage1Request request) throws Exception { - logger.debug("Starting pair verification for " + registry.getLabel()); + private HttpResponse handleVerifyStartRequest(VerifyStartRequest request) throws Exception { + logger.trace("Starting pair verification for " + registry.getLabel()); clientPublicKey = request.getClientPublicKey(); publicKey = new byte[32]; byte[] privateKey = new byte[32]; @@ -93,7 +95,7 @@ private HttpResponse stage1(Stage1Request request) throws Exception { return new PairingResponse(encoder.toByteArray()); } - private HttpResponse stage2(Stage2Request request) throws Exception { + private HttpResponse handleVerifyFinishRequest(VerifyFinishRequest request) throws Exception { ChachaDecoder chacha = new ChachaDecoder(hkdfKey, "PV-Msg03".getBytes(StandardCharsets.UTF_8)); byte[] plaintext = chacha.decodeCiphertext(request.getAuthTagData(), request.getMessageData()); @@ -103,25 +105,25 @@ private HttpResponse stage2(Stage2Request request) throws Exception { byte[] material = ByteUtils.joinBytes(clientPublicKey, clientUsername, publicKey); - byte[] clientLtpk = - authInfo.getUserPublicKey( - authInfo.getMac() + new String(clientUsername, StandardCharsets.UTF_8)); + String username = new String(clientUsername, StandardCharsets.UTF_8); + byte[] clientLtpk = authInfo.getUserPublicKey(authInfo.getMac() + username); if (clientLtpk == null) { - throw new Exception("Unknown user: " + new String(clientUsername, StandardCharsets.UTF_8)); + logger.warn("Unknown user: {}", username); + return new PairingResponse(4, ErrorCode.AUTHENTICATION); } Encoder encoder = TypeLengthValueUtils.getEncoder(); if (new EdsaVerifier(clientLtpk).verify(material, clientSignature)) { encoder.add(MessageType.STATE, (short) 4); - logger.debug("Completed pair verification for " + registry.getLabel()); + logger.trace("Completed pair verification for " + registry.getLabel()); return new UpgradeResponse( encoder.toByteArray(), createKey("Control-Write-Encryption-Key"), - createKey("Control-Read-Encryption-Key")); + createKey("Control-Read-Encryption-Key"), + username); } else { - encoder.add(MessageType.ERROR, (short) 4); logger.warn("Invalid signature. Could not pair " + registry.getLabel()); - return new OkResponse(encoder.toByteArray()); + return new PairingResponse(4, ErrorCode.AUTHENTICATION); } } @@ -139,7 +141,7 @@ private byte[] createKey(String info) { private static SecureRandom getSecureRandom() { if (secureRandom == null) { - synchronized (PairVerificationManager.class) { + synchronized (PairVerifyManager.class) { if (secureRandom == null) { secureRandom = new SecureRandom(); } diff --git a/src/main/java/io/github/hapjava/impl/pairing/PairVerificationRequest.java b/src/main/java/io/github/hapjava/server/impl/pairing/PairVerifyRequest.java similarity index 54% rename from src/main/java/io/github/hapjava/impl/pairing/PairVerificationRequest.java rename to src/main/java/io/github/hapjava/server/impl/pairing/PairVerifyRequest.java index 1d4f8db4b..7cf31585b 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/PairVerificationRequest.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/PairVerifyRequest.java @@ -1,34 +1,33 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.DecodeResult; +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.DecodeResult; -abstract class PairVerificationRequest { +abstract class PairVerifyRequest { - private static final short VALUE_STAGE_1 = 1; - private static final short VALUE_STAGE_2 = 3; - - static PairVerificationRequest of(byte[] content) throws Exception { + static PairVerifyRequest of(byte[] content) throws Exception { DecodeResult d = TypeLengthValueUtils.decode(content); short stage = d.getByte(MessageType.STATE); switch (stage) { - case VALUE_STAGE_1: - return new Stage1Request(d); + case 1: + return new VerifyStartRequest(d); - case VALUE_STAGE_2: - return new Stage2Request(d); + case 3: + return new VerifyFinishRequest(d); default: throw new Exception("Unknown pair process stage: " + stage); } } - abstract Stage getStage(); + // Raw integer. + // State of the pairing process. 1=M1, 2=M2, etc. + abstract int getState(); - static class Stage1Request extends PairVerificationRequest { + static class VerifyStartRequest extends PairVerifyRequest { private final byte[] clientPublicKey; - public Stage1Request(DecodeResult d) { + public VerifyStartRequest(DecodeResult d) { clientPublicKey = d.getBytes(MessageType.PUBLIC_KEY); } @@ -37,17 +36,17 @@ public byte[] getClientPublicKey() { } @Override - Stage getStage() { - return Stage.ONE; + int getState() { + return 1; } } - static class Stage2Request extends PairVerificationRequest { + static class VerifyFinishRequest extends PairVerifyRequest { private final byte[] messageData; private final byte[] authTagData; - public Stage2Request(DecodeResult d) { + public VerifyFinishRequest(DecodeResult d) { messageData = new byte[d.getLength(MessageType.ENCRYPTED_DATA) - 16]; authTagData = new byte[16]; d.getBytes(MessageType.ENCRYPTED_DATA, messageData, 0); @@ -63,8 +62,8 @@ public byte[] getAuthTagData() { } @Override - public Stage getStage() { - return Stage.TWO; + public int getState() { + return 3; } } } diff --git a/src/main/java/io/github/hapjava/server/impl/pairing/PairingMethod.java b/src/main/java/io/github/hapjava/server/impl/pairing/PairingMethod.java new file mode 100644 index 000000000..07decf02d --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/pairing/PairingMethod.java @@ -0,0 +1,24 @@ +package io.github.hapjava.server.impl.pairing; + +public enum PairingMethod { + PAIR_SETUP(0), + PAIR_SETUP_WITH_AUTH(1), + PAIR_VERIFY(2), + ADD_PAIRING(3), + REMOVE_PAIRING(4), + LIST_PAIRINGS(5); + + private final byte value; + + PairingMethod(byte value) { + this.value = value; + } + + PairingMethod(int value) { + this.value = (byte) value; + } + + public byte getValue() { + return value; + } +} diff --git a/src/main/java/io/github/hapjava/server/impl/pairing/PairingResponse.java b/src/main/java/io/github/hapjava/server/impl/pairing/PairingResponse.java new file mode 100644 index 000000000..defc5798f --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/pairing/PairingResponse.java @@ -0,0 +1,49 @@ +package io.github.hapjava.server.impl.pairing; + +import io.github.hapjava.server.impl.responses.OkResponse; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +class PairingResponse extends OkResponse { + + private static final Map headers = + Collections.unmodifiableMap( + new HashMap() { + private static final long serialVersionUID = 1L; + + { + put("Content-type", "application/pairing+tlv8"); + } + }); + + public PairingResponse(byte[] body) { + super(body); + } + + public PairingResponse(int state) { + this(encodeSuccess(state)); + } + + public PairingResponse(int state, ErrorCode errorCode) { + this(encodeError(state, errorCode)); + } + + private static byte[] encodeSuccess(int state) { + TypeLengthValueUtils.Encoder encoder = TypeLengthValueUtils.getEncoder(); + encoder.add(MessageType.STATE, (byte) state); + return encoder.toByteArray(); + } + + private static byte[] encodeError(int state, ErrorCode errorCode) { + TypeLengthValueUtils.Encoder encoder = TypeLengthValueUtils.getEncoder(); + encoder.add(MessageType.STATE, (byte) state); + encoder.add(MessageType.ERROR, (byte) errorCode.getKey()); + return encoder.toByteArray(); + } + + @Override + public Map getHeaders() { + return headers; + } +} diff --git a/src/main/java/io/github/hapjava/server/impl/pairing/PairingsManager.java b/src/main/java/io/github/hapjava/server/impl/pairing/PairingsManager.java new file mode 100644 index 000000000..11eb4a709 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/pairing/PairingsManager.java @@ -0,0 +1,77 @@ +package io.github.hapjava.server.impl.pairing; + +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser; +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.DecodeResult; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.Iterator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PairingsManager { + + private final HomekitAuthInfo authInfo; + private final JmdnsHomekitAdvertiser advertiser; + + private static final Logger LOGGER = LoggerFactory.getLogger(PairingsManager.class); + + public PairingsManager(HomekitAuthInfo authInfo, JmdnsHomekitAdvertiser advertiser) { + this.authInfo = authInfo; + this.advertiser = advertiser; + } + + public HttpResponse handle(HttpRequest request) throws IOException { + DecodeResult d = TypeLengthValueUtils.decode(request.getBody()); + + int method = d.getByte(MessageType.METHOD); + + if (method == PairingMethod.ADD_PAIRING.getValue()) { + byte[] username = d.getBytes(MessageType.USERNAME); + byte[] ltpk = d.getBytes(MessageType.PUBLIC_KEY); + byte permissions = d.getByte(MessageType.PERMISSIONS); + authInfo.createUser( + authInfo.getMac() + new String(username, StandardCharsets.UTF_8), ltpk, permissions == 1); + } else if (method == PairingMethod.REMOVE_PAIRING.getValue()) { + byte[] username = d.getBytes(MessageType.USERNAME); + authInfo.removeUser(authInfo.getMac() + new String(username, StandardCharsets.UTF_8)); + if (!authInfo.hasUser()) { + advertiser.setDiscoverable(true); + } + } else if (method == PairingMethod.LIST_PAIRINGS.getValue()) { + TypeLengthValueUtils.Encoder e = TypeLengthValueUtils.getEncoder(); + + Collection usernames = authInfo.listUsers(); + boolean first = true; + Iterator iterator = usernames.iterator(); + String mac = authInfo.getMac(); + + while (iterator.hasNext()) { + String username = iterator.next(); + if (first) { + e.add(MessageType.STATE, (byte) 2); + first = false; + } else { + e.add(MessageType.SEPARATOR); + } + byte[] publicKey = authInfo.getUserPublicKey(username); + boolean isAdmin = authInfo.userIsAdmin(username); + if (username.startsWith(mac)) { + username = username.substring(mac.length()); + } + e.add(MessageType.USERNAME, username); + e.add(MessageType.PUBLIC_KEY, publicKey); + e.add(MessageType.PERMISSIONS, (short) (isAdmin ? 1 : 0)); + } + + return new PairingResponse(e.toByteArray()); + } else { + throw new RuntimeException("Unrecognized method: " + method); + } + + return new PairingResponse(2); + } +} diff --git a/src/main/java/io/github/hapjava/impl/pairing/ServerEvidenceRoutineImpl.java b/src/main/java/io/github/hapjava/server/impl/pairing/ServerEvidenceRoutineImpl.java similarity index 95% rename from src/main/java/io/github/hapjava/impl/pairing/ServerEvidenceRoutineImpl.java rename to src/main/java/io/github/hapjava/server/impl/pairing/ServerEvidenceRoutineImpl.java index ca61f8ed4..7cf7b3164 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/ServerEvidenceRoutineImpl.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/ServerEvidenceRoutineImpl.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import com.nimbusds.srp6.SRP6CryptoParams; import com.nimbusds.srp6.SRP6ServerEvidenceContext; diff --git a/src/main/java/io/github/hapjava/impl/pairing/SrpHandler.java b/src/main/java/io/github/hapjava/server/impl/pairing/SrpHandler.java similarity index 79% rename from src/main/java/io/github/hapjava/impl/pairing/SrpHandler.java rename to src/main/java/io/github/hapjava/server/impl/pairing/SrpHandler.java index 0e70f6f86..5c1c23353 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/SrpHandler.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/SrpHandler.java @@ -1,12 +1,12 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import com.nimbusds.srp6.*; -import io.github.hapjava.impl.http.HttpResponse; -import io.github.hapjava.impl.pairing.HomekitSRP6ServerSession.State; -import io.github.hapjava.impl.pairing.PairSetupRequest.Stage2Request; -import io.github.hapjava.impl.pairing.TypeLengthValueUtils.Encoder; -import io.github.hapjava.impl.responses.ConflictResponse; -import io.github.hapjava.impl.responses.NotFoundResponse; +import io.github.hapjava.server.impl.http.HttpResponse; +import io.github.hapjava.server.impl.pairing.HomekitSRP6ServerSession.State; +import io.github.hapjava.server.impl.pairing.PairSetupRequest.SRPVerifyRequest; +import io.github.hapjava.server.impl.pairing.TypeLengthValueUtils.Encoder; +import io.github.hapjava.server.impl.responses.ConflictResponse; +import io.github.hapjava.server.impl.responses.NotFoundResponse; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Arrays; @@ -39,21 +39,21 @@ public SrpHandler(String pin, BigInteger salt) { } public HttpResponse handle(PairSetupRequest request) throws Exception { - switch (request.getStage()) { - case ONE: - return step1(); + switch (request.getState()) { + case 1: + return handleSrpStartRequest(); - case TWO: - return step2((Stage2Request) request); + case 3: + return handleSrpVerifyRequest((SRPVerifyRequest) request); default: return new NotFoundResponse(); } } - private HttpResponse step1() throws Exception { + private HttpResponse handleSrpStartRequest() throws Exception { if (session.getState() != State.INIT) { - logger.error("Session is not in state INIT when receiving step1"); + logger.warn("Session is not in state INIT when receiving step1"); return new ConflictResponse(); } @@ -68,9 +68,9 @@ private HttpResponse step1() throws Exception { return new PairingResponse(encoder.toByteArray()); } - private HttpResponse step2(Stage2Request request) throws Exception { + private HttpResponse handleSrpVerifyRequest(SRPVerifyRequest request) throws Exception { if (session.getState() != State.STEP_1) { - logger.error("Session is not in state Stage 1 when receiving step2"); + logger.warn("Session is not in state Stage 1 when receiving step2"); return new ConflictResponse(); } BigInteger m2 = session.step2(request.getA(), request.getM1()); diff --git a/src/main/java/io/github/hapjava/impl/pairing/TypeLengthValueUtils.java b/src/main/java/io/github/hapjava/server/impl/pairing/TypeLengthValueUtils.java similarity index 78% rename from src/main/java/io/github/hapjava/impl/pairing/TypeLengthValueUtils.java rename to src/main/java/io/github/hapjava/server/impl/pairing/TypeLengthValueUtils.java index 2f03d0a0b..cbd76f118 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/TypeLengthValueUtils.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/TypeLengthValueUtils.java @@ -1,10 +1,12 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -37,6 +39,11 @@ private Encoder() { baos = new ByteArrayOutputStream(); } + public void add(MessageType type) { + baos.write(type.getKey()); + baos.write(0); + } + public void add(MessageType type, BigInteger i) throws IOException { add(type, ByteUtils.toByteArray(i)); } @@ -58,6 +65,10 @@ public void add(MessageType type, byte[] bytes) throws IOException { } } + public void add(MessageType type, String string) throws IOException { + add(type, string.getBytes(StandardCharsets.UTF_8)); + } + public byte[] toByteArray() { return baos.toByteArray(); } @@ -68,10 +79,23 @@ public static final class DecodeResult { private DecodeResult() {} + public String toString() { + return result.toString(); + } + + public boolean hasMessage(MessageType type) { + return result.containsKey(type.getKey()); + } + public byte getByte(MessageType type) { return result.get(type.getKey())[0]; } + public int getInt(MessageType type) { + ByteBuffer wrapped = ByteBuffer.wrap(result.get(type.getKey())); + return wrapped.getInt(); + } + public BigInteger getBigInt(MessageType type) { return new BigInteger(1, result.get(type.getKey())); } diff --git a/src/main/java/io/github/hapjava/impl/pairing/UpgradeResponse.java b/src/main/java/io/github/hapjava/server/impl/pairing/UpgradeResponse.java similarity index 64% rename from src/main/java/io/github/hapjava/impl/pairing/UpgradeResponse.java rename to src/main/java/io/github/hapjava/server/impl/pairing/UpgradeResponse.java index 9d4003729..121fc7fd8 100644 --- a/src/main/java/io/github/hapjava/impl/pairing/UpgradeResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/pairing/UpgradeResponse.java @@ -1,4 +1,4 @@ -package io.github.hapjava.impl.pairing; +package io.github.hapjava.server.impl.pairing; import java.nio.ByteBuffer; @@ -6,11 +6,13 @@ public class UpgradeResponse extends PairingResponse { private final byte[] readKey; private final byte[] writeKey; + private final String username; - UpgradeResponse(byte[] body, byte[] readKey, byte[] writeKey) { + UpgradeResponse(byte[] body, byte[] readKey, byte[] writeKey, String username) { super(body); this.readKey = readKey; this.writeKey = writeKey; + this.username = username; } @Override @@ -25,4 +27,8 @@ public ByteBuffer getReadKey() { public ByteBuffer getWriteKey() { return ByteBuffer.wrap(writeKey); } + + public String getUsername() { + return username; + } } diff --git a/src/main/java/io/github/hapjava/impl/responses/ConflictResponse.java b/src/main/java/io/github/hapjava/server/impl/responses/ConflictResponse.java similarity index 54% rename from src/main/java/io/github/hapjava/impl/responses/ConflictResponse.java rename to src/main/java/io/github/hapjava/server/impl/responses/ConflictResponse.java index 203b1a676..017fee857 100644 --- a/src/main/java/io/github/hapjava/impl/responses/ConflictResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/responses/ConflictResponse.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.responses; +package io.github.hapjava.server.impl.responses; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.http.HttpResponse; public class ConflictResponse implements HttpResponse { diff --git a/src/main/java/io/github/hapjava/impl/responses/InternalServerErrorResponse.java b/src/main/java/io/github/hapjava/server/impl/responses/InternalServerErrorResponse.java similarity index 82% rename from src/main/java/io/github/hapjava/impl/responses/InternalServerErrorResponse.java rename to src/main/java/io/github/hapjava/server/impl/responses/InternalServerErrorResponse.java index 66fe5ec14..6be78e75a 100644 --- a/src/main/java/io/github/hapjava/impl/responses/InternalServerErrorResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/responses/InternalServerErrorResponse.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.responses; +package io.github.hapjava.server.impl.responses; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.http.HttpResponse; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; diff --git a/src/main/java/io/github/hapjava/impl/responses/NotFoundResponse.java b/src/main/java/io/github/hapjava/server/impl/responses/NotFoundResponse.java similarity index 54% rename from src/main/java/io/github/hapjava/impl/responses/NotFoundResponse.java rename to src/main/java/io/github/hapjava/server/impl/responses/NotFoundResponse.java index 18ab53d74..aca74ad9d 100644 --- a/src/main/java/io/github/hapjava/impl/responses/NotFoundResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/responses/NotFoundResponse.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.responses; +package io.github.hapjava.server.impl.responses; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.http.HttpResponse; public class NotFoundResponse implements HttpResponse { diff --git a/src/main/java/io/github/hapjava/impl/responses/OkResponse.java b/src/main/java/io/github/hapjava/server/impl/responses/OkResponse.java similarity index 75% rename from src/main/java/io/github/hapjava/impl/responses/OkResponse.java rename to src/main/java/io/github/hapjava/server/impl/responses/OkResponse.java index a48e5cee8..b2e62fe76 100644 --- a/src/main/java/io/github/hapjava/impl/responses/OkResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/responses/OkResponse.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.responses; +package io.github.hapjava.server.impl.responses; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.http.HttpResponse; import java.nio.ByteBuffer; public class OkResponse implements HttpResponse { diff --git a/src/main/java/io/github/hapjava/impl/responses/UnauthorizedResponse.java b/src/main/java/io/github/hapjava/server/impl/responses/UnauthorizedResponse.java similarity index 54% rename from src/main/java/io/github/hapjava/impl/responses/UnauthorizedResponse.java rename to src/main/java/io/github/hapjava/server/impl/responses/UnauthorizedResponse.java index 19656ee8d..c40a03f08 100644 --- a/src/main/java/io/github/hapjava/impl/responses/UnauthorizedResponse.java +++ b/src/main/java/io/github/hapjava/server/impl/responses/UnauthorizedResponse.java @@ -1,6 +1,6 @@ -package io.github.hapjava.impl.responses; +package io.github.hapjava.server.impl.responses; -import io.github.hapjava.impl.http.HttpResponse; +import io.github.hapjava.server.impl.http.HttpResponse; public class UnauthorizedResponse implements HttpResponse { diff --git a/src/main/java/io/github/hapjava/Service.java b/src/main/java/io/github/hapjava/services/Service.java similarity index 72% rename from src/main/java/io/github/hapjava/Service.java rename to src/main/java/io/github/hapjava/services/Service.java index 45be2a1c6..303cc5463 100644 --- a/src/main/java/io/github/hapjava/Service.java +++ b/src/main/java/io/github/hapjava/services/Service.java @@ -1,4 +1,4 @@ -package io.github.hapjava; +package io.github.hapjava.services; import io.github.hapjava.characteristics.Characteristic; import java.util.List; @@ -12,7 +12,7 @@ public interface Service { /** * Characteristics are the variables offered for reading, updating, and eventing by the Service - * over the Homekit protocol. + * over the HomeKit protocol. * *

It is important to maintain the order of this list and not change its contents between * invocations, or a pairing error will result. @@ -29,4 +29,18 @@ public interface Service { * ########-####-####-####-############. */ String getType(); + + /** + * List of all the services to which the service links + * + * @return the list of linked services. + */ + List getLinkedServices(); + + /** + * Add linked services + * + * @param service linked service + */ + void addLinkedService(Service service); } diff --git a/src/main/java/io/github/hapjava/services/impl/AbstractServiceImpl.java b/src/main/java/io/github/hapjava/services/impl/AbstractServiceImpl.java new file mode 100644 index 000000000..4dfd9f5f6 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/AbstractServiceImpl.java @@ -0,0 +1,45 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.services.Service; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +abstract class AbstractServiceImpl implements Service { + private final String type; + private final List characteristics = new LinkedList<>(); + private final List linkedServices = new LinkedList<>(); + private static final Logger logger = LoggerFactory.getLogger(AbstractServiceImpl.class); + + /** @param type unique UUID of the service according to HAP specification. */ + public AbstractServiceImpl(String type) { + this.type = type; + } + + @Override + public List getCharacteristics() { + return Collections.unmodifiableList(characteristics); + } + + @Override + public String getType() { + return type; + } + + @Override + public List getLinkedServices() { + return Collections.unmodifiableList(linkedServices); + } + + public void addCharacteristic(Characteristic characteristic) { + this.characteristics.add(characteristic); + } + + @Override + public void addLinkedService(Service service) { + this.linkedServices.add(service); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/AccessoryInformationService.java b/src/main/java/io/github/hapjava/services/impl/AccessoryInformationService.java new file mode 100644 index 000000000..1fdb30d2a --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/AccessoryInformationService.java @@ -0,0 +1,70 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.HomekitAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithAccessoryFlags; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHardwareRevision; +import io.github.hapjava.characteristics.impl.accessoryinformation.AccessoryFlagsCharacteristic; +import io.github.hapjava.characteristics.impl.accessoryinformation.FirmwareRevisionCharacteristic; +import io.github.hapjava.characteristics.impl.accessoryinformation.HardwareRevisionCharacteristic; +import io.github.hapjava.characteristics.impl.accessoryinformation.IdentifyCharacteristic; +import io.github.hapjava.characteristics.impl.accessoryinformation.ManufacturerCharacteristic; +import io.github.hapjava.characteristics.impl.accessoryinformation.ModelCharacteristic; +import io.github.hapjava.characteristics.impl.accessoryinformation.SerialNumberCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; + +/** Accessory Information service. */ +public class AccessoryInformationService extends AbstractServiceImpl { + public static final String TYPE = "0000003E-0000-1000-8000-0026BB765291"; + + public AccessoryInformationService( + IdentifyCharacteristic identify, + ManufacturerCharacteristic manufacturer, + ModelCharacteristic model, + NameCharacteristic name, + SerialNumberCharacteristic serialNumber, + FirmwareRevisionCharacteristic firmwareRevision) { + super(TYPE); + addCharacteristic(identify); + addCharacteristic(manufacturer); + addCharacteristic(model); + addCharacteristic(name); + addCharacteristic(serialNumber); + addCharacteristic(firmwareRevision); + } + + public AccessoryInformationService(HomekitAccessory accessory) { + this( + new IdentifyCharacteristic( + value -> { + if (value) { + accessory.identify(); + } + }), + new ManufacturerCharacteristic(accessory::getManufacturer), + new ModelCharacteristic(accessory::getModel), + new NameCharacteristic(accessory::getName), + new SerialNumberCharacteristic(accessory::getSerialNumber), + new FirmwareRevisionCharacteristic(accessory::getFirmwareRevision)); + + if (accessory instanceof AccessoryWithHardwareRevision) { + addOptionalCharacteristic( + new HardwareRevisionCharacteristic( + ((AccessoryWithHardwareRevision) accessory)::getHardwareRevision)); + } + if (accessory instanceof AccessoryWithAccessoryFlags) { + addOptionalCharacteristic( + new AccessoryFlagsCharacteristic( + ((AccessoryWithAccessoryFlags) accessory)::getAccessoryFlags, + ((AccessoryWithAccessoryFlags) accessory)::subscribeAccessoryFlags, + ((AccessoryWithAccessoryFlags) accessory)::unsubscribeAccessoryFlags)); + } + } + + public void addOptionalCharacteristic(HardwareRevisionCharacteristic hardwareRevision) { + addCharacteristic(hardwareRevision); + } + + public void addOptionalCharacteristic(AccessoryFlagsCharacteristic accessoryFlagsCharacteristic) { + addCharacteristic(accessoryFlagsCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/AirPurifierService.java b/src/main/java/io/github/hapjava/services/impl/AirPurifierService.java new file mode 100644 index 000000000..4918eab81 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/AirPurifierService.java @@ -0,0 +1,90 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.AirPurifierAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPhysicalControlsLock; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRotationSpeed; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithSwingMode; +import io.github.hapjava.characteristics.impl.airpurifier.CurrentAirPurifierCharacteristic; +import io.github.hapjava.characteristics.impl.airpurifier.TargetAirPurifierStateCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.fan.LockPhysicalControlsCharacteristic; +import io.github.hapjava.characteristics.impl.fan.RotationSpeedCharacteristic; +import io.github.hapjava.characteristics.impl.fan.SwingModeCharacteristic; + +/** This service describes an air purifier. */ +public class AirPurifierService extends AbstractServiceImpl { + + public AirPurifierService( + ActiveCharacteristic active, + CurrentAirPurifierCharacteristic currentState, + TargetAirPurifierStateCharacteristic targetState) { + super("000000BB-0000-1000-8000-0026BB765291"); + addCharacteristic(active); + addCharacteristic(currentState); + addCharacteristic(targetState); + } + + public AirPurifierService(AirPurifierAccessory accessory) { + this( + new ActiveCharacteristic( + () -> accessory.isActive().thenApply(s -> s ? ActiveEnum.ACTIVE : ActiveEnum.INACTIVE), + (v) -> accessory.setActive(v == ActiveEnum.ACTIVE), + accessory::subscribeActive, + accessory::unsubscribeActive), + new CurrentAirPurifierCharacteristic( + accessory::getCurrentState, + accessory::subscribeCurrentState, + accessory::unsubscribeCurrentState), + new TargetAirPurifierStateCharacteristic( + accessory::getTargetState, + accessory::setTargetState, + accessory::subscribeCurrentState, + accessory::unsubscribeCurrentState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithSwingMode) { + addOptionalCharacteristic( + new SwingModeCharacteristic( + ((AccessoryWithSwingMode) accessory)::getSwingMode, + ((AccessoryWithSwingMode) accessory)::setSwingMode, + ((AccessoryWithSwingMode) accessory)::subscribeSwingMode, + ((AccessoryWithSwingMode) accessory)::unsubscribeSwingMode)); + } + if (accessory instanceof AccessoryWithRotationSpeed) { + addOptionalCharacteristic( + new RotationSpeedCharacteristic( + ((AccessoryWithRotationSpeed) accessory)::getRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::setRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::subscribeRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::unsubscribeRotationSpeed)); + } + if (accessory instanceof AccessoryWithPhysicalControlsLock) { + addOptionalCharacteristic( + new LockPhysicalControlsCharacteristic( + ((AccessoryWithPhysicalControlsLock) accessory)::getLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::setLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::subscribeLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::unsubscribeLockControls)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(SwingModeCharacteristic mode) { + addCharacteristic(mode); + } + + public void addOptionalCharacteristic(RotationSpeedCharacteristic speed) { + addCharacteristic(speed); + } + + public void addOptionalCharacteristic(LockPhysicalControlsCharacteristic lock) { + addCharacteristic(lock); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/AirQualityService.java b/src/main/java/io/github/hapjava/services/impl/AirQualityService.java new file mode 100644 index 000000000..4aa74c88f --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/AirQualityService.java @@ -0,0 +1,178 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.AirQualityAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithNitrogenDioxideDensity; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithOzoneDensity; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPM10Density; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPM25Density; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithSulphurDioxideDensity; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVOCDensity; +import io.github.hapjava.characteristics.impl.airquality.AirQualityCharacteristic; +import io.github.hapjava.characteristics.impl.airquality.NitrogenDioxideDensityCharacteristic; +import io.github.hapjava.characteristics.impl.airquality.OzoneDensityCharacteristic; +import io.github.hapjava.characteristics.impl.airquality.PM10DensityCharacteristic; +import io.github.hapjava.characteristics.impl.airquality.PM25DensityCharacteristic; +import io.github.hapjava.characteristics.impl.airquality.SulphurDioxideDensityCharacteristic; +import io.github.hapjava.characteristics.impl.airquality.VOCDensityCharacteristic; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; + +/** This service describes air quality sensor. */ +public class AirQualityService extends AbstractServiceImpl { + + public AirQualityService(AirQualityCharacteristic airQuality) { + super("0000008D-0000-1000-8000-0026BB765291"); + addCharacteristic(airQuality); + } + + public AirQualityService(AirQualityAccessory accessory) { + this( + new AirQualityCharacteristic( + accessory::getAirQuality, + accessory::subscribeAirQuality, + accessory::unsubscribeAirQuality)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + + if (accessory instanceof AccessoryWithOzoneDensity) { + addOptionalCharacteristic( + new OzoneDensityCharacteristic( + ((AccessoryWithOzoneDensity) accessory)::getOzoneDensity, + ((AccessoryWithOzoneDensity) accessory)::subscribeOzoneDensity, + ((AccessoryWithOzoneDensity) accessory)::unsubscribeOzoneDensity)); + } + if (accessory instanceof AccessoryWithNitrogenDioxideDensity) { + addOptionalCharacteristic( + new NitrogenDioxideDensityCharacteristic( + ((AccessoryWithNitrogenDioxideDensity) accessory).getMinNitrogenDioxideDensity(), + ((AccessoryWithNitrogenDioxideDensity) accessory).getMaxNitrogenDioxideDensity(), + ((AccessoryWithNitrogenDioxideDensity) accessory).getMinStepNitrogenDioxideDensity(), + ((AccessoryWithNitrogenDioxideDensity) accessory)::getNitrogenDioxideDensity, + ((AccessoryWithNitrogenDioxideDensity) accessory)::subscribeNitrogenDioxideDensity, + ((AccessoryWithNitrogenDioxideDensity) accessory) + ::unsubscribeNitrogenDioxideDensity)); + } + + if (accessory instanceof AccessoryWithSulphurDioxideDensity) { + addOptionalCharacteristic( + new SulphurDioxideDensityCharacteristic( + ((AccessoryWithSulphurDioxideDensity) accessory).getMinSulphurDioxideDensity(), + ((AccessoryWithSulphurDioxideDensity) accessory).getMaxSulphurDioxideDensity(), + ((AccessoryWithSulphurDioxideDensity) accessory).getMinStepSulphurDioxideDensity(), + ((AccessoryWithSulphurDioxideDensity) accessory)::getSulphurDioxideDensity, + ((AccessoryWithSulphurDioxideDensity) accessory)::subscribeSulphurDioxideDensity, + ((AccessoryWithSulphurDioxideDensity) accessory)::unsubscribeSulphurDioxideDensity)); + } + if (accessory instanceof AccessoryWithPM25Density) { + addOptionalCharacteristic( + new PM25DensityCharacteristic( + ((AccessoryWithPM25Density) accessory).getMinPM25Density(), + ((AccessoryWithPM25Density) accessory).getMaxPM25Density(), + ((AccessoryWithPM25Density) accessory).getMinStepPM25Density(), + ((AccessoryWithPM25Density) accessory)::getPM25Density, + ((AccessoryWithPM25Density) accessory)::subscribePM25Density, + ((AccessoryWithPM25Density) accessory)::unsubscribePM25Density)); + } + if (accessory instanceof AccessoryWithPM10Density) { + addOptionalCharacteristic( + new PM10DensityCharacteristic( + ((AccessoryWithPM10Density) accessory).getMinPM10Density(), + ((AccessoryWithPM10Density) accessory).getMaxPM10Density(), + ((AccessoryWithPM10Density) accessory).getMinStepPM10Density(), + ((AccessoryWithPM10Density) accessory)::getPM10Density, + ((AccessoryWithPM10Density) accessory)::subscribePM10Density, + ((AccessoryWithPM10Density) accessory)::unsubscribePM10Density)); + } + if (accessory instanceof AccessoryWithVOCDensity) { + addOptionalCharacteristic( + new VOCDensityCharacteristic( + ((AccessoryWithVOCDensity) accessory).getMinVOCDensity(), + ((AccessoryWithVOCDensity) accessory).getMaxVOCDensity(), + ((AccessoryWithVOCDensity) accessory).getMinStepVOCDensity(), + ((AccessoryWithVOCDensity) accessory)::getVOCDensity, + ((AccessoryWithVOCDensity) accessory)::subscribeVOCDensity, + ((AccessoryWithVOCDensity) accessory)::unsubscribeVOCDensity)); + } + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(OzoneDensityCharacteristic ozoneDensity) { + addCharacteristic(ozoneDensity); + } + + public void addOptionalCharacteristic(NitrogenDioxideDensityCharacteristic nitrogenDensity) { + addCharacteristic(nitrogenDensity); + } + + public void addOptionalCharacteristic(SulphurDioxideDensityCharacteristic sulphuhrDensity) { + addCharacteristic(sulphuhrDensity); + } + + public void addOptionalCharacteristic(PM25DensityCharacteristic pm25Density) { + addCharacteristic(pm25Density); + } + + public void addOptionalCharacteristic(PM10DensityCharacteristic pm10Density) { + addCharacteristic(pm10Density); + } + + public void addOptionalCharacteristic(VOCDensityCharacteristic vocDensity) { + addCharacteristic(vocDensity); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/BasicFanService.java b/src/main/java/io/github/hapjava/services/impl/BasicFanService.java new file mode 100644 index 000000000..9a033dd0c --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/BasicFanService.java @@ -0,0 +1,65 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.BasicFanAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRotationDirection; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRotationSpeed; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.OnCharacteristic; +import io.github.hapjava.characteristics.impl.fan.RotationDirectionCharacteristic; +import io.github.hapjava.characteristics.impl.fan.RotationSpeedCharacteristic; + +/** + * This service describes a fan. + * + *

In the R1 release of the HAP specification, this is simply described as Fan. It is no longer + * present in the R2 release. + */ +public class BasicFanService extends AbstractServiceImpl { + + public BasicFanService(OnCharacteristic on) { + super("00000040-0000-1000-8000-0026BB765291"); + addCharacteristic(on); + } + + public BasicFanService(BasicFanAccessory accessory) { + this( + new OnCharacteristic( + () -> accessory.isOn(), + (v) -> accessory.setOn(v), + accessory::subscribeOn, + accessory::unsubscribeOn)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + + if (accessory instanceof AccessoryWithRotationDirection) { + addOptionalCharacteristic( + new RotationDirectionCharacteristic( + ((AccessoryWithRotationDirection) accessory)::getRotationDirection, + ((AccessoryWithRotationDirection) accessory)::setRotationDirection, + ((AccessoryWithRotationDirection) accessory)::subscribeRotationDirection, + ((AccessoryWithRotationDirection) accessory)::unsubscribeRotationDirection)); + } + if (accessory instanceof AccessoryWithRotationSpeed) { + addOptionalCharacteristic( + new RotationSpeedCharacteristic( + ((AccessoryWithRotationSpeed) accessory)::getRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::setRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::subscribeRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::unsubscribeRotationSpeed)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(RotationDirectionCharacteristic direction) { + addCharacteristic(direction); + } + + public void addOptionalCharacteristic(RotationSpeedCharacteristic speed) { + addCharacteristic(speed); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/BatteryService.java b/src/main/java/io/github/hapjava/services/impl/BatteryService.java new file mode 100644 index 000000000..46259a6e8 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/BatteryService.java @@ -0,0 +1,45 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.BatteryAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.characteristics.impl.battery.BatteryLevelCharacteristic; +import io.github.hapjava.characteristics.impl.battery.ChargingStateCharacteristic; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; + +/** This service describes a battery service. */ +public class BatteryService extends AbstractServiceImpl { + + public BatteryService( + BatteryLevelCharacteristic batteryLevelCharacteristic, + ChargingStateCharacteristic chargingStateCharacteristic, + StatusLowBatteryCharacteristic statusLowBatteryCharacteristic) { + super("00000096-0000-1000-8000-0026BB765291"); + addCharacteristic(batteryLevelCharacteristic); + addCharacteristic(chargingStateCharacteristic); + addCharacteristic(statusLowBatteryCharacteristic); + } + + public BatteryService(BatteryAccessory accessory) { + this( + new BatteryLevelCharacteristic( + accessory::getBatteryLevel, + accessory::subscribeBatteryLevel, + accessory::unsubscribeBatteryLevel), + new ChargingStateCharacteristic( + accessory::getChargingState, + accessory::subscribeBatteryChargingState, + accessory::unsubscribeBatteryChargingState), + new StatusLowBatteryCharacteristic( + accessory::getLowBatteryState, + accessory::subscribeLowBatteryState, + accessory::unsubscribeLowBatteryState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/CarbonDioxideSensorService.java b/src/main/java/io/github/hapjava/services/impl/CarbonDioxideSensorService.java new file mode 100644 index 000000000..b61e91b91 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/CarbonDioxideSensorService.java @@ -0,0 +1,114 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.CarbonDioxideSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCarbonDioxideLevel; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.carbondioxidesensor.CarbonDioxideDetectedCharacteristic; +import io.github.hapjava.characteristics.impl.carbondioxidesensor.CarbonDioxideLevelCharacteristic; +import io.github.hapjava.characteristics.impl.carbondioxidesensor.CarbonDioxidePeakLevelCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; + +/** This service describes a carbon dioxide sensor. */ +public class CarbonDioxideSensorService extends AbstractServiceImpl { + + public CarbonDioxideSensorService(CarbonDioxideDetectedCharacteristic carbonDioxideDetected) { + super("00000097-0000-1000-8000-0026BB765291"); + addCharacteristic(carbonDioxideDetected); + } + + public CarbonDioxideSensorService(CarbonDioxideSensorAccessory accessory) { + this( + new CarbonDioxideDetectedCharacteristic( + accessory::getCarbonDioxideDetectedState, + accessory::subscribeCarbonDioxideDetectedState, + accessory::unsubscribeCarbonDioxideDetectedState)); + + if (accessory instanceof AccessoryWithCarbonDioxideLevel) { + addOptionalCharacteristic( + new CarbonDioxideLevelCharacteristic( + ((AccessoryWithCarbonDioxideLevel) accessory).getMinCarbonDioxideLevel(), + ((AccessoryWithCarbonDioxideLevel) accessory).getMaxCarbonDioxideLevel(), + ((AccessoryWithCarbonDioxideLevel) accessory).getMinStepCarbonDioxideLevel(), + ((AccessoryWithCarbonDioxideLevel) accessory)::getCarbonDioxideLevel, + ((AccessoryWithCarbonDioxideLevel) accessory)::subscribeCarbonDioxideLevel, + ((AccessoryWithCarbonDioxideLevel) accessory)::unsubscribeCarbonDioxideLevel)); + addOptionalCharacteristic( + new CarbonDioxidePeakLevelCharacteristic( + ((AccessoryWithCarbonDioxideLevel) accessory).getMinCarbonDioxidePeakLevel(), + ((AccessoryWithCarbonDioxideLevel) accessory).getMaxCarbonDioxidePeakLevel(), + ((AccessoryWithCarbonDioxideLevel) accessory).getMinStepCarbonDioxidePeakLevel(), + ((AccessoryWithCarbonDioxideLevel) accessory)::getCarbonDioxidePeakLevel, + ((AccessoryWithCarbonDioxideLevel) accessory)::subscribeCarbonDioxidePeakLevel, + ((AccessoryWithCarbonDioxideLevel) accessory)::unsubscribeCarbonDioxidePeakLevel)); + } + + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } + + public void addOptionalCharacteristic(CarbonDioxideLevelCharacteristic carbonDioxideLevel) { + addCharacteristic(carbonDioxideLevel); + } + + public void addOptionalCharacteristic( + CarbonDioxidePeakLevelCharacteristic carbonDioxidePeakLevel) { + addCharacteristic(carbonDioxidePeakLevel); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/CarbonMonoxideSensorService.java b/src/main/java/io/github/hapjava/services/impl/CarbonMonoxideSensorService.java new file mode 100644 index 000000000..11b66c5c4 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/CarbonMonoxideSensorService.java @@ -0,0 +1,108 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.CarbonMonoxideSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCarbonMonoxideLevel; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.carbonmonoxidesensor.CarbonMonoxideDetectedCharacteristic; +import io.github.hapjava.characteristics.impl.carbonmonoxidesensor.CarbonMonoxideLevelCharacteristic; +import io.github.hapjava.characteristics.impl.carbonmonoxidesensor.CarbonMonoxidePeakLevelCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; + +/** This service describes a carbon monoxide sensor. */ +public class CarbonMonoxideSensorService extends AbstractServiceImpl { + + public CarbonMonoxideSensorService(CarbonMonoxideDetectedCharacteristic carbonMonoxideDetected) { + super("0000007F-0000-1000-8000-0026BB765291"); + addCharacteristic(carbonMonoxideDetected); + } + + public CarbonMonoxideSensorService(CarbonMonoxideSensorAccessory accessory) { + this( + new CarbonMonoxideDetectedCharacteristic( + accessory::getCarbonMonoxideDetectedState, + accessory::subscribeCarbonMonoxideDetectedState, + accessory::unsubscribeCarbonMonoxideDetectedState)); + + if (accessory instanceof AccessoryWithCarbonMonoxideLevel) { + addOptionalCharacteristic( + new CarbonMonoxideLevelCharacteristic( + ((AccessoryWithCarbonMonoxideLevel) accessory)::getCarbonMonoxideLevel, + ((AccessoryWithCarbonMonoxideLevel) accessory)::subscribeCarbonMonoxideLevel, + ((AccessoryWithCarbonMonoxideLevel) accessory)::unsubscribeCarbonMonoxideLevel)); + addOptionalCharacteristic( + new CarbonMonoxidePeakLevelCharacteristic( + ((AccessoryWithCarbonMonoxideLevel) accessory)::getCarbonMonoxidePeakLevel, + ((AccessoryWithCarbonMonoxideLevel) accessory)::subscribeCarbonMonoxidePeakLevel, + ((AccessoryWithCarbonMonoxideLevel) accessory)::unsubscribeCarbonMonoxidePeakLevel)); + } + + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } + + public void addOptionalCharacteristic(CarbonMonoxideLevelCharacteristic carbonMonoxideLevel) { + addCharacteristic(carbonMonoxideLevel); + } + + public void addOptionalCharacteristic( + CarbonMonoxidePeakLevelCharacteristic carbonMonoxidePeakLevel) { + addCharacteristic(carbonMonoxidePeakLevel); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/ContactSensorService.java b/src/main/java/io/github/hapjava/services/impl/ContactSensorService.java new file mode 100644 index 000000000..675553697 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/ContactSensorService.java @@ -0,0 +1,83 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.ContactSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.contactsensor.ContactSensorStateCharacteristic; + +/** This service describes a Contact Sensor. */ +public class ContactSensorService extends AbstractServiceImpl { + + public ContactSensorService(ContactSensorStateCharacteristic contactSensorState) { + super("00000080-0000-1000-8000-0026BB765291"); + addCharacteristic(contactSensorState); + } + + public ContactSensorService(ContactSensorAccessory accessory) { + this( + new ContactSensorStateCharacteristic( + accessory::getCurrentState, + accessory::subscribeContactState, + accessory::unsubscribeContactState)); + + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/DoorService.java b/src/main/java/io/github/hapjava/services/impl/DoorService.java new file mode 100644 index 000000000..51f956f5f --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/DoorService.java @@ -0,0 +1,84 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.DoorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHoldPosition; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithMute; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithObstructionDetection; +import io.github.hapjava.characteristics.impl.audio.MuteCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ObstructionDetectedCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.CurrentPositionCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.HoldPositionCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.PositionStateCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.TargetPositionCharacteristic; + +/** This service describes a motorized door. */ +public class DoorService extends AbstractServiceImpl { + + public DoorService( + CurrentPositionCharacteristic currentPositionCharacteristic, + TargetPositionCharacteristic targetPositionCharacteristic, + PositionStateCharacteristic positionStateCharacteristic) { + super("00000081-0000-1000-8000-0026BB765291"); + addCharacteristic(currentPositionCharacteristic); + addCharacteristic(targetPositionCharacteristic); + addCharacteristic(positionStateCharacteristic); + } + + public DoorService(DoorAccessory accessory) { + this( + new CurrentPositionCharacteristic( + accessory::getCurrentPosition, + accessory::subscribeCurrentPosition, + accessory::unsubscribeCurrentPosition), + new TargetPositionCharacteristic( + accessory::getTargetPosition, + accessory::setTargetPosition, + accessory::subscribeTargetPosition, + accessory::unsubscribeTargetPosition), + new PositionStateCharacteristic( + accessory::getPositionState, + accessory::subscribePositionState, + accessory::unsubscribePositionState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithHoldPosition) { + addOptionalCharacteristic( + new HoldPositionCharacteristic(((AccessoryWithHoldPosition) accessory)::setHoldPosition)); + } + if (accessory instanceof AccessoryWithObstructionDetection) { + addOptionalCharacteristic( + new ObstructionDetectedCharacteristic( + ((AccessoryWithObstructionDetection) accessory)::getObstructionDetected, + ((AccessoryWithObstructionDetection) accessory)::subscribeObstructionDetected, + ((AccessoryWithObstructionDetection) accessory)::unsubscribeObstructionDetected)); + } + if (accessory instanceof AccessoryWithMute) { + addOptionalCharacteristic( + new MuteCharacteristic( + ((AccessoryWithMute) accessory)::isMuted, + ((AccessoryWithMute) accessory)::setMute, + ((AccessoryWithMute) accessory)::subscribeMuteState, + ((AccessoryWithMute) accessory)::unsubscribeMuteState)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(HoldPositionCharacteristic holdPositionCharacteristic) { + addCharacteristic(holdPositionCharacteristic); + } + + public void addOptionalCharacteristic( + ObstructionDetectedCharacteristic obstructionDetectedCharacteristic) { + addCharacteristic(obstructionDetectedCharacteristic); + } + + public void addOptionalCharacteristic(MuteCharacteristic muteCharacteristic) { + addCharacteristic(muteCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/DoorbellService.java b/src/main/java/io/github/hapjava/services/impl/DoorbellService.java new file mode 100644 index 000000000..06ee325d4 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/DoorbellService.java @@ -0,0 +1,72 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.DoorbellAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithBrightness; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithMute; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVolume; +import io.github.hapjava.characteristics.impl.audio.MuteCharacteristic; +import io.github.hapjava.characteristics.impl.audio.VolumeCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ProgrammableSwitchEventCharacteristic; +import io.github.hapjava.characteristics.impl.lightbulb.BrightnessCharacteristic; + +/** The Doorbell service describes a doorbell. */ +public class DoorbellService extends AbstractServiceImpl { + + public DoorbellService(ProgrammableSwitchEventCharacteristic switchEvent) { + super("00000121-0000-1000-8000-0026BB765291"); + addCharacteristic(switchEvent); + } + + public DoorbellService(DoorbellAccessory accessory) { + this( + new ProgrammableSwitchEventCharacteristic( + accessory::getSwitchEvent, + accessory::subscribeSwitchEvent, + accessory::unsubscribeSwitchEvent)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithBrightness) { + addOptionalCharacteristic( + new BrightnessCharacteristic( + ((AccessoryWithBrightness) accessory)::getBrightness, + ((AccessoryWithBrightness) accessory)::setBrightness, + ((AccessoryWithBrightness) accessory)::subscribeBrightness, + ((AccessoryWithBrightness) accessory)::unsubscribeBrightness)); + } + if (accessory instanceof AccessoryWithVolume) { + addOptionalCharacteristic( + new VolumeCharacteristic( + ((AccessoryWithVolume) accessory)::getVolume, + ((AccessoryWithVolume) accessory)::setVolume, + ((AccessoryWithVolume) accessory)::subscribeVolume, + ((AccessoryWithVolume) accessory)::unsubscribeVolume)); + } + if (accessory instanceof AccessoryWithMute) { + addOptionalCharacteristic( + new MuteCharacteristic( + ((AccessoryWithMute) accessory)::isMuted, + ((AccessoryWithMute) accessory)::setMute, + ((AccessoryWithMute) accessory)::subscribeMuteState, + ((AccessoryWithMute) accessory)::unsubscribeMuteState)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(BrightnessCharacteristic brightness) { + addCharacteristic(brightness); + } + + public void addOptionalCharacteristic(VolumeCharacteristic volume) { + addCharacteristic(volume); + } + + public void addOptionalCharacteristic(MuteCharacteristic mute) { + addCharacteristic(mute); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/FanService.java b/src/main/java/io/github/hapjava/services/impl/FanService.java new file mode 100644 index 000000000..a8f3a7103 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/FanService.java @@ -0,0 +1,118 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.FanAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithFanState; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPhysicalControlsLock; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRotationDirection; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRotationSpeed; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithSwingMode; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.fan.CurrentFanStateCharacteristic; +import io.github.hapjava.characteristics.impl.fan.LockPhysicalControlsCharacteristic; +import io.github.hapjava.characteristics.impl.fan.RotationDirectionCharacteristic; +import io.github.hapjava.characteristics.impl.fan.RotationSpeedCharacteristic; +import io.github.hapjava.characteristics.impl.fan.SwingModeCharacteristic; +import io.github.hapjava.characteristics.impl.fan.TargetFanStateCharacteristic; + +/** + * This service describes a fan. + * + *

In the R1 release of the HAP specification, this is described as Fan v2. In the R1 release of + * the HAP specification, this is simply described as Fan. + */ +public class FanService extends AbstractServiceImpl { + + public FanService(ActiveCharacteristic active) { + super("000000B7-0000-1000-8000-0026BB765291"); + addCharacteristic(active); + } + + public FanService(FanAccessory accessory) { + this( + new ActiveCharacteristic( + () -> accessory.isActive().thenApply(s -> s ? ActiveEnum.ACTIVE : ActiveEnum.INACTIVE), + (v) -> accessory.setActive(v == ActiveEnum.ACTIVE), + accessory::subscribeActive, + accessory::unsubscribeActive)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + + if (accessory instanceof AccessoryWithFanState) { + addOptionalCharacteristic( + new CurrentFanStateCharacteristic( + ((AccessoryWithFanState) accessory)::getCurrentFanState, + ((AccessoryWithFanState) accessory)::subscribeCurrentFanState, + ((AccessoryWithFanState) accessory)::unsubscribeCurrentFanState)); + addOptionalCharacteristic( + new TargetFanStateCharacteristic( + ((AccessoryWithFanState) accessory)::getTargetFanState, + ((AccessoryWithFanState) accessory)::setTargetFanState, + ((AccessoryWithFanState) accessory)::subscribeTargetFanState, + ((AccessoryWithFanState) accessory)::unsubscribeTargetFanState)); + } + if (accessory instanceof AccessoryWithRotationDirection) { + addOptionalCharacteristic( + new RotationDirectionCharacteristic( + ((AccessoryWithRotationDirection) accessory)::getRotationDirection, + ((AccessoryWithRotationDirection) accessory)::setRotationDirection, + ((AccessoryWithRotationDirection) accessory)::subscribeRotationDirection, + ((AccessoryWithRotationDirection) accessory)::unsubscribeRotationDirection)); + } + if (accessory instanceof AccessoryWithRotationSpeed) { + addOptionalCharacteristic( + new RotationSpeedCharacteristic( + ((AccessoryWithRotationSpeed) accessory)::getRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::setRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::subscribeRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::unsubscribeRotationSpeed)); + } + if (accessory instanceof AccessoryWithSwingMode) { + addOptionalCharacteristic( + new SwingModeCharacteristic( + ((AccessoryWithSwingMode) accessory)::getSwingMode, + ((AccessoryWithSwingMode) accessory)::setSwingMode, + ((AccessoryWithSwingMode) accessory)::subscribeSwingMode, + ((AccessoryWithSwingMode) accessory)::unsubscribeSwingMode)); + } + if (accessory instanceof AccessoryWithPhysicalControlsLock) { + addOptionalCharacteristic( + new LockPhysicalControlsCharacteristic( + ((AccessoryWithPhysicalControlsLock) accessory)::getLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::setLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::subscribeLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::unsubscribeLockControls)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(CurrentFanStateCharacteristic state) { + addCharacteristic(state); + } + + public void addOptionalCharacteristic(TargetFanStateCharacteristic state) { + addCharacteristic(state); + } + + public void addOptionalCharacteristic(RotationDirectionCharacteristic direction) { + addCharacteristic(direction); + } + + public void addOptionalCharacteristic(RotationSpeedCharacteristic speed) { + addCharacteristic(speed); + } + + public void addOptionalCharacteristic(SwingModeCharacteristic mode) { + addCharacteristic(mode); + } + + public void addOptionalCharacteristic(LockPhysicalControlsCharacteristic lock) { + addCharacteristic(lock); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/FaucetService.java b/src/main/java/io/github/hapjava/services/impl/FaucetService.java new file mode 100644 index 000000000..1028fa9b1 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/FaucetService.java @@ -0,0 +1,50 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.FaucetAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; + +/** + * This service describes accessories like faucets or shower heads and must only be included when an + * accessory has either a linked {@link HeaterCoolerService}, single linked {@link ValveService} or + * multiple linked {@link ValveService} (with/without {@link HeaterCoolerService} to describe water + * outlets. This service serves as a top level service for such accessories. + */ +public class FaucetService extends AbstractServiceImpl { + + public FaucetService(ActiveCharacteristic active) { + super("000000D7-0000-1000-8000-0026BB765291"); + addCharacteristic(active); + } + + public FaucetService(FaucetAccessory accessory) { + this( + new ActiveCharacteristic( + () -> accessory.isActive().thenApply(s -> s ? ActiveEnum.ACTIVE : ActiveEnum.INACTIVE), + (v) -> accessory.setActive(v == ActiveEnum.ACTIVE), + accessory::subscribeActive, + accessory::unsubscribeActive)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/FilterMaintenanceService.java b/src/main/java/io/github/hapjava/services/impl/FilterMaintenanceService.java new file mode 100644 index 000000000..10788cdea --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/FilterMaintenanceService.java @@ -0,0 +1,57 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.FilterMaintenanceAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithFilterLifeLevel; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithResetFilterIndication; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.filtermaintenance.FilterChangeIndicationCharacteristic; +import io.github.hapjava.characteristics.impl.filtermaintenance.FilterLifeLevelCharacteristic; +import io.github.hapjava.characteristics.impl.filtermaintenance.ResetFilterIndicationCharacteristic; + +/** This service describes a filter maintenance. */ +public class FilterMaintenanceService extends AbstractServiceImpl { + + public FilterMaintenanceService(FilterChangeIndicationCharacteristic filerChange) { + super("000000BA-0000-1000-8000-0026BB765291"); + addCharacteristic(filerChange); + } + + public FilterMaintenanceService(FilterMaintenanceAccessory accessory) { + this( + new FilterChangeIndicationCharacteristic( + accessory::getFilterChangeIndication, + accessory::subscribeFilterChangeIndication, + accessory::unsubscribeFilterChangeIndication)); + + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + + if (accessory instanceof AccessoryWithFilterLifeLevel) { + addOptionalCharacteristic( + new FilterLifeLevelCharacteristic( + ((AccessoryWithFilterLifeLevel) accessory)::getFilterLifeLevel, + ((AccessoryWithFilterLifeLevel) accessory)::subscribeFilterLifeLevel, + ((AccessoryWithFilterLifeLevel) accessory)::unsubscribeFilterLifeLevel)); + } + + if (accessory instanceof AccessoryWithResetFilterIndication) { + addOptionalCharacteristic( + new ResetFilterIndicationCharacteristic( + ((AccessoryWithResetFilterIndication) accessory)::resetFilterIndication)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(FilterLifeLevelCharacteristic filterLifeLevel) { + addCharacteristic(filterLifeLevel); + } + + public void addOptionalCharacteristic(ResetFilterIndicationCharacteristic resetFilterIndication) { + addCharacteristic(resetFilterIndication); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/GarageDoorOpenerService.java b/src/main/java/io/github/hapjava/services/impl/GarageDoorOpenerService.java new file mode 100644 index 000000000..b90a7e5ee --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/GarageDoorOpenerService.java @@ -0,0 +1,73 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.GarageDoorOpenerAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithLockCurrentState; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithLockTargetState; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ObstructionDetectedCharacteristic; +import io.github.hapjava.characteristics.impl.garagedoor.CurrentDoorStateCharacteristic; +import io.github.hapjava.characteristics.impl.garagedoor.TargetDoorStateCharacteristic; +import io.github.hapjava.characteristics.impl.lock.LockCurrentStateCharacteristic; +import io.github.hapjava.characteristics.impl.lock.LockTargetStateCharacteristic; + +/** This service describes a garage door opener that controls a single door. */ +public class GarageDoorOpenerService extends AbstractServiceImpl { + + public GarageDoorOpenerService( + CurrentDoorStateCharacteristic currentState, + TargetDoorStateCharacteristic targetState, + ObstructionDetectedCharacteristic obstruction) { + super("00000041-0000-1000-8000-0026BB765291"); + addCharacteristic(currentState); + addCharacteristic(targetState); + addCharacteristic(obstruction); + } + + public GarageDoorOpenerService(GarageDoorOpenerAccessory accessory) { + this( + new CurrentDoorStateCharacteristic( + accessory::getCurrentDoorState, + accessory::subscribeCurrentDoorState, + accessory::unsubscribeCurrentDoorState), + new TargetDoorStateCharacteristic( + accessory::getTargetDoorState, + accessory::setTargetDoorState, + accessory::subscribeTargetDoorState, + accessory::unsubscribeTargetDoorState), + new ObstructionDetectedCharacteristic( + accessory::getObstructionDetected, + accessory::subscribeObstructionDetected, + accessory::unsubscribeObstructionDetected)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithLockCurrentState) { + addOptionalCharacteristic( + new LockCurrentStateCharacteristic( + ((AccessoryWithLockCurrentState) accessory)::getLockCurrentState, + ((AccessoryWithLockCurrentState) accessory)::subscribeLockCurrentState, + ((AccessoryWithLockCurrentState) accessory)::unsubscribeLockCurrentState)); + } + if (accessory instanceof AccessoryWithLockTargetState) { + addOptionalCharacteristic( + new LockTargetStateCharacteristic( + ((AccessoryWithLockTargetState) accessory)::getLockTargetState, + ((AccessoryWithLockTargetState) accessory)::setLockTargetState, + ((AccessoryWithLockTargetState) accessory)::subscribeLockTargetState, + ((AccessoryWithLockTargetState) accessory)::unsubscribeLockTargetState)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(LockCurrentStateCharacteristic lockState) { + addCharacteristic(lockState); + } + + public void addOptionalCharacteristic(LockTargetStateCharacteristic lockState) { + addCharacteristic(lockState); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/HAPProtocolInformationService.java b/src/main/java/io/github/hapjava/services/impl/HAPProtocolInformationService.java new file mode 100644 index 000000000..bc49852f5 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/HAPProtocolInformationService.java @@ -0,0 +1,12 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.characteristics.impl.common.VersionCharacteristic; + +/** This service HAP version. */ +public class HAPProtocolInformationService extends AbstractServiceImpl { + + public HAPProtocolInformationService(VersionCharacteristic versionCharacteristic) { + super("000000A2-0000-1000-8000-0026BB765291"); + addCharacteristic(versionCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/HeaterCoolerService.java b/src/main/java/io/github/hapjava/services/impl/HeaterCoolerService.java new file mode 100644 index 000000000..5204ae006 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/HeaterCoolerService.java @@ -0,0 +1,162 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.HeaterCoolerAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCoolingThresholdTemperature; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHeatingThresholdTemperature; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPhysicalControlsLock; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRotationSpeed; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithSwingMode; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithTemperatureDisplayUnits; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.fan.LockPhysicalControlsCharacteristic; +import io.github.hapjava.characteristics.impl.fan.RotationSpeedCharacteristic; +import io.github.hapjava.characteristics.impl.fan.SwingModeCharacteristic; +import io.github.hapjava.characteristics.impl.heatercooler.CurrentHeaterCoolerStateCharacteristic; +import io.github.hapjava.characteristics.impl.heatercooler.TargetHeaterCoolerStateCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.CoolingThresholdTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.CurrentTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.HeatingThresholdTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.TemperatureDisplayUnitCharacteristic; + +/** This service can be used to describe a heater and/or a cooler */ +public class HeaterCoolerService extends AbstractServiceImpl { + + public HeaterCoolerService( + ActiveCharacteristic activeCharacteristic, + CurrentTemperatureCharacteristic currentTemperatureCharacteristic, + CurrentHeaterCoolerStateCharacteristic currentHeaterCoolerStateCharacteristic, + TargetHeaterCoolerStateCharacteristic targetHeaterCoolerStateCharacteristic) { + super("000000BC-0000-1000-8000-0026BB765291"); + addCharacteristic(activeCharacteristic); + addCharacteristic(currentTemperatureCharacteristic); + addCharacteristic(currentHeaterCoolerStateCharacteristic); + addCharacteristic(targetHeaterCoolerStateCharacteristic); + } + + public HeaterCoolerService(HeaterCoolerAccessory accessory) { + this( + new ActiveCharacteristic( + () -> accessory.isActive().thenApply(s -> s ? ActiveEnum.ACTIVE : ActiveEnum.INACTIVE), + (v) -> accessory.setActive(v == ActiveEnum.ACTIVE), + accessory::subscribeActive, + accessory::unsubscribeActive), + new CurrentTemperatureCharacteristic( + accessory::getCurrentTemperature, + accessory::subscribeCurrentTemperature, + accessory::unsubscribeCurrentTemperature), + new CurrentHeaterCoolerStateCharacteristic( + accessory.getCurrentHeaterCoolerStateValidValues(), + accessory::getCurrentHeaterCoolerState, + accessory::subscribeCurrentHeaterCoolerState, + accessory::unsubscribeCurrentHeaterCoolerState), + new TargetHeaterCoolerStateCharacteristic( + accessory.getTargetHeaterCoolerStateValidValues(), + accessory::getTargetHeaterCoolerState, + accessory::setTargetHeaterCoolerState, + accessory::subscribeTargetHeaterCoolerState, + accessory::unsubscribeTargetHeaterCoolerState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithRotationSpeed) { + addOptionalCharacteristic( + new RotationSpeedCharacteristic( + ((AccessoryWithRotationSpeed) accessory)::getRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::setRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::subscribeRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::unsubscribeRotationSpeed)); + } + if (accessory instanceof AccessoryWithSwingMode) { + addOptionalCharacteristic( + new SwingModeCharacteristic( + ((AccessoryWithSwingMode) accessory)::getSwingMode, + ((AccessoryWithSwingMode) accessory)::setSwingMode, + ((AccessoryWithSwingMode) accessory)::subscribeSwingMode, + ((AccessoryWithSwingMode) accessory)::unsubscribeSwingMode)); + } + if (accessory instanceof AccessoryWithPhysicalControlsLock) { + addOptionalCharacteristic( + new LockPhysicalControlsCharacteristic( + ((AccessoryWithPhysicalControlsLock) accessory)::getLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::setLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::subscribeLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::unsubscribeLockControls)); + } + if (accessory instanceof AccessoryWithCoolingThresholdTemperature) { + addOptionalCharacteristic( + new CoolingThresholdTemperatureCharacteristic( + ((AccessoryWithCoolingThresholdTemperature) accessory) + .getMinCoolingThresholdTemperature(), + ((AccessoryWithCoolingThresholdTemperature) accessory) + .getMaxCoolingThresholdTemperature(), + ((AccessoryWithCoolingThresholdTemperature) accessory) + .getStepCoolingThresholdTemperature(), + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::getCoolingThresholdTemperature, + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::setCoolingThresholdTemperature, + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::subscribeCoolingThresholdTemperature, + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::unsubscribeCoolingThresholdTemperature)); + } + if (accessory instanceof AccessoryWithHeatingThresholdTemperature) { + addOptionalCharacteristic( + new HeatingThresholdTemperatureCharacteristic( + ((AccessoryWithHeatingThresholdTemperature) accessory) + .getMinHeatingThresholdTemperature(), + ((AccessoryWithHeatingThresholdTemperature) accessory) + .getMaxHeatingThresholdTemperature(), + ((AccessoryWithHeatingThresholdTemperature) accessory) + .getStepHeatingThresholdTemperature(), + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::getHeatingThresholdTemperature, + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::setHeatingThresholdTemperature, + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::subscribeHeatingThresholdTemperature, + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::unsubscribeHeatingThresholdTemperature)); + } + if (accessory instanceof AccessoryWithTemperatureDisplayUnits) { + addOptionalCharacteristic( + new TemperatureDisplayUnitCharacteristic( + ((AccessoryWithTemperatureDisplayUnits) accessory)::getTemperatureDisplayUnits, + ((AccessoryWithTemperatureDisplayUnits) accessory)::setTemperatureDisplayUnits, + ((AccessoryWithTemperatureDisplayUnits) accessory)::subscribeTemperatureDisplayUnits, + ((AccessoryWithTemperatureDisplayUnits) accessory) + ::unsubscribeTemperatureDisplayUnits)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(RotationSpeedCharacteristic speed) { + addCharacteristic(speed); + } + + public void addOptionalCharacteristic(SwingModeCharacteristic mode) { + addCharacteristic(mode); + } + + public void addOptionalCharacteristic(LockPhysicalControlsCharacteristic lock) { + addCharacteristic(lock); + } + + public void addOptionalCharacteristic(CoolingThresholdTemperatureCharacteristic threshold) { + addCharacteristic(threshold); + } + + public void addOptionalCharacteristic(HeatingThresholdTemperatureCharacteristic threshold) { + addCharacteristic(threshold); + } + + public void addOptionalCharacteristic(TemperatureDisplayUnitCharacteristic displayUnits) { + addCharacteristic(displayUnits); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/HumidifierDehumidifierService.java b/src/main/java/io/github/hapjava/services/impl/HumidifierDehumidifierService.java new file mode 100644 index 000000000..afd1dfdb2 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/HumidifierDehumidifierService.java @@ -0,0 +1,143 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.HumidifierDehumidifierAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHumidityDehumidifierThreshold; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHumidityHumidifierThreshold; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPhysicalControlsLock; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRotationSpeed; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithSwingMode; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithWaterLevel; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.WaterLavelCharacteristic; +import io.github.hapjava.characteristics.impl.fan.LockPhysicalControlsCharacteristic; +import io.github.hapjava.characteristics.impl.fan.RotationSpeedCharacteristic; +import io.github.hapjava.characteristics.impl.fan.SwingModeCharacteristic; +import io.github.hapjava.characteristics.impl.humidifier.CurrentHumidifierDehumidifierStateCharacteristic; +import io.github.hapjava.characteristics.impl.humidifier.HumidityDehumidifierThresholdCharacteristic; +import io.github.hapjava.characteristics.impl.humidifier.HumidityHumidifierThresholdCharacteristic; +import io.github.hapjava.characteristics.impl.humidifier.TargetHumidifierDehumidifierStateCharacteristic; +import io.github.hapjava.characteristics.impl.humiditysensor.CurrentRelativeHumidityCharacteristic; + +/** This service can be used to describe an air humidifier or/and an air dehumidifier. */ +public class HumidifierDehumidifierService extends AbstractServiceImpl { + + public HumidifierDehumidifierService( + ActiveCharacteristic activeCharacteristic, + CurrentRelativeHumidityCharacteristic currentRelativeHumidityCharacteristic, + CurrentHumidifierDehumidifierStateCharacteristic + currentHumidifierDehumidifierStateCharacteristic, + TargetHumidifierDehumidifierStateCharacteristic + targetHumidifierDehumidifierStateCharacteristic) { + super("000000BD-0000-1000-8000-0026BB765291"); + addCharacteristic(activeCharacteristic); + addCharacteristic(currentRelativeHumidityCharacteristic); + addCharacteristic(currentHumidifierDehumidifierStateCharacteristic); + addCharacteristic(targetHumidifierDehumidifierStateCharacteristic); + } + + public HumidifierDehumidifierService(HumidifierDehumidifierAccessory accessory) { + this( + new ActiveCharacteristic( + () -> accessory.isActive().thenApply(s -> s ? ActiveEnum.ACTIVE : ActiveEnum.INACTIVE), + (v) -> accessory.setActive(v == ActiveEnum.ACTIVE), + accessory::subscribeActive, + accessory::unsubscribeActive), + new CurrentRelativeHumidityCharacteristic( + accessory::getCurrentHumidity, + accessory::subscribeCurrentHumidity, + accessory::unsubscribeCurrentHumidity), + new CurrentHumidifierDehumidifierStateCharacteristic( + accessory::getCurrentHumidifierDehumidifierState, + accessory::subscribeCurrentHumidifierDehumidifierState, + accessory::unsubscribeCurrentHumidifierDehumidifierState), + new TargetHumidifierDehumidifierStateCharacteristic( + accessory.getTargetHumidifierDehumidifierStateValidValues(), + accessory::getTargetHumidifierDehumidifierState, + accessory::setTargetHumidifierDehumidifierState, + accessory::subscribeTargetHumidifierDehumidifierState, + accessory::unsubscribeTargetHumidifierDehumidifierState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithRotationSpeed) { + addOptionalCharacteristic( + new RotationSpeedCharacteristic( + ((AccessoryWithRotationSpeed) accessory)::getRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::setRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::subscribeRotationSpeed, + ((AccessoryWithRotationSpeed) accessory)::unsubscribeRotationSpeed)); + } + if (accessory instanceof AccessoryWithSwingMode) { + addOptionalCharacteristic( + new SwingModeCharacteristic( + ((AccessoryWithSwingMode) accessory)::getSwingMode, + ((AccessoryWithSwingMode) accessory)::setSwingMode, + ((AccessoryWithSwingMode) accessory)::subscribeSwingMode, + ((AccessoryWithSwingMode) accessory)::unsubscribeSwingMode)); + } + if (accessory instanceof AccessoryWithPhysicalControlsLock) { + addOptionalCharacteristic( + new LockPhysicalControlsCharacteristic( + ((AccessoryWithPhysicalControlsLock) accessory)::getLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::setLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::subscribeLockControls, + ((AccessoryWithPhysicalControlsLock) accessory)::unsubscribeLockControls)); + } + if (accessory instanceof AccessoryWithHumidityDehumidifierThreshold) { + addOptionalCharacteristic( + new HumidityDehumidifierThresholdCharacteristic( + ((AccessoryWithHumidityDehumidifierThreshold) accessory)::getHumidityThreshold, + ((AccessoryWithHumidityDehumidifierThreshold) accessory)::setHumidityThreshold, + ((AccessoryWithHumidityDehumidifierThreshold) accessory)::subscribeHumidityThreshold, + ((AccessoryWithHumidityDehumidifierThreshold) accessory) + ::unsubscribeHumidityThreshold)); + } + if (accessory instanceof AccessoryWithHumidityHumidifierThreshold) { + addOptionalCharacteristic( + new HumidityHumidifierThresholdCharacteristic( + ((AccessoryWithHumidityHumidifierThreshold) accessory)::getHumidityThreshold, + ((AccessoryWithHumidityHumidifierThreshold) accessory)::setHumidityThreshold, + ((AccessoryWithHumidityHumidifierThreshold) accessory)::subscribeHumidityThreshold, + ((AccessoryWithHumidityHumidifierThreshold) accessory) + ::unsubscribeHumidityThreshold)); + } + if (accessory instanceof AccessoryWithWaterLevel) { + addOptionalCharacteristic( + new WaterLavelCharacteristic( + ((AccessoryWithWaterLevel) accessory)::getWaterLevel, + ((AccessoryWithWaterLevel) accessory)::subscribeWaterLevel, + ((AccessoryWithWaterLevel) accessory)::unsubscribeWaterLevel)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(RotationSpeedCharacteristic speed) { + addCharacteristic(speed); + } + + public void addOptionalCharacteristic(SwingModeCharacteristic mode) { + addCharacteristic(mode); + } + + public void addOptionalCharacteristic(LockPhysicalControlsCharacteristic lock) { + addCharacteristic(lock); + } + + public void addOptionalCharacteristic(HumidityDehumidifierThresholdCharacteristic threshold) { + addCharacteristic(threshold); + } + + public void addOptionalCharacteristic(HumidityHumidifierThresholdCharacteristic threshold) { + addCharacteristic(threshold); + } + + public void addOptionalCharacteristic(WaterLavelCharacteristic level) { + addCharacteristic(level); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/HumiditySensorService.java b/src/main/java/io/github/hapjava/services/impl/HumiditySensorService.java new file mode 100644 index 000000000..4153510a3 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/HumiditySensorService.java @@ -0,0 +1,84 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.HumiditySensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.humiditysensor.CurrentRelativeHumidityCharacteristic; + +/** This service describes a humidity sensor. */ +public class HumiditySensorService extends AbstractServiceImpl { + + public HumiditySensorService( + CurrentRelativeHumidityCharacteristic currentRelativeHumidityCharacteristic) { + super("00000082-0000-1000-8000-0026BB765291"); + addCharacteristic(currentRelativeHumidityCharacteristic); + } + + public HumiditySensorService(HumiditySensorAccessory accessory) { + this( + new CurrentRelativeHumidityCharacteristic( + accessory::getCurrentRelativeHumidity, + accessory::subscribeCurrentRelativeHumidity, + accessory::unsubscribeCurrentRelativeHumidity)); + + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/InputSourceService.java b/src/main/java/io/github/hapjava/services/impl/InputSourceService.java new file mode 100644 index 000000000..4af2736a2 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/InputSourceService.java @@ -0,0 +1,91 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.InputSourceAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithIdentifier; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithInputDeviceType; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithTargetVisibilityState; +import io.github.hapjava.characteristics.impl.common.ConfiguredNameCharacteristic; +import io.github.hapjava.characteristics.impl.common.IdentifierCharacteristic; +import io.github.hapjava.characteristics.impl.common.IsConfiguredCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.inputsource.CurrentVisibilityStateCharacteristic; +import io.github.hapjava.characteristics.impl.inputsource.InputDeviceTypeCharacteristic; +import io.github.hapjava.characteristics.impl.inputsource.InputSourceTypeCharacteristic; +import io.github.hapjava.characteristics.impl.inputsource.TargetVisibilityStateCharacteristic; + +/** This service describes a input source. */ +public class InputSourceService extends AbstractServiceImpl { + + public InputSourceService( + ConfiguredNameCharacteristic configuredNameCharacteristic, + InputSourceTypeCharacteristic inputSourceTypeCharacteristic, + IsConfiguredCharacteristic isConfiguredCharacteristic, + CurrentVisibilityStateCharacteristic currentVisibilityStateCharacteristic) { + super("000000D9-0000-1000-8000-0026BB765291"); + addCharacteristic(configuredNameCharacteristic); + addCharacteristic(inputSourceTypeCharacteristic); + addCharacteristic(isConfiguredCharacteristic); + addCharacteristic(currentVisibilityStateCharacteristic); + } + + public InputSourceService(InputSourceAccessory accessory) { + this( + new ConfiguredNameCharacteristic( + accessory::getConfiguredName, + accessory::setConfiguredName, + accessory::subscribeConfiguredName, + accessory::unsubscribeConfiguredName), + new InputSourceTypeCharacteristic( + accessory::getInputSourceType, + accessory::subscribeInputSourceType, + accessory::unsubscribeInputSourceType), + new IsConfiguredCharacteristic( + accessory::isConfigured, + accessory::setIsConfigured, + accessory::subscribeIsConfigured, + accessory::unsubscribeIsConfigured), + new CurrentVisibilityStateCharacteristic( + accessory::getCurrentVisibilityState, + accessory::subscribeCurrentVisibilityState, + accessory::unsubscribeCurrentVisibilityState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithIdentifier) { + addOptionalCharacteristic( + new IdentifierCharacteristic(((AccessoryWithIdentifier) accessory)::getIdentifier)); + } + if (accessory instanceof AccessoryWithInputDeviceType) { + addOptionalCharacteristic( + new InputDeviceTypeCharacteristic( + ((AccessoryWithInputDeviceType) accessory)::getInputDeviceType, + ((AccessoryWithInputDeviceType) accessory)::subscribeInputDeviceType, + ((AccessoryWithInputDeviceType) accessory)::unsubscribeInputDeviceType)); + } + if (accessory instanceof AccessoryWithTargetVisibilityState) { + addOptionalCharacteristic( + new TargetVisibilityStateCharacteristic( + ((AccessoryWithTargetVisibilityState) accessory)::getTargetVisibilityState, + ((AccessoryWithTargetVisibilityState) accessory)::setTargetVisibilityState, + ((AccessoryWithTargetVisibilityState) accessory)::subscribeTargetVisibilityState, + ((AccessoryWithTargetVisibilityState) accessory)::unsubscribeTargetVisibilityState)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(IdentifierCharacteristic identifier) { + addCharacteristic(identifier); + } + + public void addOptionalCharacteristic(InputDeviceTypeCharacteristic inputDeviceType) { + addCharacteristic(inputDeviceType); + } + + public void addOptionalCharacteristic(TargetVisibilityStateCharacteristic targetVisibilityState) { + addCharacteristic(targetVisibilityState); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/IrrigationSystemService.java b/src/main/java/io/github/hapjava/services/impl/IrrigationSystemService.java new file mode 100644 index 000000000..3501ba723 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/IrrigationSystemService.java @@ -0,0 +1,71 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.IrrigationSystemAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRemainingDuration; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.InUseCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ProgramModeCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.valve.RemainingDurationCharacteristic; + +/** An irrigation system service */ +public class IrrigationSystemService extends AbstractServiceImpl { + + public IrrigationSystemService( + ActiveCharacteristic activeCharacteristic, + InUseCharacteristic inUseCharacteristic, + ProgramModeCharacteristic programModeCharacteristic) { + super("000000CF-0000-1000-8000-0026BB765291"); + addCharacteristic(activeCharacteristic); + addCharacteristic(inUseCharacteristic); + addCharacteristic(programModeCharacteristic); + } + + public IrrigationSystemService(IrrigationSystemAccessory accessory) { + this( + new ActiveCharacteristic( + accessory::getActive, + accessory::setActive, + accessory::subscribeActive, + accessory::unsubscribeActive), + new InUseCharacteristic( + accessory::getInUse, accessory::subscribeInUse, accessory::unsubscribeInUse), + new ProgramModeCharacteristic( + accessory::getProgramMode, + accessory::subscribeProgramMode, + accessory::unsubscribeProgramMode)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithRemainingDuration) { + addOptionalCharacteristic( + new RemainingDurationCharacteristic( + ((AccessoryWithRemainingDuration) accessory)::getRemainingDuration, + ((AccessoryWithRemainingDuration) accessory)::subscribeRemainingDuration, + ((AccessoryWithRemainingDuration) accessory)::unsubscribeRemainingDuration)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFaultCharacteristic) { + addCharacteristic(statusFaultCharacteristic); + } + + public void addOptionalCharacteristic( + RemainingDurationCharacteristic remainingDurationCharacteristic) { + addCharacteristic(remainingDurationCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/LeakSensorService.java b/src/main/java/io/github/hapjava/services/impl/LeakSensorService.java new file mode 100644 index 000000000..b8470371a --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/LeakSensorService.java @@ -0,0 +1,83 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.LeakSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.leaksensor.LeakDetectedStateCharacteristic; + +/** This service describes a leak sensor. */ +public class LeakSensorService extends AbstractServiceImpl { + + public LeakSensorService(LeakDetectedStateCharacteristic leakDetectedState) { + super("00000083-0000-1000-8000-0026BB765291"); + addCharacteristic(leakDetectedState); + } + + public LeakSensorService(LeakSensorAccessory accessory) { + this( + new LeakDetectedStateCharacteristic( + accessory::getLeakDetected, + accessory::subscribeLeakDetected, + accessory::unsubscribeLeakDetected)); + + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/LightSensorService.java b/src/main/java/io/github/hapjava/services/impl/LightSensorService.java new file mode 100644 index 000000000..6aef8cd34 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/LightSensorService.java @@ -0,0 +1,86 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.LightSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.lightsensor.CurrentAmbientLightLevelCharacteristic; + +/** This service describes a light sensor. */ +public class LightSensorService extends AbstractServiceImpl { + + public LightSensorService(CurrentAmbientLightLevelCharacteristic lightLevel) { + super("00000084-0000-1000-8000-0026BB765291"); + addCharacteristic(lightLevel); + } + + public LightSensorService(LightSensorAccessory accessory) { + this( + new CurrentAmbientLightLevelCharacteristic( + accessory.getMinCurrentAmbientLightLevel(), + accessory.getMaxCurrentAmbientLightLevel(), + accessory.getMinStepCurrentAmbientLightLevel(), + accessory::getCurrentAmbientLightLevel, + accessory::subscribeCurrentAmbientLightLevel, + accessory::unsubscribeCurrentAmbientLightLevel)); + + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/LightbulbService.java b/src/main/java/io/github/hapjava/services/impl/LightbulbService.java new file mode 100644 index 000000000..b37ca4d2c --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/LightbulbService.java @@ -0,0 +1,86 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.LightbulbAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithBrightness; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithColor; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithColorTemperature; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.OnCharacteristic; +import io.github.hapjava.characteristics.impl.lightbulb.BrightnessCharacteristic; +import io.github.hapjava.characteristics.impl.lightbulb.ColorTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.lightbulb.HueCharacteristic; +import io.github.hapjava.characteristics.impl.lightbulb.SaturationCharacteristic; + +/** This service describes a light bulb. */ +public class LightbulbService extends AbstractServiceImpl { + + public LightbulbService(OnCharacteristic onState) { + super("00000043-0000-1000-8000-0026BB765291"); + addCharacteristic(onState); + } + + public LightbulbService(LightbulbAccessory accessory) { + this( + new OnCharacteristic( + accessory::getLightbulbPowerState, + accessory::setLightbulbPowerState, + accessory::subscribeLightbulbPowerState, + accessory::unsubscribeLightbulbPowerState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithColor) { + addOptionalCharacteristic( + new HueCharacteristic( + ((AccessoryWithColor) accessory)::getHue, + ((AccessoryWithColor) accessory)::setHue, + ((AccessoryWithColor) accessory)::subscribeHue, + ((AccessoryWithColor) accessory)::unsubscribeHue)); + addOptionalCharacteristic( + new SaturationCharacteristic( + ((AccessoryWithColor) accessory)::getSaturation, + ((AccessoryWithColor) accessory)::setSaturation, + ((AccessoryWithColor) accessory)::subscribeSaturation, + ((AccessoryWithColor) accessory)::unsubscribeSaturation)); + } + if (accessory instanceof AccessoryWithBrightness) { + addOptionalCharacteristic( + new BrightnessCharacteristic( + ((AccessoryWithBrightness) accessory)::getBrightness, + ((AccessoryWithBrightness) accessory)::setBrightness, + ((AccessoryWithBrightness) accessory)::subscribeBrightness, + ((AccessoryWithBrightness) accessory)::unsubscribeBrightness)); + } + if (accessory instanceof AccessoryWithColorTemperature) { + addOptionalCharacteristic( + new ColorTemperatureCharacteristic( + ((AccessoryWithColorTemperature) accessory).getMinColorTemperature(), + ((AccessoryWithColorTemperature) accessory).getMaxColorTemperature(), + ((AccessoryWithColorTemperature) accessory)::getColorTemperature, + ((AccessoryWithColorTemperature) accessory)::setColorTemperature, + ((AccessoryWithColorTemperature) accessory)::subscribeColorTemperature, + ((AccessoryWithColorTemperature) accessory)::unsubscribeColorTemperature)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(HueCharacteristic hue) { + addCharacteristic(hue); + } + + public void addOptionalCharacteristic(BrightnessCharacteristic brightness) { + addCharacteristic(brightness); + } + + public void addOptionalCharacteristic(SaturationCharacteristic saturation) { + addCharacteristic(saturation); + } + + public void addOptionalCharacteristic(ColorTemperatureCharacteristic color) { + addCharacteristic(color); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/LockMechanismService.java b/src/main/java/io/github/hapjava/services/impl/LockMechanismService.java new file mode 100644 index 000000000..de59ca516 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/LockMechanismService.java @@ -0,0 +1,39 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.LockMechanismAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.lock.LockCurrentStateCharacteristic; +import io.github.hapjava.characteristics.impl.lock.LockTargetStateCharacteristic; + +/** The Lock Mechanism Service describes the physical lock mechanism on a device. */ +public class LockMechanismService extends AbstractServiceImpl { + + public LockMechanismService( + LockCurrentStateCharacteristic lockCurrentState, + LockTargetStateCharacteristic lockTargetState) { + super("00000045-0000-1000-8000-0026BB765291"); + addCharacteristic(lockCurrentState); + addCharacteristic(lockTargetState); + } + + public LockMechanismService(LockMechanismAccessory accessory) { + this( + new LockCurrentStateCharacteristic( + accessory::getLockCurrentState, + accessory::subscribeLockCurrentState, + accessory::unsubscribeLockCurrentState), + new LockTargetStateCharacteristic( + accessory::getLockTargetState, + accessory::setLockTargetState, + accessory::subscribeLockTargetState, + accessory::unsubscribeLockTargetState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/MicrophoneService.java b/src/main/java/io/github/hapjava/services/impl/MicrophoneService.java new file mode 100644 index 000000000..3f72bd4f7 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/MicrophoneService.java @@ -0,0 +1,48 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.MicrophoneAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVolume; +import io.github.hapjava.characteristics.impl.audio.MuteCharacteristic; +import io.github.hapjava.characteristics.impl.audio.VolumeCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; + +/** + * A Microphone service is used to control the sourcing of the input audio – primarily through a + * microphone. + */ +public class MicrophoneService extends AbstractServiceImpl { + + public MicrophoneService(MuteCharacteristic muteCharacteristic) { + super("00000112-0000-1000-8000-0026BB765291"); + addCharacteristic(muteCharacteristic); + } + + public MicrophoneService(MicrophoneAccessory accessory) { + this( + new MuteCharacteristic( + accessory::isMuted, + accessory::setMute, + accessory::subscribeMuteState, + accessory::unsubscribeMuteState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithVolume) { + addOptionalCharacteristic( + new VolumeCharacteristic( + ((AccessoryWithVolume) accessory)::getVolume, + ((AccessoryWithVolume) accessory)::setVolume, + ((AccessoryWithVolume) accessory)::subscribeVolume, + ((AccessoryWithVolume) accessory)::unsubscribeVolume)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(VolumeCharacteristic volume) { + addCharacteristic(volume); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/MotionSensorService.java b/src/main/java/io/github/hapjava/services/impl/MotionSensorService.java new file mode 100644 index 000000000..388448b35 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/MotionSensorService.java @@ -0,0 +1,82 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.MotionSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.motionsensor.MotionDetectedCharacteristic; + +/** This service describes a motion sensor. */ +public class MotionSensorService extends AbstractServiceImpl { + + public MotionSensorService(MotionDetectedCharacteristic motionDetectedCharacteristic) { + super("00000085-0000-1000-8000-0026BB765291"); + addCharacteristic(motionDetectedCharacteristic); + } + + public MotionSensorService(MotionSensorAccessory accessory) { + this( + new MotionDetectedCharacteristic( + accessory::getMotionDetected, + accessory::subscribeMotionDetected, + accessory::unsubscribeMotionDetected)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/OccupancySensorService.java b/src/main/java/io/github/hapjava/services/impl/OccupancySensorService.java new file mode 100644 index 000000000..12771e60e --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/OccupancySensorService.java @@ -0,0 +1,82 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.OccupancySensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.occupancysensor.OccupancyDetectedCharacteristic; + +/** This service describes an occupancy sensor. */ +public class OccupancySensorService extends AbstractServiceImpl { + + public OccupancySensorService(OccupancyDetectedCharacteristic occupancyDetectedCharacteristic) { + super("00000086-0000-1000-8000-0026BB765291"); + addCharacteristic(occupancyDetectedCharacteristic); + } + + public OccupancySensorService(OccupancySensorAccessory accessory) { + this( + new OccupancyDetectedCharacteristic( + accessory::getOccupancyDetected, + accessory::subscribeOccupancyDetected, + accessory::unsubscribeOccupancyDetected)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/OutletService.java b/src/main/java/io/github/hapjava/services/impl/OutletService.java new file mode 100644 index 000000000..780024f1f --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/OutletService.java @@ -0,0 +1,37 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.OutletAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.OnCharacteristic; +import io.github.hapjava.characteristics.impl.outlet.OutletInUseCharacteristic; + +/** This service describes a power outlet. */ +public class OutletService extends AbstractServiceImpl { + + public OutletService(OnCharacteristic onState, OutletInUseCharacteristic outletInUse) { + super("00000047-0000-1000-8000-0026BB765291"); + addCharacteristic(onState); + addCharacteristic(outletInUse); + } + + public OutletService(OutletAccessory accessory) { + this( + new OnCharacteristic( + accessory::getPowerState, + accessory::setPowerState, + accessory::subscribePowerState, + accessory::unsubscribePowerState), + new OutletInUseCharacteristic( + accessory::getOutletInUse, + accessory::subscribeOutletInUse, + accessory::unsubscribeOutletInUse)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/SecuritySystemService.java b/src/main/java/io/github/hapjava/services/impl/SecuritySystemService.java new file mode 100644 index 000000000..f2bc8d02e --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/SecuritySystemService.java @@ -0,0 +1,80 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.SecuritySystemAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithSecurityAlarmType; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.securitysystem.CurrentSecuritySystemStateCharacteristic; +import io.github.hapjava.characteristics.impl.securitysystem.SecuritySystemAlarmTypeCharacteristic; +import io.github.hapjava.characteristics.impl.securitysystem.TargetSecuritySystemStateCharacteristic; + +/** This service describes a security system service. */ +public class SecuritySystemService extends AbstractServiceImpl { + + public SecuritySystemService( + CurrentSecuritySystemStateCharacteristic currentState, + TargetSecuritySystemStateCharacteristic targetState) { + super("0000007E-0000-1000-8000-0026BB765291"); + addCharacteristic(currentState); + addCharacteristic(targetState); + } + + public SecuritySystemService(SecuritySystemAccessory accessory) { + this( + new CurrentSecuritySystemStateCharacteristic( + accessory.getCurrentSecuritySystemStateValidValues(), + accessory::getCurrentSecuritySystemState, + accessory::subscribeCurrentSecuritySystemState, + accessory::unsubscribeCurrentSecuritySystemState), + new TargetSecuritySystemStateCharacteristic( + accessory.getTargetSecuritySystemStateValidValues(), + accessory::getTargetSecuritySystemState, + accessory::setTargetSecuritySystemState, + accessory::subscribeTargetSecuritySystemState, + accessory::unsubscribeTargetSecuritySystemState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithSecurityAlarmType) { + addOptionalCharacteristic( + new SecuritySystemAlarmTypeCharacteristic( + ((AccessoryWithSecurityAlarmType) accessory)::getSecurityAlarmType, + ((AccessoryWithSecurityAlarmType) accessory)::subscribeSecurityAlarmType, + ((AccessoryWithSecurityAlarmType) accessory)::unsubscribeSecurityAlarmType)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(SecuritySystemAlarmTypeCharacteristic alarmType) { + addCharacteristic(alarmType); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/ServiceLabelService.java b/src/main/java/io/github/hapjava/services/impl/ServiceLabelService.java new file mode 100644 index 000000000..bee40f094 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/ServiceLabelService.java @@ -0,0 +1,13 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.characteristics.impl.common.ServiceLabelNamespaceCharacteristic; + +/** This service describes label scheme. */ +public class ServiceLabelService extends AbstractServiceImpl { + + public ServiceLabelService( + ServiceLabelNamespaceCharacteristic serviceLabelNamespaceCharacteristic) { + super("000000CC-0000-1000-8000-0026BB765291"); + addCharacteristic(serviceLabelNamespaceCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/SlatService.java b/src/main/java/io/github/hapjava/services/impl/SlatService.java new file mode 100644 index 000000000..5993983fa --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/SlatService.java @@ -0,0 +1,77 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.SlatAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCurrentTilting; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithSwingMode; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithTargetTilting; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.fan.SwingModeCharacteristic; +import io.github.hapjava.characteristics.impl.slat.CurrentSlatStateCharacteristic; +import io.github.hapjava.characteristics.impl.slat.CurrentTiltAngleCharacteristic; +import io.github.hapjava.characteristics.impl.slat.SlatTypeCharacteristic; +import io.github.hapjava.characteristics.impl.slat.TargetTiltAngleCharacteristic; + +/** This service describes a slat */ +public class SlatService extends AbstractServiceImpl { + + public SlatService( + CurrentSlatStateCharacteristic state, SlatTypeCharacteristic slatTypeCharacteristic) { + super("000000B9-0000-1000-8000-0026BB765291"); + addCharacteristic(state); + addCharacteristic(slatTypeCharacteristic); + } + + public SlatService(SlatAccessory accessory) { + this( + new CurrentSlatStateCharacteristic( + accessory::getSlatState, + accessory::subscribeSlatState, + accessory::unsubscribeSlatState), + new SlatTypeCharacteristic(accessory::getSlatType)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithSwingMode) { + addOptionalCharacteristic( + new SwingModeCharacteristic( + ((AccessoryWithSwingMode) accessory)::getSwingMode, + ((AccessoryWithSwingMode) accessory)::setSwingMode, + ((AccessoryWithSwingMode) accessory)::subscribeSwingMode, + ((AccessoryWithSwingMode) accessory)::unsubscribeSwingMode)); + } + if (accessory instanceof AccessoryWithCurrentTilting) { + addOptionalCharacteristic( + new CurrentTiltAngleCharacteristic( + ((AccessoryWithCurrentTilting) accessory)::getCurrentTiltAngle, + ((AccessoryWithCurrentTilting) accessory)::subscribeCurrentTiltAngle, + ((AccessoryWithCurrentTilting) accessory)::unsubscribeCurrentTiltAngle)); + } + if (accessory instanceof AccessoryWithTargetTilting) { + addOptionalCharacteristic( + new TargetTiltAngleCharacteristic( + ((AccessoryWithTargetTilting) accessory)::getTargetTiltAngle, + ((AccessoryWithTargetTilting) accessory)::setTargetTiltAngle, + ((AccessoryWithTargetTilting) accessory)::subscribeTargetTiltAngle, + ((AccessoryWithTargetTilting) accessory)::unsubscribeTargetTiltAngle)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(SwingModeCharacteristic mode) { + addCharacteristic(mode); + } + + public void addOptionalCharacteristic( + TargetTiltAngleCharacteristic targetTiltAngleCharacteristic) { + addCharacteristic(targetTiltAngleCharacteristic); + } + + public void addOptionalCharacteristic( + CurrentTiltAngleCharacteristic currentTiltAngleCharacteristic) { + addCharacteristic(currentTiltAngleCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/SmartSpeakerService.java b/src/main/java/io/github/hapjava/services/impl/SmartSpeakerService.java new file mode 100644 index 000000000..e5f57eff4 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/SmartSpeakerService.java @@ -0,0 +1,95 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.SmartSpeakerAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithAirPlayEnable; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithConfiguredName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithMute; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVolume; +import io.github.hapjava.characteristics.impl.audio.MuteCharacteristic; +import io.github.hapjava.characteristics.impl.audio.VolumeCharacteristic; +import io.github.hapjava.characteristics.impl.common.AirPlayEnableCharacteristic; +import io.github.hapjava.characteristics.impl.common.ConfiguredNameCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.television.CurrentMediaStateCharacteristic; +import io.github.hapjava.characteristics.impl.television.TargetMediaStateCharacteristic; + +/** A smart speaker service can be used to control the audio output settings on a speaker device. */ +public class SmartSpeakerService extends AbstractServiceImpl { + + public SmartSpeakerService( + CurrentMediaStateCharacteristic currentMediaStateCharacteristic, + TargetMediaStateCharacteristic targetMediaStateCharacteristic) { + super("00000228-0000-1000-8000-0026BB765291"); + addCharacteristic(currentMediaStateCharacteristic); + addCharacteristic(targetMediaStateCharacteristic); + } + + public SmartSpeakerService(SmartSpeakerAccessory accessory) { + this( + new CurrentMediaStateCharacteristic( + accessory::getCurrentMediaState, + accessory::subscribeCurrentMediaState, + accessory::unsubscribeCurrentMediaState), + new TargetMediaStateCharacteristic( + accessory::getTargetMediaState, + accessory::setTargetMediaState, + accessory::subscribeTargetMediaState, + accessory::unsubscribeTargetMediaState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithVolume) { + addOptionalCharacteristic( + new VolumeCharacteristic( + ((AccessoryWithVolume) accessory)::getVolume, + ((AccessoryWithVolume) accessory)::setVolume, + ((AccessoryWithVolume) accessory)::subscribeVolume, + ((AccessoryWithVolume) accessory)::unsubscribeVolume)); + } + if (accessory instanceof AccessoryWithConfiguredName) { + addOptionalCharacteristic( + new ConfiguredNameCharacteristic( + ((AccessoryWithConfiguredName) accessory)::getConfiguredName, + ((AccessoryWithConfiguredName) accessory)::setConfiguredName, + ((AccessoryWithConfiguredName) accessory)::subscribeConfiguredName, + ((AccessoryWithConfiguredName) accessory)::unsubscribeConfiguredName)); + } + if (accessory instanceof AccessoryWithMute) { + addOptionalCharacteristic( + new MuteCharacteristic( + ((AccessoryWithMute) accessory)::isMuted, + ((AccessoryWithMute) accessory)::setMute, + ((AccessoryWithMute) accessory)::subscribeMuteState, + ((AccessoryWithMute) accessory)::unsubscribeMuteState)); + } + if (accessory instanceof AccessoryWithAirPlayEnable) { + addOptionalCharacteristic( + new AirPlayEnableCharacteristic( + ((AccessoryWithAirPlayEnable) accessory)::getAirPlayEnable, + ((AccessoryWithAirPlayEnable) accessory)::setAirPlayEnable, + ((AccessoryWithAirPlayEnable) accessory)::subscribeAirPlayEnable, + ((AccessoryWithAirPlayEnable) accessory)::unsubscribeAirPlayEnable)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(VolumeCharacteristic volume) { + addCharacteristic(volume); + } + + public void addOptionalCharacteristic(ConfiguredNameCharacteristic configuredNameCharacteristic) { + addCharacteristic(configuredNameCharacteristic); + } + + public void addOptionalCharacteristic(MuteCharacteristic muteCharacteristic) { + addCharacteristic(muteCharacteristic); + } + + public void addOptionalCharacteristic(AirPlayEnableCharacteristic airPlayEnableCharacteristic) { + addCharacteristic(airPlayEnableCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/SmokeSensorService.java b/src/main/java/io/github/hapjava/services/impl/SmokeSensorService.java new file mode 100644 index 000000000..b6bf2f8d6 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/SmokeSensorService.java @@ -0,0 +1,82 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.SmokeSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.smokesensor.SmokeDetectedCharacteristic; + +/** This service describes a Smoke detector Sensor. */ +public class SmokeSensorService extends AbstractServiceImpl { + + public SmokeSensorService(SmokeDetectedCharacteristic smokeDetectedCharacteristic) { + super("00000087-0000-1000-8000-0026BB765291"); + addCharacteristic(smokeDetectedCharacteristic); + } + + public SmokeSensorService(SmokeSensorAccessory accessory) { + this( + new SmokeDetectedCharacteristic( + accessory::getSmokeDetectedState, + accessory::subscribeSmokeDetectedState, + accessory::unsubscribeSmokeDetectedState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/SpeakerService.java b/src/main/java/io/github/hapjava/services/impl/SpeakerService.java new file mode 100644 index 000000000..8619d5a50 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/SpeakerService.java @@ -0,0 +1,45 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.SpeakerAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVolume; +import io.github.hapjava.characteristics.impl.audio.MuteCharacteristic; +import io.github.hapjava.characteristics.impl.audio.VolumeCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; + +/** A Speaker service can be used to control the audio output settings on a speaker device. */ +public class SpeakerService extends AbstractServiceImpl { + + public SpeakerService(MuteCharacteristic muteCharacteristic) { + super("00000113-0000-1000-8000-0026BB765291"); + addCharacteristic(muteCharacteristic); + } + + public SpeakerService(SpeakerAccessory accessory) { + this( + new MuteCharacteristic( + accessory::isMuted, + accessory::setMute, + accessory::subscribeMuteState, + accessory::unsubscribeMuteState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithVolume) { + addOptionalCharacteristic( + new VolumeCharacteristic( + ((AccessoryWithVolume) accessory)::getVolume, + ((AccessoryWithVolume) accessory)::setVolume, + ((AccessoryWithVolume) accessory)::subscribeVolume, + ((AccessoryWithVolume) accessory)::unsubscribeVolume)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(VolumeCharacteristic volume) { + addCharacteristic(volume); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/StatelessProgrammableSwitchService.java b/src/main/java/io/github/hapjava/services/impl/StatelessProgrammableSwitchService.java new file mode 100644 index 000000000..bded30f47 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/StatelessProgrammableSwitchService.java @@ -0,0 +1,42 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.StatelessProgrammableSwitchAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithServiceLabelIndex; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ProgrammableSwitchEventCharacteristic; +import io.github.hapjava.characteristics.impl.common.ServiceLabelIndexCharacteristic; + +/** This service describes a stateless programmable switch. */ +public class StatelessProgrammableSwitchService extends AbstractServiceImpl { + + public StatelessProgrammableSwitchService(ProgrammableSwitchEventCharacteristic switchEvent) { + super("00000089-0000-1000-8000-0026BB765291"); + addCharacteristic(switchEvent); + } + + public StatelessProgrammableSwitchService(StatelessProgrammableSwitchAccessory accessory) { + this( + new ProgrammableSwitchEventCharacteristic( + accessory::getSwitchEvent, + accessory::subscribeSwitchEvent, + accessory::unsubscribeSwitchEvent)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithServiceLabelIndex) { + addOptionalCharacteristic( + new ServiceLabelIndexCharacteristic( + ((AccessoryWithServiceLabelIndex) accessory)::getServiceLabelIndex)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic( + ServiceLabelIndexCharacteristic serviceLabelIndexCharacteristic) { + addCharacteristic(serviceLabelIndexCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/SwitchService.java b/src/main/java/io/github/hapjava/services/impl/SwitchService.java new file mode 100644 index 000000000..65a8f2124 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/SwitchService.java @@ -0,0 +1,31 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.SwitchAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.OnCharacteristic; + +/** This service describes a binary switch. */ +public class SwitchService extends AbstractServiceImpl { + + public SwitchService(OnCharacteristic onState) { + super("00000049-0000-1000-8000-0026BB765291"); + addCharacteristic(onState); + } + + public SwitchService(SwitchAccessory accessory) { + this( + new OnCharacteristic( + accessory::getSwitchState, + accessory::setSwitchState, + accessory::subscribeSwitchState, + accessory::unsubscribeSwitchState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/TelevisionService.java b/src/main/java/io/github/hapjava/services/impl/TelevisionService.java new file mode 100644 index 000000000..8846cffe1 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/TelevisionService.java @@ -0,0 +1,139 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.TelevisionAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithBrightness; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithClosedCaptions; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCurrentMediaState; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPictureMode; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithPowerMode; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithTargetMediaState; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveEnum; +import io.github.hapjava.characteristics.impl.common.ActiveIdentifierCharacteristic; +import io.github.hapjava.characteristics.impl.common.ConfiguredNameCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.lightbulb.BrightnessCharacteristic; +import io.github.hapjava.characteristics.impl.television.ClosedCaptionsCharacteristic; +import io.github.hapjava.characteristics.impl.television.CurrentMediaStateCharacteristic; +import io.github.hapjava.characteristics.impl.television.PictureModeCharacteristic; +import io.github.hapjava.characteristics.impl.television.PowerModeCharacteristic; +import io.github.hapjava.characteristics.impl.television.RemoteKeyCharacteristic; +import io.github.hapjava.characteristics.impl.television.SleepDiscoveryModeCharacteristic; +import io.github.hapjava.characteristics.impl.television.TargetMediaStateCharacteristic; + +/** This service describes a television. */ +public class TelevisionService extends AbstractServiceImpl { + + public TelevisionService( + ActiveCharacteristic activeCharacteristic, + ActiveIdentifierCharacteristic activeIdentifierCharacteristic, + ConfiguredNameCharacteristic configuredNameCharacteristic, + RemoteKeyCharacteristic remoteKeyCharacteristic, + SleepDiscoveryModeCharacteristic sleepDiscoveryModeCharacteristic) { + super("000000D8-0000-1000-8000-0026BB765291"); + addCharacteristic(activeCharacteristic); + addCharacteristic(activeIdentifierCharacteristic); + addCharacteristic(configuredNameCharacteristic); + addCharacteristic(remoteKeyCharacteristic); + addCharacteristic(sleepDiscoveryModeCharacteristic); + } + + public TelevisionService(TelevisionAccessory accessory) { + this( + new ActiveCharacteristic( + () -> accessory.isActive().thenApply(s -> s ? ActiveEnum.ACTIVE : ActiveEnum.INACTIVE), + (v) -> accessory.setActive(v == ActiveEnum.ACTIVE), + accessory::subscribeActive, + accessory::unsubscribeActive), + new ActiveIdentifierCharacteristic( + accessory::getActiveIdentifier, + accessory::setActiveIdentifier, + accessory::subscribeActiveIdentifier, + accessory::unsubscribeActiveIdentifier), + new ConfiguredNameCharacteristic( + accessory::getConfiguredName, + accessory::setConfiguredName, + accessory::subscribeConfiguredName, + accessory::unsubscribeConfiguredName), + new RemoteKeyCharacteristic(accessory::setRemoteKey), + new SleepDiscoveryModeCharacteristic( + accessory::getSleepDiscoveryMode, + accessory::subscribeSleepDiscoveryMode, + accessory::unsubscribeSleepDiscoveryMode)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithBrightness) { + addOptionalCharacteristic( + new BrightnessCharacteristic( + ((AccessoryWithBrightness) accessory)::getBrightness, + ((AccessoryWithBrightness) accessory)::setBrightness, + ((AccessoryWithBrightness) accessory)::subscribeBrightness, + ((AccessoryWithBrightness) accessory)::unsubscribeBrightness)); + } + if (accessory instanceof AccessoryWithPowerMode) { + addOptionalCharacteristic( + new PowerModeCharacteristic(((AccessoryWithPowerMode) accessory)::setPowerMode)); + } + if (accessory instanceof AccessoryWithClosedCaptions) { + addOptionalCharacteristic( + new ClosedCaptionsCharacteristic( + ((AccessoryWithClosedCaptions) accessory)::getClosedCaptions, + ((AccessoryWithClosedCaptions) accessory)::setClosedCaptions, + ((AccessoryWithClosedCaptions) accessory)::subscribeClosedCaptions, + ((AccessoryWithClosedCaptions) accessory)::unsubscribeClosedCaptions)); + } + if (accessory instanceof AccessoryWithCurrentMediaState) { + addOptionalCharacteristic( + new CurrentMediaStateCharacteristic( + ((AccessoryWithCurrentMediaState) accessory)::getCurrentMediaState, + ((AccessoryWithCurrentMediaState) accessory)::subscribeCurrentMediaState, + ((AccessoryWithCurrentMediaState) accessory)::unsubscribeCurrentMediaState)); + } + if (accessory instanceof AccessoryWithTargetMediaState) { + addOptionalCharacteristic( + new TargetMediaStateCharacteristic( + ((AccessoryWithTargetMediaState) accessory)::getTargetMediaState, + ((AccessoryWithTargetMediaState) accessory)::setTargetMediaState, + ((AccessoryWithTargetMediaState) accessory)::subscribeTargetMediaState, + ((AccessoryWithTargetMediaState) accessory)::unsubscribeTargetMediaState)); + } + if (accessory instanceof AccessoryWithPictureMode) { + addOptionalCharacteristic( + new PictureModeCharacteristic( + ((AccessoryWithPictureMode) accessory)::getPictureMode, + ((AccessoryWithPictureMode) accessory)::setPictureMode, + ((AccessoryWithPictureMode) accessory)::subscribePictureMode, + ((AccessoryWithPictureMode) accessory)::unsubscribePictureMode)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(PowerModeCharacteristic powerMode) { + addCharacteristic(powerMode); + } + + public void addOptionalCharacteristic(ClosedCaptionsCharacteristic closedCaptions) { + addCharacteristic(closedCaptions); + } + + public void addOptionalCharacteristic(CurrentMediaStateCharacteristic currentMediaState) { + addCharacteristic(currentMediaState); + } + + public void addOptionalCharacteristic(TargetMediaStateCharacteristic targetMediaState) { + addCharacteristic(targetMediaState); + } + + public void addOptionalCharacteristic(PictureModeCharacteristic pictureMode) { + addCharacteristic(pictureMode); + } + + public void addOptionalCharacteristic(BrightnessCharacteristic brightness) { + addCharacteristic(brightness); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/TelevisionSpeakerService.java b/src/main/java/io/github/hapjava/services/impl/TelevisionSpeakerService.java new file mode 100644 index 000000000..b53fb81bd --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/TelevisionSpeakerService.java @@ -0,0 +1,75 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.TelevisionSpeakerAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVolume; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVolumeControlType; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithVolumeSelector; +import io.github.hapjava.characteristics.impl.audio.MuteCharacteristic; +import io.github.hapjava.characteristics.impl.audio.VolumeCharacteristic; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.televisionspeaker.VolumeControlTypeCharacteristic; +import io.github.hapjava.characteristics.impl.televisionspeaker.VolumeSelectorCharacteristic; + +/** This service describes a television. */ +public class TelevisionSpeakerService extends AbstractServiceImpl { + + public TelevisionSpeakerService(MuteCharacteristic muteCharacteristic) { + super("00000113-0000-1000-8000-0026BB765291"); + addCharacteristic(muteCharacteristic); + } + + public TelevisionSpeakerService(TelevisionSpeakerAccessory accessory) { + this( + new MuteCharacteristic( + accessory::isMuted, + accessory::setMute, + accessory::subscribeMuteState, + accessory::unsubscribeMuteState)); + if (accessory instanceof AccessoryWithActive) { + addOptionalCharacteristic( + new ActiveCharacteristic( + ((AccessoryWithActive) accessory)::getActive, + ((AccessoryWithActive) accessory)::setActive, + ((AccessoryWithActive) accessory)::subscribeActive, + ((AccessoryWithActive) accessory)::unsubscribeActive)); + } + if (accessory instanceof AccessoryWithVolume) { + addOptionalCharacteristic( + new VolumeCharacteristic( + ((AccessoryWithVolume) accessory)::getVolume, + ((AccessoryWithVolume) accessory)::setVolume, + ((AccessoryWithVolume) accessory)::subscribeVolume, + ((AccessoryWithVolume) accessory)::unsubscribeVolume)); + } + if (accessory instanceof AccessoryWithVolumeSelector) { + addOptionalCharacteristic( + new VolumeSelectorCharacteristic( + ((AccessoryWithVolumeSelector) accessory)::setVolumeSelector)); + } + if (accessory instanceof AccessoryWithVolumeControlType) { + addOptionalCharacteristic( + new VolumeControlTypeCharacteristic( + ((AccessoryWithVolumeControlType) accessory)::getVolumeControlType, + ((AccessoryWithVolumeControlType) accessory)::subscribeVolumeControlType, + ((AccessoryWithVolumeControlType) accessory)::unsubscribeVolumeControlType)); + ; + } + } + + public void addOptionalCharacteristic(ActiveCharacteristic activeCharacteristic) { + addCharacteristic(activeCharacteristic); + } + + public void addOptionalCharacteristic(VolumeCharacteristic volume) { + addCharacteristic(volume); + } + + public void addOptionalCharacteristic(VolumeSelectorCharacteristic volumeSelector) { + addCharacteristic(volumeSelector); + } + + public void addOptionalCharacteristic(VolumeControlTypeCharacteristic volumeControlType) { + addCharacteristic(volumeControlType); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/TemperatureSensorService.java b/src/main/java/io/github/hapjava/services/impl/TemperatureSensorService.java new file mode 100644 index 000000000..bef9fff60 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/TemperatureSensorService.java @@ -0,0 +1,86 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.TemperatureSensorAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusActive; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusLowBattery; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusTampered; +import io.github.hapjava.characteristics.impl.battery.StatusLowBatteryCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusTamperedCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.CurrentTemperatureCharacteristic; + +/** This service describes a Temperature Sensor. */ +public class TemperatureSensorService extends AbstractServiceImpl { + + public TemperatureSensorService( + CurrentTemperatureCharacteristic currentTemperatureCharacteristic) { + super("0000008A-0000-1000-8000-0026BB765291"); + addCharacteristic(currentTemperatureCharacteristic); + } + + public TemperatureSensorService(TemperatureSensorAccessory accessory) { + this( + new CurrentTemperatureCharacteristic( + accessory.getMinCurrentTemperature(), + accessory.getMaxCurrentTemperature(), + accessory.getMinStepCurrentTemperature(), + accessory::getCurrentTemperature, + accessory::subscribeCurrentTemperature, + accessory::unsubscribeCurrentTemperature)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusActive) { + addOptionalCharacteristic( + new StatusActiveCharacteristic( + ((AccessoryWithStatusActive) accessory)::getStatusActive, + ((AccessoryWithStatusActive) accessory)::subscribeStatusActive, + ((AccessoryWithStatusActive) accessory)::unsubscribeStatusActive)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithStatusTampered) { + addOptionalCharacteristic( + new StatusTamperedCharacteristic( + ((AccessoryWithStatusTampered) accessory)::getStatusTampered, + ((AccessoryWithStatusTampered) accessory)::subscribeStatusTampered, + ((AccessoryWithStatusTampered) accessory)::unsubscribeStatusTampered)); + } + if (accessory instanceof AccessoryWithStatusLowBattery) { + addOptionalCharacteristic( + new StatusLowBatteryCharacteristic( + ((AccessoryWithStatusLowBattery) accessory)::getStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::subscribeStatusLowBattery, + ((AccessoryWithStatusLowBattery) accessory)::unsubscribeStatusLowBattery)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusActiveCharacteristic statusActive) { + addCharacteristic(statusActive); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFault) { + addCharacteristic(statusFault); + } + + public void addOptionalCharacteristic(StatusTamperedCharacteristic statusTampered) { + addCharacteristic(statusTampered); + } + + public void addOptionalCharacteristic(StatusLowBatteryCharacteristic statusLowBattery) { + addCharacteristic(statusLowBattery); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/ThermostatService.java b/src/main/java/io/github/hapjava/services/impl/ThermostatService.java new file mode 100644 index 000000000..c775a41d5 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/ThermostatService.java @@ -0,0 +1,147 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.ThermostatAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCoolingThresholdTemperature; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCurrentRelativeHumidity; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHeatingThresholdTemperature; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithTargetRelativeHumidity; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.humiditysensor.CurrentRelativeHumidityCharacteristic; +import io.github.hapjava.characteristics.impl.humiditysensor.TargetRelativeHumidityCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.CoolingThresholdTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.CurrentHeatingCoolingStateCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.CurrentTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.HeatingThresholdTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.TargetHeatingCoolingStateCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.TargetTemperatureCharacteristic; +import io.github.hapjava.characteristics.impl.thermostat.TemperatureDisplayUnitCharacteristic; + +/** This service describes a thermostat. */ +public class ThermostatService extends AbstractServiceImpl { + + public ThermostatService( + CurrentHeatingCoolingStateCharacteristic currentHeatingCoolingStateCharacteristic, + TargetHeatingCoolingStateCharacteristic targetHeatingCoolingStateCharacteristic, + CurrentTemperatureCharacteristic currentTemperatureCharacteristic, + TargetTemperatureCharacteristic targetTemperatureCharacteristic, + TemperatureDisplayUnitCharacteristic temperatureUnitsCharacteristic) { + super("0000004A-0000-1000-8000-0026BB765291"); + addCharacteristic(currentHeatingCoolingStateCharacteristic); + addCharacteristic(targetHeatingCoolingStateCharacteristic); + addCharacteristic(currentTemperatureCharacteristic); + addCharacteristic(targetTemperatureCharacteristic); + addCharacteristic(temperatureUnitsCharacteristic); + } + + public ThermostatService(ThermostatAccessory accessory) { + this( + new CurrentHeatingCoolingStateCharacteristic( + accessory.getCurrentHeatingCoolingStateValidValues(), + accessory::getCurrentState, + accessory::subscribeCurrentState, + accessory::unsubscribeCurrentState), + new TargetHeatingCoolingStateCharacteristic( + accessory.getTargetHeatingCoolingStateValidValues(), + accessory::getTargetState, + accessory::setTargetState, + accessory::subscribeTargetState, + accessory::unsubscribeTargetState), + new CurrentTemperatureCharacteristic( + accessory.getMinCurrentTemperature(), + accessory.getMaxCurrentTemperature(), + accessory.getMinStepCurrentTemperature(), + accessory::getCurrentTemperature, + accessory::subscribeCurrentTemperature, + accessory::unsubscribeCurrentTemperature), + new TargetTemperatureCharacteristic( + accessory.getMinTargetTemperature(), + accessory.getMaxTargetTemperature(), + accessory.getMinStepTargetTemperature(), + accessory::getTargetTemperature, + accessory::setTargetTemperature, + accessory::subscribeTargetTemperature, + accessory::unsubscribeTargetTemperature), + new TemperatureDisplayUnitCharacteristic( + accessory::getTemperatureDisplayUnit, + accessory::setTemperatureDisplayUnit, + accessory::subscribeTemperatureDisplayUnit, + accessory::unsubscribeTemperatureDisplayUnit)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithCoolingThresholdTemperature) { + addOptionalCharacteristic( + new CoolingThresholdTemperatureCharacteristic( + ((AccessoryWithCoolingThresholdTemperature) accessory) + .getMinCoolingThresholdTemperature(), + ((AccessoryWithCoolingThresholdTemperature) accessory) + .getMaxCoolingThresholdTemperature(), + ((AccessoryWithCoolingThresholdTemperature) accessory) + .getStepCoolingThresholdTemperature(), + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::getCoolingThresholdTemperature, + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::setCoolingThresholdTemperature, + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::subscribeCoolingThresholdTemperature, + ((AccessoryWithCoolingThresholdTemperature) accessory) + ::unsubscribeCoolingThresholdTemperature)); + } + if (accessory instanceof AccessoryWithHeatingThresholdTemperature) { + addOptionalCharacteristic( + new HeatingThresholdTemperatureCharacteristic( + ((AccessoryWithHeatingThresholdTemperature) accessory) + .getMinHeatingThresholdTemperature(), + ((AccessoryWithHeatingThresholdTemperature) accessory) + .getMaxHeatingThresholdTemperature(), + ((AccessoryWithHeatingThresholdTemperature) accessory) + .getStepHeatingThresholdTemperature(), + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::getHeatingThresholdTemperature, + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::setHeatingThresholdTemperature, + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::subscribeHeatingThresholdTemperature, + ((AccessoryWithHeatingThresholdTemperature) accessory) + ::unsubscribeHeatingThresholdTemperature)); + } + if (accessory instanceof AccessoryWithCurrentRelativeHumidity) { + addOptionalCharacteristic( + new CurrentRelativeHumidityCharacteristic( + ((AccessoryWithCurrentRelativeHumidity) accessory)::getCurrentRelativeHumidity, + ((AccessoryWithCurrentRelativeHumidity) accessory)::subscribeCurrentRelativeHumidity, + ((AccessoryWithCurrentRelativeHumidity) accessory) + ::unsubscribeCurrentRelativeHumidity)); + } + if (accessory instanceof AccessoryWithTargetRelativeHumidity) { + addOptionalCharacteristic( + new TargetRelativeHumidityCharacteristic( + ((AccessoryWithTargetRelativeHumidity) accessory)::getTargetRelativeHumidity, + ((AccessoryWithTargetRelativeHumidity) accessory)::setTargetRelativeHumidity, + ((AccessoryWithTargetRelativeHumidity) accessory)::subscribeTargetRelativeHumidity, + ((AccessoryWithTargetRelativeHumidity) accessory) + ::unsubscribeTargetRelativeHumidity)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(CoolingThresholdTemperatureCharacteristic threshold) { + addCharacteristic(threshold); + } + + public void addOptionalCharacteristic(HeatingThresholdTemperatureCharacteristic threshold) { + addCharacteristic(threshold); + } + + public void addOptionalCharacteristic(CurrentRelativeHumidityCharacteristic humidity) { + addCharacteristic(humidity); + } + + public void addOptionalCharacteristic(TargetRelativeHumidityCharacteristic humidity) { + addCharacteristic(humidity); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/ValveService.java b/src/main/java/io/github/hapjava/services/impl/ValveService.java new file mode 100644 index 000000000..519502a3c --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/ValveService.java @@ -0,0 +1,117 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.ValveAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithDuration; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithIsConfigured; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithRemainingDuration; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithServiceLabelIndex; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithStatusFault; +import io.github.hapjava.characteristics.impl.common.ActiveCharacteristic; +import io.github.hapjava.characteristics.impl.common.InUseCharacteristic; +import io.github.hapjava.characteristics.impl.common.IsConfiguredCharacteristic; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ServiceLabelIndexCharacteristic; +import io.github.hapjava.characteristics.impl.common.StatusFaultCharacteristic; +import io.github.hapjava.characteristics.impl.valve.RemainingDurationCharacteristic; +import io.github.hapjava.characteristics.impl.valve.SetDurationCharacteristic; +import io.github.hapjava.characteristics.impl.valve.ValveTypeCharacteristic; + +/** This service describes accessories valves. */ +public class ValveService extends AbstractServiceImpl { + + public ValveService( + ActiveCharacteristic activeCharacteristic, + InUseCharacteristic inUseCharacteristic, + ValveTypeCharacteristic valveTypeCharacteristic) { + super("000000D0-0000-1000-8000-0026BB765291"); + addCharacteristic(activeCharacteristic); + addCharacteristic(inUseCharacteristic); + addCharacteristic(valveTypeCharacteristic); + } + + public ValveService(ValveAccessory accessory) { + this( + new ActiveCharacteristic( + accessory::getValveActive, + accessory::setValveActive, + accessory::subscribeValveActive, + accessory::unsubscribeValveActive), + new InUseCharacteristic( + accessory::getValveInUse, + accessory::subscribeValveInUse, + accessory::unsubscribeValveInUse), + new ValveTypeCharacteristic( + accessory::getValveType, + accessory::subscribeValveType, + accessory::unsubscribeValveType)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithStatusFault) { + addOptionalCharacteristic( + new StatusFaultCharacteristic( + ((AccessoryWithStatusFault) accessory)::getStatusFault, + ((AccessoryWithStatusFault) accessory)::subscribeStatusFault, + ((AccessoryWithStatusFault) accessory)::unsubscribeStatusFault)); + } + if (accessory instanceof AccessoryWithDuration) { + addOptionalCharacteristic( + new SetDurationCharacteristic( + ((AccessoryWithDuration) accessory).getMinDuration(), + ((AccessoryWithDuration) accessory).getMaxDuration(), + ((AccessoryWithDuration) accessory)::getSetDuration, + ((AccessoryWithDuration) accessory)::setSetDuration, + ((AccessoryWithDuration) accessory)::subscribeSetDuration, + ((AccessoryWithDuration) accessory)::unsubscribeSetDuration)); + } + if (accessory instanceof AccessoryWithRemainingDuration) { + addOptionalCharacteristic( + new RemainingDurationCharacteristic( + ((AccessoryWithRemainingDuration) accessory).getMinRemainingDuration(), + ((AccessoryWithRemainingDuration) accessory).getMaxRemainingDuration(), + ((AccessoryWithRemainingDuration) accessory)::getRemainingDuration, + ((AccessoryWithRemainingDuration) accessory)::subscribeRemainingDuration, + ((AccessoryWithRemainingDuration) accessory)::unsubscribeRemainingDuration)); + } + if (accessory instanceof AccessoryWithIsConfigured) { + addOptionalCharacteristic( + new IsConfiguredCharacteristic( + ((AccessoryWithIsConfigured) accessory)::getIsConfigured, + ((AccessoryWithIsConfigured) accessory)::setIsConfigured, + ((AccessoryWithIsConfigured) accessory)::subscribeIsConfigured, + ((AccessoryWithIsConfigured) accessory)::unsubscribeIsConfigured)); + } + if (accessory instanceof AccessoryWithServiceLabelIndex) { + addOptionalCharacteristic( + new ServiceLabelIndexCharacteristic( + ((AccessoryWithServiceLabelIndex) accessory)::getServiceLabelIndex)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(StatusFaultCharacteristic statusFaultCharacteristic) { + addCharacteristic(statusFaultCharacteristic); + } + + public void addOptionalCharacteristic(SetDurationCharacteristic setDurationCharacteristic) { + addCharacteristic(setDurationCharacteristic); + } + + public void addOptionalCharacteristic( + RemainingDurationCharacteristic remainingDurationCharacteristic) { + addCharacteristic(remainingDurationCharacteristic); + } + + public void addOptionalCharacteristic(IsConfiguredCharacteristic isConfiguredCharacteristic) { + addCharacteristic(isConfiguredCharacteristic); + } + + public void addOptionalCharacteristic( + ServiceLabelIndexCharacteristic serviceLabelIndexCharacteristic) { + addCharacteristic(serviceLabelIndexCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/WindowCoveringService.java b/src/main/java/io/github/hapjava/services/impl/WindowCoveringService.java new file mode 100644 index 000000000..fe483e4c0 --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/WindowCoveringService.java @@ -0,0 +1,135 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.WindowCoveringAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCurrentHorizontalTilting; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithCurrentVerticalTilting; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHoldPosition; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithObstructionDetection; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithTargetHorizontalTilting; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithTargetVerticalTilting; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ObstructionDetectedCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.CurrentHorizontalTiltAngleCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.CurrentPositionCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.CurrentVerticalTiltAngleCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.HoldPositionCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.PositionStateCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.TargetHorizontalTiltAngleCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.TargetPositionCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.TargetVerticalTiltAngleCharacteristic; + +/** This service describes motorized window coverings or shades */ +public class WindowCoveringService extends AbstractServiceImpl { + + public WindowCoveringService( + TargetPositionCharacteristic targetPositionCharacteristic, + CurrentPositionCharacteristic currentPositionCharacteristic, + PositionStateCharacteristic positionStateCharacteristic) { + super("0000008C-0000-1000-8000-0026BB765291"); + addCharacteristic(targetPositionCharacteristic); + addCharacteristic(currentPositionCharacteristic); + addCharacteristic(positionStateCharacteristic); + } + + public WindowCoveringService(WindowCoveringAccessory accessory) { + this( + new TargetPositionCharacteristic( + accessory::getTargetPosition, + accessory::setTargetPosition, + accessory::subscribeTargetPosition, + accessory::unsubscribeTargetPosition), + new CurrentPositionCharacteristic( + accessory::getCurrentPosition, + accessory::subscribeCurrentPosition, + accessory::unsubscribeCurrentPosition), + new PositionStateCharacteristic( + accessory::getPositionState, + accessory::subscribePositionState, + accessory::unsubscribePositionState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithHoldPosition) { + addOptionalCharacteristic( + new HoldPositionCharacteristic(((AccessoryWithHoldPosition) accessory)::setHoldPosition)); + } + + if (accessory instanceof AccessoryWithObstructionDetection) { + addOptionalCharacteristic( + new ObstructionDetectedCharacteristic( + ((AccessoryWithObstructionDetection) accessory)::getObstructionDetected, + ((AccessoryWithObstructionDetection) accessory)::subscribeObstructionDetected, + ((AccessoryWithObstructionDetection) accessory)::unsubscribeObstructionDetected)); + } + if (accessory instanceof AccessoryWithCurrentHorizontalTilting) { + addOptionalCharacteristic( + new CurrentHorizontalTiltAngleCharacteristic( + ((AccessoryWithCurrentHorizontalTilting) accessory)::getCurrentHorizontalTiltAngle, + ((AccessoryWithCurrentHorizontalTilting) accessory) + ::subscribeCurrentHorizontalTiltAngle, + ((AccessoryWithCurrentHorizontalTilting) accessory) + ::unsubscribeCurrentHorizontalTiltAngle)); + } + if (accessory instanceof AccessoryWithTargetHorizontalTilting) { + addOptionalCharacteristic( + new TargetHorizontalTiltAngleCharacteristic( + ((AccessoryWithTargetHorizontalTilting) accessory)::getTargetHorizontalTiltAngle, + ((AccessoryWithTargetHorizontalTilting) accessory)::setTargetHorizontalTiltAngle, + ((AccessoryWithTargetHorizontalTilting) accessory) + ::subscribeTargetHorizontalTiltAngle, + ((AccessoryWithTargetHorizontalTilting) accessory) + ::unsubscribeTargetHorizontalTiltAngle)); + } + if (accessory instanceof AccessoryWithCurrentVerticalTilting) { + addOptionalCharacteristic( + new CurrentVerticalTiltAngleCharacteristic( + ((AccessoryWithCurrentVerticalTilting) accessory)::getCurrentVerticalTiltAngle, + ((AccessoryWithCurrentVerticalTilting) accessory)::subscribeCurrentVerticalTiltAngle, + ((AccessoryWithCurrentVerticalTilting) accessory) + ::unsubscribeCurrentVerticalTiltAngle)); + } + if (accessory instanceof AccessoryWithTargetVerticalTilting) { + addOptionalCharacteristic( + new TargetVerticalTiltAngleCharacteristic( + ((AccessoryWithTargetVerticalTilting) accessory)::getTargetVerticalTiltAngle, + ((AccessoryWithTargetVerticalTilting) accessory)::setTargetVerticalTiltAngle, + ((AccessoryWithTargetVerticalTilting) accessory)::subscribeTargetVerticalTiltAngle, + ((AccessoryWithTargetVerticalTilting) accessory) + ::unsubscribeTargetVerticalTiltAngle)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(HoldPositionCharacteristic holdPositionCharacteristic) { + addCharacteristic(holdPositionCharacteristic); + } + + public void addOptionalCharacteristic( + ObstructionDetectedCharacteristic obstructionDetectedCharacteristic) { + addCharacteristic(obstructionDetectedCharacteristic); + } + + public void addOptionalCharacteristic( + CurrentHorizontalTiltAngleCharacteristic currentHorizontalTiltAngleCharacteristic) { + addCharacteristic(currentHorizontalTiltAngleCharacteristic); + } + + public void addOptionalCharacteristic( + TargetHorizontalTiltAngleCharacteristic targetHorizontalTiltAngleCharacteristic) { + addCharacteristic(targetHorizontalTiltAngleCharacteristic); + } + + public void addOptionalCharacteristic( + CurrentVerticalTiltAngleCharacteristic currentVerticalTiltAngleCharacteristic) { + addCharacteristic(currentVerticalTiltAngleCharacteristic); + } + + public void addOptionalCharacteristic( + TargetVerticalTiltAngleCharacteristic targetVerticalTiltAngleCharacteristic) { + addCharacteristic(targetVerticalTiltAngleCharacteristic); + } +} diff --git a/src/main/java/io/github/hapjava/services/impl/WindowService.java b/src/main/java/io/github/hapjava/services/impl/WindowService.java new file mode 100644 index 000000000..e7f2e775d --- /dev/null +++ b/src/main/java/io/github/hapjava/services/impl/WindowService.java @@ -0,0 +1,71 @@ +package io.github.hapjava.services.impl; + +import io.github.hapjava.accessories.WindowAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHoldPosition; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithObstructionDetection; +import io.github.hapjava.characteristics.impl.common.NameCharacteristic; +import io.github.hapjava.characteristics.impl.common.ObstructionDetectedCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.CurrentPositionCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.HoldPositionCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.PositionStateCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.TargetPositionCharacteristic; + +/** This service describes a motorized window. */ +public class WindowService extends AbstractServiceImpl { + + public WindowService( + CurrentPositionCharacteristic currentPositionCharacteristic, + TargetPositionCharacteristic targetPositionCharacteristic, + PositionStateCharacteristic positionStateCharacteristic) { + super("0000008B-0000-1000-8000-0026BB765291"); + addCharacteristic(currentPositionCharacteristic); + addCharacteristic(targetPositionCharacteristic); + addCharacteristic(positionStateCharacteristic); + } + + public WindowService(WindowAccessory accessory) { + this( + new CurrentPositionCharacteristic( + accessory::getCurrentPosition, + accessory::subscribeCurrentPosition, + accessory::unsubscribeCurrentPosition), + new TargetPositionCharacteristic( + accessory::getTargetPosition, + accessory::setTargetPosition, + accessory::subscribeTargetPosition, + accessory::unsubscribeTargetPosition), + new PositionStateCharacteristic( + accessory::getPositionState, + accessory::subscribePositionState, + accessory::unsubscribePositionState)); + if (accessory instanceof AccessoryWithName) { + addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName)); + } + if (accessory instanceof AccessoryWithHoldPosition) { + addOptionalCharacteristic( + new HoldPositionCharacteristic(((AccessoryWithHoldPosition) accessory)::setHoldPosition)); + } + + if (accessory instanceof AccessoryWithObstructionDetection) { + addOptionalCharacteristic( + new ObstructionDetectedCharacteristic( + ((AccessoryWithObstructionDetection) accessory)::getObstructionDetected, + ((AccessoryWithObstructionDetection) accessory)::subscribeObstructionDetected, + ((AccessoryWithObstructionDetection) accessory)::unsubscribeObstructionDetected)); + } + } + + public void addOptionalCharacteristic(NameCharacteristic name) { + addCharacteristic(name); + } + + public void addOptionalCharacteristic(HoldPositionCharacteristic holdPositionCharacteristic) { + addCharacteristic(holdPositionCharacteristic); + } + + public void addOptionalCharacteristic( + ObstructionDetectedCharacteristic obstructionDetectedCharacteristic) { + addCharacteristic(obstructionDetectedCharacteristic); + } +} diff --git a/src/test/java/io/github/hapjava/characteristics/impl/CustomTiltAngleRangeTest.java b/src/test/java/io/github/hapjava/characteristics/impl/CustomTiltAngleRangeTest.java new file mode 100644 index 000000000..d3cd51756 --- /dev/null +++ b/src/test/java/io/github/hapjava/characteristics/impl/CustomTiltAngleRangeTest.java @@ -0,0 +1,78 @@ +package io.github.hapjava.characteristics.impl; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.impl.windowcovering.CurrentHorizontalTiltAngleCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.CurrentVerticalTiltAngleCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.TargetHorizontalTiltAngleCharacteristic; +import io.github.hapjava.characteristics.impl.windowcovering.TargetVerticalTiltAngleCharacteristic; +import java.util.Arrays; +import java.util.concurrent.CompletableFuture; +import javax.json.JsonObject; +import org.junit.Test; + +/** Custom tilt angle ranges, see https://github.com/hap-java/HAP-Java/issues/162 */ +public class CustomTiltAngleRangeTest { + + @Test + public void defaultConstructorsKeepTheirSerializedOutput() { + // Serialized output captured before custom ranges were added. + for (Case c : + Arrays.asList( + Case.of( + new CurrentHorizontalTiltAngleCharacteristic( + () -> CompletableFuture.completedFuture(50), cb -> {}, () -> {}), + "{\"iid\":7,\"type\":\"6C\",\"perms\":[\"pr\",\"ev\"],\"format\":\"int\",\"value\":50,\"minValue\":-90,\"maxValue\":90,\"minStep\":1,\"unit\":\"arcdegrees\"}"), + Case.of( + new TargetHorizontalTiltAngleCharacteristic( + () -> CompletableFuture.completedFuture(50), v -> {}, cb -> {}, () -> {}), + "{\"iid\":7,\"type\":\"7B\",\"perms\":[\"pr\",\"pw\",\"ev\"],\"format\":\"int\",\"value\":50,\"minValue\":-90,\"maxValue\":90,\"minStep\":1,\"unit\":\"arcdegrees\"}"), + Case.of( + new CurrentVerticalTiltAngleCharacteristic( + () -> CompletableFuture.completedFuture(50), cb -> {}, () -> {}), + "{\"iid\":7,\"type\":\"6E\",\"perms\":[\"pr\",\"ev\"],\"format\":\"int\",\"value\":50,\"minValue\":-90,\"maxValue\":90,\"minStep\":1,\"unit\":\"arcdegrees\"}"), + Case.of( + new TargetVerticalTiltAngleCharacteristic( + () -> CompletableFuture.completedFuture(50), v -> {}, cb -> {}, () -> {}), + "{\"iid\":7,\"type\":\"7D\",\"perms\":[\"pr\",\"pw\",\"ev\"],\"format\":\"int\",\"value\":50,\"minValue\":-90,\"maxValue\":90,\"minStep\":1,\"unit\":\"arcdegrees\"}"))) { + assertThat(c.characteristic.toJson(7).join().toString()) + .as(c.characteristic.getClass().getSimpleName()) + .isEqualTo(c.expected); + } + } + + @Test + public void customRangeIsAdvertised() { + for (Characteristic c : + Arrays.asList( + new CurrentHorizontalTiltAngleCharacteristic( + 0, 90, () -> CompletableFuture.completedFuture(50), cb -> {}, () -> {}), + new TargetHorizontalTiltAngleCharacteristic( + 0, 90, () -> CompletableFuture.completedFuture(50), v -> {}, cb -> {}, () -> {}), + new CurrentVerticalTiltAngleCharacteristic( + 0, 90, () -> CompletableFuture.completedFuture(50), cb -> {}, () -> {}), + new TargetVerticalTiltAngleCharacteristic( + 0, 90, () -> CompletableFuture.completedFuture(50), v -> {}, cb -> {}, () -> {}))) { + JsonObject json = c.toJson(7).join(); + String name = c.getClass().getSimpleName(); + assertThat(json.getInt("minValue")).as(name).isEqualTo(0); + assertThat(json.getInt("maxValue")).as(name).isEqualTo(90); + assertThat(json.getInt("minStep")).as(name).isEqualTo(1); + } + } + + private static class Case { + final Characteristic characteristic; + final String expected; + + private Case(Characteristic characteristic, String expected) { + this.characteristic = characteristic; + this.expected = expected; + } + + static Case of(Characteristic characteristic, String expected) { + return new Case(characteristic, expected); + } + } +} diff --git a/src/test/java/io/github/hapjava/characteristics/impl/valve/DurationCharacteristicFormatTest.java b/src/test/java/io/github/hapjava/characteristics/impl/valve/DurationCharacteristicFormatTest.java new file mode 100644 index 000000000..2e12b2daa --- /dev/null +++ b/src/test/java/io/github/hapjava/characteristics/impl/valve/DurationCharacteristicFormatTest.java @@ -0,0 +1,56 @@ +package io.github.hapjava.characteristics.impl.valve; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.github.hapjava.characteristics.impl.windowcovering.CurrentPositionCharacteristic; +import java.util.concurrent.CompletableFuture; +import javax.json.JsonObject; +import org.junit.Test; + +/** Regression tests for https://github.com/hap-java/HAP-Java/issues/202 */ +public class DurationCharacteristicFormatTest { + + @Test + public void setDurationAdvertisesUint32() { + SetDurationCharacteristic characteristic = + new SetDurationCharacteristic( + () -> CompletableFuture.completedFuture(300), value -> {}, callback -> {}, () -> {}); + + JsonObject json = characteristic.toJson(12).join(); + + assertThat(json.getString("type")).isEqualTo("D3"); + assertThat(json.getString("format")).isEqualTo("uint32"); + assertThat(json.getInt("value")).isEqualTo(300); + assertThat(json.getInt("minValue")).isEqualTo(0); + assertThat(json.getInt("maxValue")).isEqualTo(3600); + assertThat(json.getInt("minStep")).isEqualTo(1); + assertThat(json.getString("unit")).isEqualTo("s"); + } + + @Test + public void remainingDurationAdvertisesUint32() { + RemainingDurationCharacteristic characteristic = + new RemainingDurationCharacteristic( + () -> CompletableFuture.completedFuture(180), callback -> {}, () -> {}); + + JsonObject json = characteristic.toJson(13).join(); + + assertThat(json.getString("type")).isEqualTo("D4"); + assertThat(json.getString("format")).isEqualTo("uint32"); + assertThat(json.getInt("value")).isEqualTo(180); + assertThat(json.getInt("minValue")).isEqualTo(0); + assertThat(json.getInt("maxValue")).isEqualTo(3600); + assertThat(json.getString("unit")).isEqualTo("s"); + } + + @Test + public void otherIntegerCharacteristicsKeepIntFormat() { + CurrentPositionCharacteristic characteristic = + new CurrentPositionCharacteristic( + () -> CompletableFuture.completedFuture(50), callback -> {}, () -> {}); + + JsonObject json = characteristic.toJson(14).join(); + + assertThat(json.getString("format")).isEqualTo("int"); + } +} diff --git a/src/test/java/com/github/hapjava/HomekitRootTest.java b/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java similarity index 68% rename from src/test/java/com/github/hapjava/HomekitRootTest.java rename to src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java index 226e80d4a..81d2666e5 100644 --- a/src/test/java/com/github/hapjava/HomekitRootTest.java +++ b/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java @@ -1,14 +1,22 @@ -package io.github.hapjava; +package io.github.hapjava.server.impl; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import io.github.hapjava.impl.HomekitWebHandler; -import io.github.hapjava.impl.http.HomekitClientConnectionFactory; -import io.github.hapjava.impl.jmdns.JmdnsHomekitAdvertiser; +import io.github.hapjava.accessories.HomekitAccessory; +import io.github.hapjava.server.HomekitAccessoryCategories; +import io.github.hapjava.server.HomekitAuthInfo; +import io.github.hapjava.server.HomekitWebHandler; +import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory; +import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser; import java.util.concurrent.CompletableFuture; -import org.junit.*; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; public class HomekitRootTest { @@ -19,6 +27,8 @@ public class HomekitRootTest { private HomekitAuthInfo authInfo; private static final int PORT = 12345; + private static final String SETUPID = "Gx12"; + private static final String LABEL = "Test Label"; @Before @@ -29,7 +39,8 @@ public void setup() throws Exception { when(webHandler.start(any())).thenReturn(CompletableFuture.completedFuture(PORT)); advertiser = mock(JmdnsHomekitAdvertiser.class); authInfo = mock(HomekitAuthInfo.class); - root = new HomekitRoot(LABEL, webHandler, authInfo, advertiser); + root = + new HomekitRoot(LABEL, HomekitAccessoryCategories.OTHER, webHandler, authInfo, advertiser); } @Test @@ -64,10 +75,12 @@ public void testWebHandlerStops() throws Exception { @Test public void testAdvertiserStarts() throws Exception { - String mac = "00:00:00:00:00:00"; + final String mac = "00:00:00:00:00:00"; when(authInfo.getMac()).thenReturn(mac); + when(authInfo.getSetupId()).thenReturn(SETUPID); + root.start(); - verify(advertiser).advertise(eq(LABEL), eq(mac), eq(PORT), eq(1)); + verify(advertiser).advertise(eq(LABEL), eq(1), eq(mac), eq(PORT), eq(1), eq(SETUPID)); } @Test @@ -78,20 +91,18 @@ public void testAdvertiserStops() throws Exception { } @Test - public void testAddAccessoryResetsWeb() { + public void testAddAccessoryDoesntResetWeb() { root.start(); - verify(webHandler, never()).resetConnections(); root.addAccessory(accessory); - verify(webHandler).resetConnections(); + verify(webHandler, never()).resetConnections(); } @Test - public void testRemoveAccessoryResetsWeb() { + public void testRemoveAccessoryDoesntResetWeb() { root.addAccessory(accessory); root.start(); - verify(webHandler, never()).resetConnections(); root.removeAccessory(accessory); - verify(webHandler).resetConnections(); + verify(webHandler, never()).resetConnections(); } @Test(expected = IndexOutOfBoundsException.class) diff --git a/src/test/java/io/github/hapjava/server/impl/connections/LengthPrefixedByteArrayProcessorTest.java b/src/test/java/io/github/hapjava/server/impl/connections/LengthPrefixedByteArrayProcessorTest.java new file mode 100644 index 000000000..9e839848d --- /dev/null +++ b/src/test/java/io/github/hapjava/server/impl/connections/LengthPrefixedByteArrayProcessorTest.java @@ -0,0 +1,125 @@ +package io.github.hapjava.server.impl.connections; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import org.junit.Test; + +public class LengthPrefixedByteArrayProcessorTest { + + private static final int TAG_LENGTH = 16; + + /** + * Builds a frame as it arrives on the wire: 2-byte little-endian payload length, payload, 16-byte + * tag. The payload and tag bytes start at 0x80 so that they never look like a short length. + */ + private static byte[] frame(int payloadLength, int seed) { + byte[] frame = new byte[2 + payloadLength + TAG_LENGTH]; + frame[0] = (byte) (payloadLength & 0xFF); + frame[1] = (byte) ((payloadLength >> 8) & 0xFF); + for (int i = 2; i < frame.length; i++) { + frame[i] = (byte) (0x80 + seed + i); + } + return frame; + } + + /** What the processor is expected to emit for a frame: payload + tag, without the length. */ + private static byte[] body(byte[] frame) { + return Arrays.copyOfRange(frame, 2, frame.length); + } + + private static byte[] concat(byte[]... parts) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] part : parts) { + out.write(part, 0, part.length); + } + return out.toByteArray(); + } + + private static List feed(LengthPrefixedByteArrayProcessor processor, byte[]... reads) { + List results = new ArrayList<>(); + for (byte[] read : reads) { + results.addAll(processor.handle(read)); + } + return results; + } + + private static List sizes(Collection results) { + List sizes = new ArrayList<>(); + for (byte[] result : results) { + sizes.add(result.length); + } + return sizes; + } + + private static void assertBodies(List results, byte[]... frames) { + List expectedSizes = new ArrayList<>(); + for (byte[] frame : frames) { + expectedSizes.add(frame.length - 2); + } + assertThat(sizes(results)).isEqualTo(expectedSizes); + for (int i = 0; i < frames.length; i++) { + assertThat(results.get(i)).as("frame %d", i).isEqualTo(body(frames[i])); + } + } + + @Test + public void singleFrameInOneRead() { + byte[] a = frame(100, 1); + assertBodies(feed(new LengthPrefixedByteArrayProcessor(), a), a); + } + + @Test + public void threeFramesInOneRead() { + byte[] a = frame(1024, 1); + byte[] b = frame(1024, 2); + byte[] c = frame(200, 3); + assertBodies(feed(new LengthPrefixedByteArrayProcessor(), concat(a, b, c)), a, b, c); + } + + @Test + public void frameSplitAcrossTwoReads() { + byte[] a = frame(1024, 1); + int[] offsets = {1, 2, 3, 10, 18, 19, 20, 500, a.length - 1}; + for (int offset : offsets) { + byte[] first = Arrays.copyOfRange(a, 0, offset); + byte[] second = Arrays.copyOfRange(a, offset, a.length); + List results = feed(new LengthPrefixedByteArrayProcessor(), first, second); + assertThat(sizes(results)).as("split at %d", offset).containsExactly(a.length - 2); + assertThat(results.get(0)).as("split at %d", offset).isEqualTo(body(a)); + } + } + + @Test + public void frameSplitWithNextFrameInSecondRead() { + byte[] a = frame(1024, 1); + byte[] b = frame(200, 2); + byte[] first = Arrays.copyOfRange(a, 0, 500); + byte[] second = concat(Arrays.copyOfRange(a, 500, a.length), b); + assertBodies(feed(new LengthPrefixedByteArrayProcessor(), first, second), a, b); + } + + @Test + public void shortFrameFollowedByLongerFrameInOneRead() { + byte[] a = frame(5, 1); + byte[] b = frame(100, 2); + List results = feed(new LengthPrefixedByteArrayProcessor(), concat(a, b)); + assertThat(sizes(results)).containsExactly(21, 116); + assertBodies(results, a, b); + } + + @Test + public void singleLengthByteThenRestThenAnotherFrame() { + byte[] a = frame(5, 1); + byte[] b = frame(40, 2); + byte[] first = Arrays.copyOfRange(a, 0, 1); + byte[] second = concat(Arrays.copyOfRange(a, 1, a.length), b); + List results = feed(new LengthPrefixedByteArrayProcessor(), first, second); + assertThat(sizes(results)).containsExactly(21, 56); + assertBodies(results, a, b); + } +} diff --git a/src/test/java/io/github/hapjava/server/impl/jmdns/JmdnsHomekitAdvertiserTest.java b/src/test/java/io/github/hapjava/server/impl/jmdns/JmdnsHomekitAdvertiserTest.java new file mode 100644 index 000000000..731be498f --- /dev/null +++ b/src/test/java/io/github/hapjava/server/impl/jmdns/JmdnsHomekitAdvertiserTest.java @@ -0,0 +1,91 @@ +package io.github.hapjava.server.impl.jmdns; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.net.UnknownHostException; +import javax.jmdns.JmDNS; +import javax.jmdns.ServiceInfo; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +public class JmdnsHomekitAdvertiserTest { + + JmdnsHomekitAdvertiser subject; + JmDNS jmdns; + + @Before + public void setup() throws UnknownHostException, IOException { + jmdns = mock(JmDNS.class); + subject = new JmdnsHomekitAdvertiser(jmdns); + } + + @Test + public void testAdvertiseTwiceFails() throws Exception { + advertise(); + assertThatThrownBy(() -> advertise()).isNotNull(); + } + + /* + * Verify that the unregister call is for the initial registered service + * when changing discoverability causes advertising to be toggled. + */ + @Test + public void testSetDiscoverableAfterAdvertise() throws Exception { + subject.setDiscoverable(false); + advertise(); + subject.setDiscoverable(true); + assertThat(getArgumentFromUnregister().getPropertyString("sf")).isEqualTo("0"); + } + + /* + * Verify that the unregister call is for the initial registered service + * when changing the config index causes advertising to be toggled. + */ + @Test + public void testSetConfigurationIndex() throws Exception { + subject.setConfigurationIndex(1); + advertise(); + subject.setConfigurationIndex(2); + assertThat(getArgumentFromUnregister().getPropertyString("c#")).isEqualTo("1"); + } + + @Test + public void testStopClosesOwnedJmdns() throws Exception { + subject = new JmdnsHomekitAdvertiser(jmdns, true); + advertise(); + subject.stop(); + verify(jmdns).close(); + } + + @Test + public void testStopDoesNotCloseSuppliedJmdns() throws Exception { + advertise(); + subject.stop(); + verify(jmdns, never()).close(); + } + + @Test + public void testSetDiscoverableAfterStopDoesNotRegister() throws Exception { + advertise(); + subject.stop(); + subject.setDiscoverable(false); + verify(jmdns).registerService(any(ServiceInfo.class)); + } + + private ServiceInfo getArgumentFromUnregister() { + ArgumentCaptor serviceInfoCaptor = ArgumentCaptor.forClass(ServiceInfo.class); + verify(jmdns).unregisterService(serviceInfoCaptor.capture()); + return serviceInfoCaptor.getValue(); + } + + private void advertise() throws Exception { + subject.advertise("test", 1, "00:00:00:00:00:00", 1234, 1, "1"); + } +} diff --git a/src/test/java/io/github/hapjava/services/impl/DoorbellServiceTest.java b/src/test/java/io/github/hapjava/services/impl/DoorbellServiceTest.java new file mode 100644 index 000000000..feb67b94c --- /dev/null +++ b/src/test/java/io/github/hapjava/services/impl/DoorbellServiceTest.java @@ -0,0 +1,51 @@ +package io.github.hapjava.services.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +import io.github.hapjava.accessories.DoorbellAccessory; +import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithMute; +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.impl.audio.MuteCharacteristic; +import io.github.hapjava.characteristics.impl.common.ProgrammableSwitchEventCharacteristic; +import java.util.concurrent.CompletableFuture; +import javax.json.JsonObject; +import javax.json.JsonValue; +import org.junit.Test; + +public class DoorbellServiceTest { + + @Test + public void doorbellWithoutOptionalsOnlyHasSwitchEvent() { + DoorbellService service = new DoorbellService(mock(DoorbellAccessory.class)); + + assertThat(service.getType()).isEqualTo("00000121-0000-1000-8000-0026BB765291"); + assertThat(service.getCharacteristics()) + .hasExactlyElementsOfTypes(ProgrammableSwitchEventCharacteristic.class); + } + + @Test + public void doorbellWithMuteHasMuteCharacteristic() throws Exception { + DoorbellAccessory accessory = + mock(DoorbellAccessory.class, withSettings().extraInterfaces(AccessoryWithMute.class)); + when(((AccessoryWithMute) accessory).isMuted()) + .thenReturn(CompletableFuture.completedFuture(true)); + + DoorbellService service = new DoorbellService(accessory); + + assertThat(service.getCharacteristics()) + .hasExactlyElementsOfTypes( + ProgrammableSwitchEventCharacteristic.class, MuteCharacteristic.class); + + Characteristic mute = service.getCharacteristics().get(1); + JsonObject json = mute.toJson(2).join(); + assertThat(json.getString("type")).isEqualTo("11A"); + assertThat(json.getBoolean("value")).isTrue(); + + mute.setValue(JsonValue.FALSE); + verify((AccessoryWithMute) accessory).setMute(false); + } +}