├── .DS_Store ├── README.md └── custom_components ├── .gitignore ├── dawon ├── Dawon.jar └── dawon │ ├── build.gradle │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle │ └── src │ └── main │ └── java │ └── com │ └── stkang90 │ └── Main.java ├── enertalk ├── __init__.py ├── api.py ├── config_flow.py ├── const.py ├── manifest.json ├── sensor.py ├── strings.json └── translations │ ├── en.json │ └── ko.json └── sk_weather ├── manifest.json └── sensor.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stkang/home-assistant-custom-component/2ec2503d3befb36702d4916eedb62df43d55034f/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HomeAssistant Custom Component 2 | 3 | * HomeAssistant 0.110.7 버전에서 테스트 완료되었습니다. 4 | 5 | ## ~~Enertalk (에너톡)~~ 6 | 7 | 8 | ## AirKorea 공기오염정보료 9 | https://github.com/stkang/ha-component-air-korea 10 | 11 | ## 귀뚜라미 IOT 보일러 12 | https://github.com/stkang/ha-component-kiturami 13 | 14 | ## 동행복권: 로또 6/45 15 | https://github.com/stkang/ha-component-dh-lottery 16 | 17 | ## 샤오미 제습기 18 | https://github.com/stkang/ha-component-xiaomi-dh 19 | 20 | ## 현대HT: Imazu Wall Pad 21 | https://github.com/stkang/ha-component-imazu-wall-pad 22 | 23 | ## ~~SK 날씨정보(지원 종료)~~ 24 | 25 | 26 | **네이버 페이 후원하기** 27 | - http://npay.to/975894e97ffd4b1f3c4a 28 | -------------------------------------------------------------------------------- /custom_components/.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /custom_components/dawon/Dawon.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stkang/home-assistant-custom-component/2ec2503d3befb36702d4916eedb62df43d55034f/custom_components/dawon/Dawon.jar -------------------------------------------------------------------------------- /custom_components/dawon/dawon/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'application' 4 | } 5 | 6 | group 'com.stkang90' 7 | mainClassName = 'com.stkang90.Main' 8 | sourceCompatibility = 1.8 9 | version = '1.0' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | jar { 16 | manifest { 17 | attributes 'Title': 'Dawon Dns Local Tool', 'Main-Class': mainClassName 18 | } 19 | archiveName 'Dawon.jar' 20 | dependsOn configurations.runtime 21 | from { 22 | configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } 23 | } 24 | } 25 | 26 | dependencies { 27 | testCompile group: 'junit', name: 'junit', version: '4.12' 28 | } 29 | -------------------------------------------------------------------------------- /custom_components/dawon/dawon/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /custom_components/dawon/dawon/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /custom_components/dawon/dawon/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'dawon' 2 | 3 | -------------------------------------------------------------------------------- /custom_components/dawon/dawon/src/main/java/com/stkang90/Main.java: -------------------------------------------------------------------------------- 1 | package com.stkang90; 2 | 3 | import java.io.DataOutputStream; 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | import java.net.InetSocketAddress; 7 | import java.net.Socket; 8 | import java.net.SocketAddress; 9 | import java.net.SocketException; 10 | import java.util.Scanner; 11 | 12 | public class Main { 13 | private static String wifiName = null; 14 | private static String wifiPasswd = null; 15 | 16 | private static String mqttIp = null; 17 | private static Integer mqttPort = 1883; 18 | private static String mqttPasswd = null; 19 | 20 | private static String deviceIp = "192.168.43.1"; 21 | private static int devicePort = 5000; 22 | 23 | private static String deviceModelName = "B540-WF"; 24 | private static String deviceModel = "B5X"; 25 | 26 | private static Scanner sc; 27 | 28 | public static void main(String[] args) { 29 | System.out.println("###############################################"); 30 | System.out.println("######### [Dawon Dns 스마트 플러그 설정 툴] #########"); 31 | System.out.println("###############################################"); 32 | System.out.println("## 테스트 성공 모델: Smart Plug(B530-WF/B540-WF), Smart Solar Power Generation Plug(B400-W) ##"); 33 | System.out.println(); 34 | 35 | sc = new Scanner(System.in); 36 | boolean result = false; 37 | while (!result) { 38 | if (!inputInfoData()) { 39 | return; 40 | } 41 | System.out.println(); 42 | result = checkInfoData(); 43 | } 44 | sc.close(); 45 | 46 | System.out.println("설정 완료"); 47 | System.out.println(""); 48 | 49 | 50 | System.out.println("연결 시도 중입니다."); 51 | SocketAddress socketAddress = new InetSocketAddress(deviceIp, devicePort); 52 | Socket socket = new Socket(); 53 | try { 54 | socket.setSoTimeout(5000); 55 | socket.connect(socketAddress, 5000); 56 | 57 | System.out.println("연결 성공"); 58 | DataOutputStream bufferedWriter = new DataOutputStream(socket.getOutputStream()); 59 | 60 | String dataFormat = "{\"server_addr\":\"%s\",\"server_port\":\"%d\",\"ssl_support\":\"no\",\"ssid\":\"%s\",\"pass\":\"%s\",\"mqtt_key\":\"%s\",\"company\":\"DAWONDNS\",\"model\":\"%s\",\"topic\":\"dwd\"}"; 61 | String sendData = String.format(dataFormat, mqttIp, mqttPort, wifiName, wifiPasswd, mqttPasswd, deviceModel); 62 | System.out.println("SendData: " + sendData); 63 | 64 | (new PrintWriter(bufferedWriter, true)).println(sendData); 65 | System.out.println("#### 성공 ####"); 66 | 67 | } catch (SocketException e) { 68 | System.out.println("#### 실패 ####"); 69 | e.printStackTrace(); 70 | } catch (IOException e) { 71 | System.out.println("#### 실패 ####"); 72 | e.printStackTrace(); 73 | } finally { 74 | try { 75 | socket.close(); 76 | } catch (IOException e) { 77 | e.printStackTrace(); 78 | } 79 | } 80 | } 81 | 82 | private static boolean inputInfoData() { 83 | System.out.println("######### [WIFI 설정] #########"); 84 | System.out.println("WIFI 이름을 입력하세요."); 85 | wifiName = sc.next(); 86 | if (wifiName == null || wifiName.length() == 0) { 87 | System.out.println("[오류] - WIFI 이름 미입력"); 88 | return false; 89 | } 90 | 91 | System.out.println("WIFI 비밀번호을 입력하세요. (8자리 이상)"); 92 | wifiPasswd = sc.next(); 93 | if (wifiPasswd == null || wifiPasswd.length() < 8) { 94 | System.out.println("[오류] - WIFI 비밀번호 미입력 또는 8자리 미만"); 95 | return false; 96 | } 97 | System.out.println("##############################"); 98 | System.out.println(); 99 | 100 | System.out.println("######### [MQTT 설정] #########"); 101 | System.out.println("MQTT 서버 주소(IP or Domain)를 입력하세요"); 102 | mqttIp = sc.next(); 103 | if (mqttIp == null || mqttIp.length() == 0) { 104 | System.out.println("[오류] - MQTT 서버 주소 미입력"); 105 | return false; 106 | } 107 | 108 | System.out.println("MQTT 서버 포트를 입력하세요. (기본값: 1883)"); 109 | mqttPort = sc.nextInt(); 110 | if (mqttPort == 0) { 111 | mqttPort = 1883; 112 | } 113 | if (mqttPort <= 0 || mqttPort > 65535) { 114 | System.out.println("[오류] - MQTT 서버 포트 미입력 또는 포트 가용 범위가 아님."); 115 | return false; 116 | } 117 | System.out.println("MQTT 서버 비밀번호를 입력하세요. (1234 입력 권장)"); 118 | mqttPasswd = sc.next(); 119 | 120 | System.out.println("##############################"); 121 | System.out.println(); 122 | 123 | System.out.println("#### [디바이스(스마트 플러그) 설정] ###"); 124 | System.out.println("디바이스 모델명를 입력하세요. (기본값: B540-WF) 지원 모델: B530-WF/B540-WF/B400-W"); 125 | deviceModelName = sc.next(); 126 | if (deviceModelName == null || deviceModelName.length() == 0) { 127 | deviceModelName = "B540-WF"; 128 | } 129 | if (deviceModelName.equalsIgnoreCase("B540-WF") || deviceModelName.equalsIgnoreCase("B530-WF")) { 130 | deviceModel = "B5X"; 131 | } else if (deviceModelName.equalsIgnoreCase("B400-W")) { 132 | deviceModel = "B400_SW"; 133 | } else { 134 | System.out.println("[오류] - 지원하지 않는 디바이스 모델 입니다."); 135 | return false; 136 | } 137 | 138 | System.out.println("디바이스 주소(IP)를 입력하세요. (IPv4) (기본값: " + deviceIp + ")"); 139 | deviceIp = sc.next(); 140 | if (deviceIp == null || deviceIp.length() == 0) { 141 | deviceIp = "192.168.43.1"; 142 | } 143 | if (!isValidInet4Address(deviceIp)) { 144 | System.out.println("[오류] - 디바이스 주소 미입력 또는 IPv4 형식이 아님"); 145 | return false; 146 | } 147 | 148 | System.out.println("디바이스 포트를 입력하세요. (기본값: 5000)"); 149 | devicePort = sc.nextInt(); 150 | if (devicePort == 0) { 151 | devicePort = 5000; 152 | } 153 | if (devicePort <= 0 || devicePort > 65535) { 154 | System.out.println("[오류] - 디바이스 포트 미입력 또는 포트 가용 범위가 아님."); 155 | return false; 156 | } 157 | return true; 158 | } 159 | 160 | private static boolean checkInfoData() { 161 | System.out.println("########## [설정 확인] #########"); 162 | System.out.println(String.format("WIFI 이름: %s", wifiName)); 163 | System.out.println(String.format("WIFI 비밀번호: %s", wifiPasswd)); 164 | System.out.println(String.format("MQTT IP: %s", mqttIp)); 165 | System.out.println(String.format("MQTT 포트: %d", mqttPort)); 166 | System.out.println(String.format("MQTT 비밀번호: %s", mqttPasswd)); 167 | System.out.println(String.format("디바이스 모델명: %s (%s)", deviceModelName, deviceModel)); 168 | System.out.println(String.format("디바이스 IP: %s", deviceIp)); 169 | System.out.println(String.format("디바이스 포트: %d", devicePort)); 170 | System.out.println(); 171 | 172 | System.out.println("위 설정이 맞습니까? (y/n)"); 173 | String result = ""; 174 | while (result == null || result.length() == 0 || !(result.equalsIgnoreCase("Y") || result.equalsIgnoreCase("N"))) { 175 | result = sc.next(); 176 | } 177 | return result.equalsIgnoreCase("Y"); 178 | } 179 | 180 | public static boolean isValidInet4Address(String inet4Address) { 181 | if (inet4Address == null || inet4Address.length() == 0) { 182 | return false; 183 | } 184 | String[] groups = inet4Address.split("\\."); 185 | if (groups.length != 4) { 186 | return false; 187 | } 188 | 189 | // verify that address subgroups are legal 190 | for (String ipSegment : groups) { 191 | if (ipSegment == null || ipSegment.length() == 0) { 192 | return false; 193 | } 194 | int iIpSegment = 0; 195 | try { 196 | iIpSegment = Integer.parseInt(ipSegment); 197 | } catch (NumberFormatException e) { 198 | return false; 199 | } 200 | if (iIpSegment > 255) { 201 | return false; 202 | } 203 | if (ipSegment.length() > 1 && ipSegment.startsWith("0")) { 204 | return false; 205 | } 206 | } 207 | return true; 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /custom_components/enertalk/__init__.py: -------------------------------------------------------------------------------- 1 | """The Enertalk integration.""" 2 | import asyncio 3 | import logging 4 | 5 | import voluptuous as vol 6 | 7 | from datetime import timedelta 8 | 9 | from homeassistant.config_entries import ConfigEntry 10 | from homeassistant.const import ( 11 | CONF_CLIENT_ID, 12 | CONF_CLIENT_SECRET, 13 | ) 14 | from homeassistant.const import CONF_MONITORED_CONDITIONS 15 | from homeassistant.core import HomeAssistant 16 | from homeassistant.helpers import config_entry_oauth2_flow, \ 17 | config_validation as cv 18 | 19 | from . import api, config_flow 20 | from .const import ( 21 | AUTH, 22 | MONITORED_CONDITIONS, 23 | CONF_REAL_TIME_INTERVAL, 24 | CONF_BILLING_INTERVAL, 25 | DATA_CONF, 26 | DOMAIN, 27 | OAUTH2_AUTHORIZE, 28 | OAUTH2_TOKEN, 29 | ) 30 | 31 | _LOGGER = logging.getLogger(__name__) 32 | CONFIG_SCHEMA = vol.Schema( 33 | { 34 | DOMAIN: vol.Schema( 35 | { 36 | vol.Required(CONF_CLIENT_ID): cv.string, 37 | vol.Required(CONF_CLIENT_SECRET): cv.string, 38 | vol.Optional( 39 | CONF_REAL_TIME_INTERVAL, default=timedelta(seconds=10) 40 | ): vol.All(cv.time_period, cv.positive_timedelta), 41 | vol.Optional( 42 | CONF_BILLING_INTERVAL, default=timedelta(seconds=1800) 43 | ): vol.All(cv.time_period, cv.positive_timedelta), 44 | vol.Optional(CONF_MONITORED_CONDITIONS): 45 | vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), 46 | } 47 | ) 48 | }, 49 | extra=vol.ALLOW_EXTRA, 50 | ) 51 | 52 | 53 | async def async_setup(hass: HomeAssistant, config: dict): 54 | """Set up the EnerTalk component.""" 55 | hass.data[DOMAIN] = { 56 | DATA_CONF: config[DOMAIN] 57 | } 58 | 59 | if DOMAIN not in config: 60 | return True 61 | 62 | config_flow.EnerTalkFlowHandler.async_register_implementation( 63 | hass, 64 | config_entry_oauth2_flow.LocalOAuth2Implementation( 65 | hass, 66 | DOMAIN, 67 | config[DOMAIN][CONF_CLIENT_ID], 68 | config[DOMAIN][CONF_CLIENT_SECRET], 69 | OAUTH2_AUTHORIZE, 70 | OAUTH2_TOKEN, 71 | ), 72 | ) 73 | 74 | return True 75 | 76 | 77 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): 78 | """Set up EnerTalk from a config entry.""" 79 | impl = await config_entry_oauth2_flow.async_get_config_entry_implementation( 80 | hass, entry 81 | ) 82 | 83 | hass.data[DOMAIN][entry.entry_id] = { 84 | AUTH: api.ConfigEntryEnerTalkAuth(hass, entry, impl) 85 | } 86 | 87 | hass.async_create_task( 88 | hass.config_entries.async_forward_entry_setup(entry, "sensor") 89 | ) 90 | return True 91 | 92 | 93 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): 94 | """Unload a config entry.""" 95 | await asyncio.gather( 96 | hass.config_entries.async_forward_entry_unload(entry, "sensor") 97 | ) 98 | hass.data[DOMAIN].pop(entry.entry_id) 99 | 100 | return True 101 | -------------------------------------------------------------------------------- /custom_components/enertalk/api.py: -------------------------------------------------------------------------------- 1 | """API for EnerTalk bound to HASS OAuth.""" 2 | import logging 3 | from asyncio import run_coroutine_threadsafe 4 | from time import sleep 5 | 6 | import requests 7 | from homeassistant import config_entries, core 8 | from homeassistant.helpers import config_entry_oauth2_flow 9 | 10 | from .const import API_ENDPOINT 11 | 12 | _LOGGER = logging.getLogger(__name__) 13 | 14 | 15 | class ConfigEntryEnerTalkAuth: 16 | """Provide EnerTalk authentication tied to an OAuth2 based config entry.""" 17 | 18 | def __init__( 19 | self, 20 | hass: core.HomeAssistant, 21 | config_entry: config_entries.ConfigEntry, 22 | impl: config_entry_oauth2_flow.AbstractOAuth2Implementation, 23 | ): 24 | """Initialize EnerTalk Auth.""" 25 | self.hass = hass 26 | self.session = config_entry_oauth2_flow.OAuth2Session( 27 | hass, config_entry, impl 28 | ) 29 | 30 | def refresh_tokens(self, ): 31 | """Refresh new EnerTalk tokens using Home Assistant OAuth2 session.""" 32 | run_coroutine_threadsafe( 33 | self.session.async_ensure_token_valid(), self.hass.loop 34 | ).result() 35 | 36 | def request(self, url): 37 | headers = { 38 | 'Authorization': f"Bearer {self.session.token['access_token']}", 39 | 'accept-version': '2.0.0' 40 | } 41 | try: 42 | response = requests.get(f'{API_ENDPOINT}/{url}', 43 | headers=headers, timeout=10) 44 | _LOGGER.debug('JSON Response: %s', response.content.decode('utf8')) 45 | return response 46 | except Exception as ex: 47 | _LOGGER.error('Failed to update EnerToken status Error: %s', ex) 48 | raise 49 | 50 | def get(self, url): 51 | response = self.request(url) 52 | if response.status_code == 401: 53 | error_type = response.json()['type'] 54 | if error_type == 'UnauthorizedError': 55 | self.refresh_tokens() 56 | # Sleep for 1 sec to prevent authentication related 57 | # timeouts after a token refresh. 58 | sleep(1) 59 | response = self.request(url) 60 | return response.json() 61 | -------------------------------------------------------------------------------- /custom_components/enertalk/config_flow.py: -------------------------------------------------------------------------------- 1 | """Config flow for EnerTalk.""" 2 | import logging 3 | 4 | from homeassistant import config_entries 5 | from homeassistant.helpers import config_entry_oauth2_flow 6 | 7 | from .const import DOMAIN 8 | 9 | _LOGGER = logging.getLogger(__name__) 10 | 11 | 12 | class EnerTalkFlowHandler( 13 | config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN 14 | ): 15 | """Config flow to handle Enertalk OAuth2 authentication.""" 16 | 17 | DOMAIN = DOMAIN 18 | CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL 19 | 20 | @property 21 | def logger(self) -> logging.Logger: 22 | """Return logger.""" 23 | return logging.getLogger(__name__) 24 | 25 | async def async_oauth_create_entry(self, data: dict) -> dict: 26 | """Create an entry for the flow. 27 | 28 | Ok to override if you want to fetch extra info or even add another step. 29 | """ 30 | return self.async_create_entry(title=DOMAIN, data=data) 31 | 32 | async def async_step_user(self, user_input=None): 33 | """Handle a flow start.""" 34 | if self.hass.config_entries.async_entries(DOMAIN): 35 | return self.async_abort(reason="already_setup") 36 | 37 | return await super().async_step_user(user_input) 38 | 39 | async def async_step_homekit(self, homekit_info): 40 | """Handle HomeKit discovery.""" 41 | return await self.async_step_user() 42 | -------------------------------------------------------------------------------- /custom_components/enertalk/const.py: -------------------------------------------------------------------------------- 1 | """Constants used by the Netatmo component.""" 2 | 3 | DOMAIN = "enertalk" 4 | MANUFACTURER = "EnerTalk" 5 | 6 | REAL_TIME_MON_COND = { 7 | 'real_time_usage': ['Real Time', 'Usage', 'W', 'mdi:pulse'] 8 | } 9 | BILLING_MON_COND = { 10 | 'today_usage': ['Today', 'Usage', 'kWh', 'mdi:trending-up'], 11 | 'today_charge': ['Today', 'Charge', '원', 'mdi:currency-krw'], 12 | 'yesterday_usage': ['Yesterday', 'Usage', 'kWh', 'mdi:trending-up'], 13 | 'yesterday_charge': ['Yesterday', 'Charge', '원', 'mdi:currency-krw'], 14 | 'month_usage': ['Month', 'Usage', 'kWh', 'mdi:trending-up'], 15 | 'month_charge': ['Month', 'Charge', '원', 'mdi:currency-krw'], 16 | 'estimate_usage': ['Estimate', 'Usage', 'kWh', 'mdi:calendar-question'], 17 | 'estimate_charge': ['Estimate', 'Charge', '원', 'mdi:currency-krw'] 18 | } 19 | MONITORED_CONDITIONS = list(REAL_TIME_MON_COND.keys()) + \ 20 | list(BILLING_MON_COND.keys()) 21 | 22 | AUTH = "enertalk_auth" 23 | CONF_REAL_TIME_INTERVAL = 'real_time_interval' 24 | CONF_BILLING_INTERVAL = 'billing_interval' 25 | 26 | OAUTH2_AUTHORIZE = "https://auth.enertalk.com/authorization" 27 | OAUTH2_TOKEN = "https://auth.enertalk.com/token" 28 | API_ENDPOINT = 'https://api2.enertalk.com' 29 | 30 | DATA_CONF = "enertalk_conf" 31 | -------------------------------------------------------------------------------- /custom_components/enertalk/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "enertalk", 3 | "name": "EnerTalk", 4 | "documentation": "https://www.home-assistant.io/integrations/enertalk", 5 | "dependencies": [], 6 | "codeowners": [ 7 | "@stkang90" 8 | ], 9 | "requirements": [], 10 | "config_flow": true, 11 | "iot_class": "cloud_polling", 12 | "version": "1.0.0" 13 | } -------------------------------------------------------------------------------- /custom_components/enertalk/sensor.py: -------------------------------------------------------------------------------- 1 | """Support for the EnerTalk Sensor.""" 2 | 3 | import logging 4 | from datetime import datetime, timedelta 5 | 6 | from homeassistant.const import CONF_MONITORED_CONDITIONS 7 | from homeassistant.helpers.entity import Entity 8 | from homeassistant.util import Throttle 9 | 10 | from .const import ( 11 | AUTH, 12 | DOMAIN, 13 | MANUFACTURER, 14 | DATA_CONF, 15 | REAL_TIME_MON_COND, 16 | BILLING_MON_COND, 17 | CONF_REAL_TIME_INTERVAL, 18 | CONF_BILLING_INTERVAL, 19 | ) 20 | 21 | _LOGGER = logging.getLogger(__name__) 22 | 23 | 24 | async def async_setup_entry(hass, entry, async_add_entities): 25 | """Set up the Netatmo weather and homecoach platform.""" 26 | 27 | data_conf = hass.data[DOMAIN][DATA_CONF] 28 | monitored_conditions = data_conf[CONF_MONITORED_CONDITIONS] 29 | real_time_interval = data_conf[CONF_REAL_TIME_INTERVAL] 30 | billing_interval = data_conf[CONF_BILLING_INTERVAL] 31 | 32 | auth = hass.data[DOMAIN][entry.entry_id][AUTH] 33 | 34 | def find_entities(device): 35 | """Find all entities.""" 36 | entities = [] 37 | for variable in monitored_conditions: 38 | if variable in REAL_TIME_MON_COND: 39 | entities += [ 40 | EnerTalkRealTimeSensor( 41 | device, variable, REAL_TIME_MON_COND[variable], 42 | auth, real_time_interval 43 | ) 44 | ] 45 | 46 | billing_api = {} 47 | for variable in monitored_conditions: 48 | if variable in BILLING_MON_COND: 49 | billing_type = BILLING_MON_COND[variable][0] 50 | if billing_type not in billing_api: 51 | billing_api[billing_type] = EnerBillingApi( 52 | auth, device, billing_type, billing_interval) 53 | entities += [ 54 | EnerTalkBillingSensor( 55 | device, variable, 56 | BILLING_MON_COND[variable], billing_api[billing_type] 57 | ) 58 | ] 59 | return entities 60 | 61 | def get_entities(): 62 | from pytz import timezone 63 | """Retrieve EnerTalk entities.""" 64 | entities = [] 65 | 66 | devices = auth.get('sites') 67 | for device in devices: 68 | device['timezone'] = timezone(device['timezone']) 69 | entities.extend(find_entities(device)) 70 | 71 | return entities 72 | 73 | async_add_entities(await hass.async_add_executor_job(get_entities), True) 74 | 75 | 76 | class EnerTalkSensor(Entity): 77 | """Representation of a EnerTalk Sensor.""" 78 | 79 | def __init__(self, device, variable, variable_info): 80 | """Initialize the EnerTalk sensor.""" 81 | self._device = device 82 | self._name = self._device['name'].lower() 83 | self.var_id = variable 84 | self.var_period = variable_info[0] 85 | self.var_type = variable_info[1] 86 | self.var_units = variable_info[2] 87 | self.var_icon = variable_info[3] 88 | 89 | @property 90 | def unique_id(self): 91 | """Return a unique ID.""" 92 | return f'{DOMAIN}_{self._name}_{self.var_id}' 93 | 94 | @property 95 | def name(self): 96 | """Return the name of the sensor, if any.""" 97 | return f'{MANUFACTURER} {self.var_period} {self.var_type}' 98 | 99 | @property 100 | def icon(self): 101 | """Icon to use in the frontend, if any.""" 102 | return self.var_icon 103 | 104 | @property 105 | def unit_of_measurement(self): 106 | """Return the unit the value is expressed in.""" 107 | return self.var_units 108 | 109 | @property 110 | def device_info(self): 111 | """Return information about the device.""" 112 | return { 113 | "identifiers": {(DOMAIN, self._device['id'])}, 114 | 'name': f'{MANUFACTURER} ({self._name})', 115 | 'manufacturer': MANUFACTURER, 116 | 'model': self._device['description'], 117 | 'country': self._device['country'], 118 | 'timezone': self._device['timezone'], 119 | 'description': self._device['description'] 120 | } 121 | 122 | 123 | class EnerBillingApi: 124 | """Class to interface with EnerTalk Billing API.""" 125 | 126 | def __init__(self, api, device, billing_type, interval): 127 | """Initialize the Billing API wrapper class.""" 128 | self.api = api 129 | self.site_id = device['id'] 130 | self.timezone = device['timezone'] 131 | self.type = billing_type 132 | self.result = None 133 | self.update = Throttle(interval)(self.update) 134 | 135 | def update(self): 136 | """Update function for updating api information.""" 137 | param = '' 138 | today_date = datetime.now(tz=self.timezone) \ 139 | .replace(hour=0, minute=0, second=0, microsecond=0) 140 | if self.type == 'Today': 141 | param = f'?period=day&start={today_date.timestamp() * 1000}' 142 | elif self.type == 'Yesterday': 143 | param = '?period=day&start={}&end={}'.format( 144 | (today_date - timedelta(1)).timestamp() * 1000, 145 | today_date.timestamp() * 1000) 146 | elif self.type == 'Estimate': 147 | param = '?timeType=pastToFuture' 148 | 149 | self.result = self.api.get( 150 | f'sites/{self.site_id}/usages/billing{param}') 151 | self.result['charge'] = self.result['bill']['charge'] 152 | 153 | 154 | class EnerTalkRealTimeSensor(EnerTalkSensor): 155 | """Representation of a EnerTalk RealTime Sensor.""" 156 | 157 | def __init__(self, device, variable, variable_info, api, 158 | interval): 159 | """Initialize the Real Time Sensor.""" 160 | super().__init__(device, variable, variable_info) 161 | self.site_id = self._device['id'] 162 | self.api = api 163 | self.result = None 164 | self.update = Throttle(interval)(self.update) 165 | 166 | @property 167 | def state(self): 168 | """Return the state of the sensor.""" 169 | if self.result is None: 170 | return None 171 | return round(self.result['activePower'] * 0.001, 2) 172 | 173 | @property 174 | def device_state_attributes(self): 175 | """Return the device state attributes.""" 176 | if self.result is None: 177 | return None 178 | return { 179 | 'time': datetime.fromtimestamp( 180 | self.result['timestamp'] / 1000, 181 | self._device['timezone']).strftime('%Y-%m-%d %H:%M:%S'), 182 | 'current': self.result['current'], 183 | 'active_power': self.result['activePower'], 184 | 'billing_active_power': self.result['billingActivePower'], 185 | 'apparent_power': self.result['apparentPower'], 186 | 'reactive_power': self.result['reactivePower'], 187 | 'power_factor': self.result['powerFactor'], 188 | 'voltage': self.result['voltage'], 189 | 'positive_energy': self.result['positiveEnergy'], 190 | 'negative_energy': self.result['negativeEnergy'], 191 | 'positive_energy_reactive': self.result['positiveEnergyReactive'], 192 | 'negative_energy_reactive': self.result['negativeEnergyReactive'] 193 | } 194 | 195 | def update(self): 196 | """Update function for updating api information.""" 197 | self.result = self.api.get( 198 | f'sites/{self.site_id}/usages/realtime') 199 | 200 | 201 | class EnerTalkBillingSensor(EnerTalkSensor): 202 | """Representation of a EnerTalk Billing Sensor.""" 203 | 204 | def __init__(self, device, variable, variable_info, api): 205 | """Initialize the Billing Sensor.""" 206 | super().__init__(device, variable, variable_info) 207 | self.api = api 208 | 209 | @property 210 | def state(self): 211 | """Return the state of the sensor.""" 212 | if self.api.result is None: 213 | return None 214 | elif self.var_type == 'Usage': 215 | return round(self.api.result['usage'] * 0.000001, 2) 216 | else: 217 | return round(self.api.result['charge'], 1) 218 | 219 | @property 220 | def device_state_attributes(self): 221 | """Return the device state attributes.""" 222 | if self.api.result is None: 223 | return 224 | return { 225 | 'period': self.api.result['period'], 226 | 'start': datetime.fromtimestamp( 227 | self.api.result['start'] / 1000, 228 | self._device['timezone']).strftime('%Y-%m-%d %H:%M:%S'), 229 | 'end': datetime.fromtimestamp( 230 | self.api.result['end'] / 1000, 231 | self._device['timezone']).strftime('%Y-%m-%d %H:%M:%S') 232 | } 233 | 234 | def update(self): 235 | """Get the latest state of the sensor.""" 236 | self.api.update() -------------------------------------------------------------------------------- /custom_components/enertalk/strings.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "step": { 4 | "pick_implementation": { 5 | "title": "[%key:common::config_flow::title::oauth2_pick_implementation%]" 6 | } 7 | }, 8 | "abort": { 9 | "already_setup": "[%key:common::config_flow::abort::single_instance_allowed%]", 10 | "authorize_url_timeout": "[%key:common::config_flow::abort::oauth2_authorize_url_timeout%]", 11 | "missing_configuration": "[%key:common::config_flow::abort::oauth2_missing_configuration%]" 12 | }, 13 | "create_entry": { 14 | "default": "[%key:common::config_flow::create_entry::authenticated%]" 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /custom_components/enertalk/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_setup": "Already configured. Only a single configuration possible.", 5 | "authorize_url_timeout": "Timeout generating authorize url.", 6 | "missing_configuration": "The component is not configured. Please follow the documentation." 7 | }, 8 | "create_entry": { 9 | "default": "Successfully authenticated" 10 | }, 11 | "step": { 12 | "pick_implementation": { 13 | "title": "Pick Authentication Method" 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /custom_components/enertalk/translations/ko.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_setup": "\uc774\ubbf8 \uad6c\uc131\ub418\uc5c8\uc2b5\ub2c8\ub2e4. \ud558\ub098\uc758 \uad6c\uc131\ub9cc \uac00\ub2a5\ud569\ub2c8\ub2e4.", 5 | "authorize_url_timeout": "\uc778\uc99d url \uc0dd\uc131 \uc2dc\uac04\uc774 \ucd08\uacfc\ub418\uc5c8\uc2b5\ub2c8\ub2e4.", 6 | "missing_configuration": "\uad6c\uc131\uc694\uc18c\uac00 \uad6c\uc131\ub418\uc9c0 \uc54a\uc558\uc2b5\ub2c8\ub2e4. \uc124\uba85\uc11c\ub97c \ucc38\uace0\ud574\uc8fc\uc138\uc694." 7 | }, 8 | "create_entry": { 9 | "default": "\uc131\uacf5\uc801\uc73c\ub85c \uc778\uc99d\ub418\uc5c8\uc2b5\ub2c8\ub2e4" 10 | }, 11 | "step": { 12 | "pick_implementation": { 13 | "title": "\uc778\uc99d \ubc29\ubc95 \uc120\ud0dd\ud558\uae30" 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /custom_components/sk_weather/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "sk_weather", 3 | "name": "sk_weather", 4 | "documentation": "https://www.home-assistant.io/components/sensor.sk_weather", 5 | "requirements": [], 6 | "dependencies": [], 7 | "codeowners": [] 8 | } -------------------------------------------------------------------------------- /custom_components/sk_weather/sensor.py: -------------------------------------------------------------------------------- 1 | """Support for SK Weather Sensors.""" 2 | import logging 3 | import requests 4 | import voluptuous as vol 5 | import homeassistant.helpers.config_validation as cv 6 | 7 | from datetime import timedelta 8 | from homeassistant.components.sensor import PLATFORM_SCHEMA 9 | from homeassistant.const import (CONF_NAME, CONF_LATITUDE, CONF_LONGITUDE) 10 | from homeassistant.helpers.entity import Entity 11 | from homeassistant.util import Throttle 12 | 13 | _LOGGER = logging.getLogger(__name__) 14 | 15 | CONF_APP_KEY = 'app_key' 16 | CONF_SUMMARY_INTERVAL = 'summary_interval' 17 | CONF_MINUTELY_INTERVAL = 'minutely_interval' 18 | CONF_SUMMARY_MON_COND = 'summary_monitored_conditions' 19 | CONF_MINUTELY_MON_COND = 'minutely_monitored_conditions' 20 | 21 | SK_WEATHER_API_URL = 'https://api2.sktelecom.com' 22 | DEFAULT_NAME = 'SK Weather' 23 | 24 | MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30) 25 | SCAN_INTERVAL = timedelta(seconds=600) 26 | 27 | _SUMMARY_MON_COND = { 28 | 'summary_time': ['Summary', 'Time', '', None, 'mdi:clock-outline'], 29 | 'today_sky': ['Today', 'Sky', '', None, None], 30 | 'today_tmax': ['Today', 'Temperature', 'Max', '°C', 31 | 'mdi:thermometer-lines'], 32 | 'today_tmin': ['Today', 'Temperature', 'Min', '°C', 'mdi:thermometer'], 33 | 'tomorrow_sky': ['Tomorrow', 'Sky', '', None, None], 34 | 'tomorrow_tmax': ['Tomorrow', 'Temperature', 'Max', '°C', 35 | 'mdi:thermometer-lines'], 36 | 'tomorrow_tmin': ['Tomorrow', 'Temperature', 'Min', '°C', 37 | 'mdi:thermometer'] 38 | } 39 | _MINUTELY_MON_COND = { 40 | 'minutely_time': ['Minutely', 'Time', '', None, 'mdi:clock-outline'], 41 | 'now_sky': ['Now', 'Sky', '', None, None], 42 | 'now_temp': ['Now', 'Temperature', '', '°C', 'mdi:thermometer'], 43 | 'now_humidity': ['Now', 'Humidity', '', '%', 'mdi:water-percent'], 44 | 'now_wind_direction': ['Now', 'Wind', 'Direction', 'degree', 45 | 'mdi:sign-direction'], 46 | 'now_wind_speed': ['Now', 'Wind', 'Speed', 'm/s', 'mdi:weather-windy'], 47 | 'now_precipitation': ['Now', 'Precipitation', 'Since On Time', 'mm', 48 | 'mdi:water'], 49 | 'now_pressure_surface': ['Now', 'Pressure', 'Surface', 'Ps', ''], 50 | 'now_pressure_sea_level': ['Now', 'Pressure', 'Sea Level', 'SLP', ''], 51 | 'now_lightning': ['Now', 'Lightning', '', None, 'mdi:weather-lightning'] 52 | } 53 | 54 | PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ 55 | vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, 56 | vol.Required(CONF_APP_KEY): cv.string, 57 | vol.Optional(CONF_SUMMARY_INTERVAL, default=timedelta(seconds=600)): 58 | vol.All(cv.time_period, cv.positive_timedelta), 59 | vol.Optional(CONF_MINUTELY_INTERVAL, default=timedelta(seconds=600)): 60 | vol.All(cv.time_period, cv.positive_timedelta), 61 | vol.Optional(CONF_SUMMARY_MON_COND): 62 | vol.All(cv.ensure_list, [vol.In(_SUMMARY_MON_COND)]), 63 | vol.Optional(CONF_MINUTELY_MON_COND): 64 | vol.All(cv.ensure_list, [vol.In(_MINUTELY_MON_COND)]), 65 | }) 66 | 67 | 68 | def setup_platform(hass, config, add_entities, discovery_info=None): 69 | """Set up a SK Weather Sensors.""" 70 | 71 | name = config.get(CONF_NAME) 72 | app_key = config.get(CONF_APP_KEY) 73 | lat = config.get(CONF_LATITUDE, hass.config.latitude) 74 | lon = config.get(CONF_LONGITUDE, hass.config.longitude) 75 | summary_interval = config.get(CONF_SUMMARY_INTERVAL) 76 | minutely_interval = config.get(CONF_MINUTELY_INTERVAL) 77 | summary_monitored_conditions = config.get(CONF_SUMMARY_MON_COND) 78 | minutely_monitored_conditions = config.get(CONF_MINUTELY_MON_COND) 79 | 80 | api = SKWeatherAPI(app_key) 81 | 82 | sensors = [] 83 | if summary_monitored_conditions is not None: 84 | summary_api = SKWeatherSummaryAPI(lat, lon, api) 85 | for variable in summary_monitored_conditions: 86 | sensors += [SKWeatherSummarySensor( 87 | name, variable, _SUMMARY_MON_COND[variable], 88 | summary_api, summary_interval)] 89 | 90 | if minutely_monitored_conditions is not None: 91 | url = '/weather/code/grid?version=2&lat={}&lon={}'.format(lat, lon) 92 | grid = api.get(url)['weather']['grid'][0] 93 | minutely_api = SKWeatherMinutelyAPI(lat, lon, grid, api) 94 | for variable in minutely_monitored_conditions: 95 | sensors += [SKWeatherMinutelySensor( 96 | name, variable, _MINUTELY_MON_COND[variable], 97 | grid, minutely_api, minutely_interval)] 98 | 99 | add_entities(sensors, True) 100 | 101 | 102 | def get_sky_icon(sky_code): 103 | sky_code = sky_code[4:] 104 | if sky_code == 'D01' or sky_code == 'M01' or sky_code == 'A01': 105 | return 'mdi:weather-sunny' 106 | if sky_code == 'D02' or sky_code == 'M02' or sky_code == 'A02': 107 | return 'mdi:weather-partlycloudy' 108 | if sky_code == 'D03' or sky_code == 'M03' or sky_code == 'A03': 109 | return 'mdi:weather-cloudy' 110 | if sky_code == 'D04' or sky_code == 'M04' or sky_code == 'A07': 111 | return 'mdi:weather-fog' 112 | if sky_code == 'D05' or sky_code == 'M05'\ 113 | or sky_code == 'A04' or sky_code == 'A08': 114 | return 'mdi:weather-pouring' 115 | if sky_code == 'D06' or sky_code == 'M06'\ 116 | or sky_code == 'A05' or sky_code == 'A09' or sky_code == 'A13': 117 | return 'mdi:weather-snowy' 118 | if sky_code == 'D07' or sky_code == 'M07'\ 119 | or sky_code == 'A06' or sky_code == 'A10' or sky_code == 'A14': 120 | return 'mdi:weather-snowy-rainy' 121 | if sky_code == 'A11': 122 | return 'mdi:weather-lightning' 123 | if sky_code == 'A12': 124 | return 'mdi:weather-lightning-rainy' 125 | 126 | 127 | class SKWeatherAPI: 128 | """SK Weather API.""" 129 | def __init__(self, app_key): 130 | """Initialize the SK Weather API..""" 131 | self.app_key = app_key 132 | 133 | def get(self, url): 134 | headers = {'appKey': '{}'.format(self.app_key)} 135 | try: 136 | response = requests.get( 137 | '{}{}'.format(SK_WEATHER_API_URL, url), 138 | headers=headers, timeout=10) 139 | response.raise_for_status() 140 | _LOGGER.debug('JSON Response: %s', response.content.decode('utf8')) 141 | return response.json() 142 | except Exception as ex: 143 | _LOGGER.error('Failed to update Weather API status Error: %s', ex) 144 | raise 145 | 146 | 147 | class SKWeatherSummaryAPI: 148 | """Representation of a SK Weather Summary Api.""" 149 | 150 | def __init__(self, lat, lon, api): 151 | """Initialize of a SK Weather Summary Api.""" 152 | self.lat = lat 153 | self.lon = lon 154 | self.api = api 155 | self.result = {} 156 | 157 | @Throttle(MIN_TIME_BETWEEN_UPDATES) 158 | def update(self): 159 | """Update function for updating api information.""" 160 | url = '/weather/summary?version=2&lat={}&lon={}' \ 161 | .format(self.lat, self.lon) 162 | self.result = self.api.get(url)['weather']['summary'][0] 163 | 164 | 165 | class SKWeatherMinutelyAPI: 166 | """Representation of a SK Weather Minutely Api.""" 167 | 168 | def __init__(self, lat, lon, grid, api): 169 | """Initialize of a SK Weather Minutely Api.""" 170 | self.lat = lat 171 | self.lon = lon 172 | self.city = grid['city'] 173 | self.county = grid['county'] 174 | self.village = grid['village'] 175 | self.api = api 176 | self.result = {} 177 | 178 | @Throttle(MIN_TIME_BETWEEN_UPDATES) 179 | def update(self): 180 | """Update function for updating api information.""" 181 | url = '/weather/current/minutely' \ 182 | '?version=2&lat={}&lon={}&city={}&county={}&village={}' \ 183 | .format(self.lat, self.lon, self.city, self.county, self.village) 184 | self.result = self.api.get(url)['weather']['minutely'][0] 185 | 186 | 187 | class SKWeatherSensor(Entity): 188 | """Representation of a SK Weather Sensor.""" 189 | 190 | def __init__(self, name, variable, variable_info): 191 | """Initialize the SK Weather sensor.""" 192 | self._name = name 193 | self.var_id = variable 194 | self.var_period = variable_info[0] 195 | self.var_type = variable_info[1] 196 | self.var_detail = variable_info[2] 197 | self.var_units = variable_info[3] 198 | self.var_icon = variable_info[4] 199 | self.var_state = None 200 | 201 | @property 202 | def entity_id(self): 203 | """Return the entity ID.""" 204 | return 'sensor.{}_{}'.format(self._name, self.var_id) 205 | 206 | @property 207 | def name(self): 208 | """Return the name of the sensor, if any.""" 209 | return '{} {} {}'.format(self.var_period, self.var_type, 210 | self.var_detail) 211 | 212 | @property 213 | def icon(self): 214 | """Icon to use in the frontend, if any.""" 215 | return self.var_icon 216 | 217 | @property 218 | def unit_of_measurement(self): 219 | """Return the unit the value is expressed in.""" 220 | return self.var_units 221 | 222 | @property 223 | def state(self): 224 | """Return the state of the sensor.""" 225 | return self.var_state 226 | 227 | 228 | class SKWeatherSummarySensor(SKWeatherSensor): 229 | """Representation of a SK Weather Summary Sensor.""" 230 | 231 | def __init__(self, name, variable, variable_info, api, interval): 232 | """Initialize the SK Weather Summary Sensor.""" 233 | super().__init__(name, variable, variable_info) 234 | self.api = api 235 | self.update = Throttle(interval)(self.update) 236 | 237 | def update(self): 238 | """Get the latest state of the sensor.""" 239 | if self.api is None: 240 | return 241 | self.api.update() 242 | 243 | if self.var_type == 'Time': 244 | self.var_state = self.api.result['timeRelease'] 245 | return 246 | 247 | result = self.api.result[self.var_period.lower()] 248 | if self.var_type == 'Sky': 249 | sky = result['sky'] 250 | self.var_state = sky['name'] 251 | self.var_icon = get_sky_icon(sky['code']) 252 | else: 253 | temp = result['temperature'] 254 | if self.var_detail == 'Max': 255 | self.var_state = round(float(temp['tmax']), 1) 256 | else: 257 | self.var_state = round(float(temp['tmin']), 1) 258 | 259 | 260 | class SKWeatherMinutelySensor(SKWeatherSensor): 261 | """Representation of a SK Weather Minutely Sensor.""" 262 | 263 | def __init__(self, name, variable, variable_info, grid, api, interval): 264 | """Initialize the SK Weather Summary Sensor.""" 265 | super().__init__(name, variable, variable_info) 266 | self.city = grid['city'] 267 | self.county = grid['county'] 268 | self.village = grid['village'] 269 | self.api = api 270 | self.update = Throttle(interval)(self.update) 271 | 272 | def update(self): 273 | """Get the latest state of the sensor.""" 274 | if self.api is None: 275 | return 276 | self.api.update() 277 | 278 | if self.var_type == 'Time': 279 | self.var_state = self.api.result['timeObservation'] 280 | return 281 | result = self.api.result[self.var_type.lower()] 282 | if self.var_type == 'Sky': 283 | self.var_state = result['name'] 284 | self.var_icon = get_sky_icon(result['code']) 285 | elif self.var_type == 'Temperature': 286 | self.var_state = round(float(result['tc']), 1) 287 | elif self.var_type == 'Humidity': 288 | self.var_state = result 289 | elif self.var_type == 'Wind': 290 | if self.var_detail == 'Direction': 291 | self.var_state = round(float(result['wdir']), 1) 292 | else: 293 | self.var_state = round(float(result['wspd']), 1) 294 | elif self.var_type == 'Precipitation': 295 | self.var_state = round(float(result['sinceOntime']), 1) 296 | p_type = result['type'] 297 | if p_type == 0: 298 | self.var_units = 'mm' 299 | self.var_icon = 'mdi:weather-sunny' 300 | elif p_type == 1: 301 | self.var_units = 'mm' 302 | self.var_icon = 'mdi:weather-rainy' 303 | elif p_type == 2: 304 | self.var_units = 'mm' 305 | self.var_icon = 'mdi:weather-snowy' 306 | elif p_type == 3: 307 | self.var_units = 'cm' 308 | self.var_icon = 'mdi:weather-snowy-rainy' 309 | elif self.var_type == 'Pressure': 310 | if self.var_detail == 'Surface': 311 | self.var_state = round(float(result['surface']), 1) 312 | else: 313 | self.var_state = round(float(result['seaLevel']), 1) 314 | elif self.var_type == 'Lightning': 315 | if result == '1': 316 | self.var_state = 'Exist' 317 | else: 318 | self.var_state = 'None' 319 | --------------------------------------------------------------------------------