Last active
August 30, 2022 18:28
-
-
Save PeyaPeyaPeyang/133c5c7d8f82bf3c0f55686faa73a2c1 to your computer and use it in GitHub Desktop.
Google Homeに雨を喋らせます
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import threading | |
import time | |
import traceback | |
import http.server | |
import socketserver | |
import pychromecast | |
import requests | |
from gtts import gTTS | |
from scipy import signal | |
def die(str): | |
print(str) | |
exit(1) | |
API_URL = "https://map.yahooapis.jp/weather/V1/place" | |
APP_ID = os.getenv("YAHOO_APP_ID") | |
WAIT_TIME = 60 * 5 | |
COORDINATE_LOC = [ | |
139.688911, | |
35.502668 | |
] | |
HOST = "192.168.0.236" | |
PORT = 25565 | |
casts = pychromecast.get_chromecasts() | |
toCast = None | |
def autoSelect(): | |
global toCast | |
if len(casts) == 0: | |
return | |
toCast = casts[0][0] | |
print("Device AutoSelected:" + toCast.device.friendly_name + "(" + str(toCast.device.uuid) + ")") | |
toCast.wait() | |
def runCommand(command, args): | |
if command == "test": | |
if len(args) is 0: | |
print("Usage: test <test-data json>") | |
jsonStr = "".join(args) | |
import json | |
data = json.loads(jsonStr) | |
weathers = convertData(data) | |
tendency = calcWeatherTendency(weathers) | |
print("Tendency:" + str(tendency)) | |
postWeatherReport(createReport(weathers, tendency, int(time.time()))) | |
def command(inputStr): | |
command = inputStr.split(" ") | |
while "" in command: | |
command.remove("") | |
if len(command) is 0: | |
return | |
args = command[1:] | |
command = command[0] | |
runCommand(command, args) | |
def checkWeather(): | |
req = requests.get(API_URL, params={ | |
"appid": APP_ID, | |
"coordinates": ",".join(map(str, COORDINATE_LOC)), | |
"output": "json", | |
"interval": 5, | |
}) | |
if req.status_code is not 200: | |
die("Error: " + str(req.status_code)) | |
weathers = convertData(req.json()["Feature"][0]["Property"]["WeatherList"]["Weather"]) | |
if len(weathers) is 0: | |
die("Error: No weather data has been provided") | |
tendency = calcWeatherTendency(weathers) | |
print("Tendency:" + str(tendency)) | |
postAutoReport(weathers, tendency) | |
def postWeatherReport(report): | |
detail = report["result"] | |
reportType = report["reportType"] | |
print("Posting: " + reportType + " - " + detail) | |
if toCast is not None: | |
voice = gTTS(detail, lang="ja") | |
voice.save("temp.mp3") | |
media = toCast.media_controller | |
media.play_media("http://" + HOST + ":" + str(PORT) + "/", "audio/mp3") | |
media.block_until_active() | |
lastPosted = 0 | |
def postAutoReport(weather, tendency): | |
global lastPosted | |
report = createReport(weather, tendency, lastPosted) | |
if report is None: | |
return | |
lastPosted = int(time.time()) | |
postWeatherReport(report) | |
def calcWeatherTendency(waterfalls): | |
isRaining = waterfalls[0] != 0 | |
startsOn = -1 | |
stopsOn = -1 | |
continuesOn = -1 | |
for i in range(len(waterfalls)): | |
if waterfalls[i] == 0: | |
if isRaining and stopsOn == -1: | |
stopsOn = i * 5 | |
else: | |
if not isRaining and startsOn == -1: | |
startsOn = i * 5 | |
elif stopsOn != -1 and continuesOn == -1: | |
continuesOn = i * 5 | |
while waterfalls[-1] == 0: | |
waterfalls.pop() | |
detrended = waterfalls - signal.detrend(waterfalls) | |
tendency = detrended.argmax() - detrended.argmin() | |
if tendency > 0: | |
tendency = 1 | |
elif tendency < 0: | |
tendency = -1 | |
return { | |
"tendency": tendency, | |
"isRaining": isRaining, | |
"startsOn": startsOn, | |
"stopsOn": stopsOn, | |
"continuesOn": continuesOn, | |
} | |
def createReport(weathers, tendency, lastNoticed=0, isRained=False): | |
result = "" | |
if tendency["isRaining"]: | |
info = False | |
result += "今降っている雨は" | |
tendencyValue = tendency["tendency"] | |
if tendencyValue != 0: | |
if tendencyValue == 1: | |
result += "強くなる" | |
elif tendencyValue == -1: | |
result += "弱くなる" | |
result += "傾向にあり" | |
info = True | |
reportType = "rain_tendency" | |
else: | |
result += "変わらず降り続け" | |
reportType = "rain_not_change" | |
if tendency["stopsOn"] != -1: | |
result += str(tendency["stopsOn"]) + "分後には止み" | |
info = True | |
reportType = "rain_stops" | |
if tendency["continuesOn"] != -1: | |
result += "ますが、" + str(tendency["continuesOn"]) + "分後にはまた降り始め" | |
info = True | |
reportType = "rain_continues" | |
if not info: | |
return None | |
result += "ます。" | |
else: | |
if tendency["startsOn"] != -1: | |
startsOn = tendency["startsOn"] | |
if startsOn == 0 and int(time.time()) - lastNoticed < 60 * 10: | |
return None | |
rain_from = "今" if startsOn == 0 else str(startsOn) + "分後" | |
result += rain_from + "から、" + getRainClass(weathers[int(startsOn / 5)]) + "が降ります" | |
reportType = "rain_starts" | |
if tendency["stopsOn"] != -1 and tendency["continuesOn"]: | |
result += "が、" + str(tendency["stopsOn"]) + "分後には止むでしょう" | |
reportType = "shower_rain_starts" | |
result += "。" | |
elif isRained: | |
result += "雨がやみました。" | |
reportType = "rain_ended" | |
else: | |
return None | |
return { | |
"result": result, | |
"reportType": reportType, | |
} | |
def convertData(datas): | |
return [data["Rainfall"] for data in datas] | |
def getRainClass(rainfall): | |
if rainfall <= 1: | |
return "非常に弱い雨" | |
elif rainfall <= 3: | |
return "弱い雨" | |
if rainfall <= 20: | |
return "やや強い雨" | |
elif rainfall <= 30: | |
return "強い雨" | |
elif rainfall <= 50: | |
return "激しい雨" | |
elif rainfall <= 80: | |
return "非常に激しい雨" | |
else: | |
return "猛烈な雨" | |
def pollWeather(): | |
while True: | |
print("Checking weather...") | |
checkWeather() | |
time.sleep(WAIT_TIME) | |
def startServer(): | |
httpd = socketserver.TCPServer(("0.0.0.0", PORT), Handler) | |
print("Starting server...", PORT) | |
httpd.serve_forever() | |
class Handler(http.server.BaseHTTPRequestHandler): | |
def do_GET(self): | |
self.send_response(200) | |
self.send_header("Content-type", "audio/mp3") | |
self.end_headers() | |
self.wfile.write(open("temp.mp3", "rb").read()) | |
if __name__ == "__main__": | |
print("-=-=-=-=[Googlehome weather notifier]=-=-=-=-") | |
print("Made-By: Daisuke Yamazaki") | |
print() | |
pollThread = threading.Thread(target=pollWeather) | |
serverThread = threading.Thread(target=startServer) | |
print("Ready.") | |
autoSelect() | |
pollThread.start() | |
serverThread.start() | |
while True: | |
ipt = input(">") | |
try: | |
command(ipt) | |
except Exception as e: | |
traceback.print_exc() | |
print("OK.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MIT License | |
Copyright (c) 2022 Peyang | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment