最近、スマホ外に持ち出そうと思ったら、充電忘れで、使えない状態になったりということもあったので、 スマホバッテリーが減ってきたら、rapi経由で音声で知らせるようにしてみました。
以前作成したシステムに音声ファイルを追加しただけです。bottleのコードは、今回、夜間はならないように少し修正しました。macrodroidを使ってGETでアクセスする予定です。リレーは、動作時のみアンプの電源をOnにするためのものです。
def alarmW(wav_file):
file_path = os.path.join("/home/pi", wav_file)
if not os.path.isfile(file_path):
return f"File not found: {wav_file}"
try:
# 現在の時刻(時間)を取得
now = datetime.now()
current_hour = now.hour
# 22時以降、または朝6時未満(22:00 〜 5:59)は「夜間」と判定
is_night = (current_hour >= 22 or current_hour < 6)
if not is_night:
# 昼間だけリレーをONにして音声を再生する
GPIO.output(RELAY_PIN, GPIO.HIGH)
time.sleep(0.2)
proc = subprocess.Popen(["aplay", file_path])
proc.wait()
# リレーのOFFは、この後の「finally」で確実に実行されるためここでは省略可能ですが、
# 安全のため残すか、下のfinallyに任せます(今回は安全のためfinallyに集約します)
# --- ログ保存(昼夜問わず常時実行) ---
with open("wavlog.txt", "a", newline="") as f:
writer = csv.writer(f)
now_str = now.strftime('%Y-%m-%d %H:%M:%S')
writer.writerow([now_str, wav_file])
with open("wavlog.txt", "r") as f:
lines = f.readlines()
if len(lines) > MAX_LINES:
lines = lines[-MAX_LINES:] # 最新MAX_LINES行だけ残す
with open("wavlog.txt", "w", newline="") as f:
f.writelines(lines)
# 戻り値のメッセージを昼夜で分ける
if is_night:
return f"Logged only (Night time skip): {wav_file}"
else:
return f"Played and Logged: {wav_file}"
except Exception as e:
return f"Error: {e}"
finally:
# 昼間にエラーで止まった場合や、正常終了時、
# どちらの場合でも「最後に必ずリレーをLOWにする」安全対策
GPIO.output(RELAY_PIN, GPIO.LOW)
file_path = os.path.join("/home/pi", wav_file)
if not os.path.isfile(file_path):
return f"File not found: {wav_file}"
try:
# 現在の時刻(時間)を取得
now = datetime.now()
current_hour = now.hour
# 22時以降、または朝6時未満(22:00 〜 5:59)は「夜間」と判定
is_night = (current_hour >= 22 or current_hour < 6)
if not is_night:
# 昼間だけリレーをONにして音声を再生する
GPIO.output(RELAY_PIN, GPIO.HIGH)
time.sleep(0.2)
proc = subprocess.Popen(["aplay", file_path])
proc.wait()
# リレーのOFFは、この後の「finally」で確実に実行されるためここでは省略可能ですが、
# 安全のため残すか、下のfinallyに任せます(今回は安全のためfinallyに集約します)
# --- ログ保存(昼夜問わず常時実行) ---
with open("wavlog.txt", "a", newline="") as f:
writer = csv.writer(f)
now_str = now.strftime('%Y-%m-%d %H:%M:%S')
writer.writerow([now_str, wav_file])
with open("wavlog.txt", "r") as f:
lines = f.readlines()
if len(lines) > MAX_LINES:
lines = lines[-MAX_LINES:] # 最新MAX_LINES行だけ残す
with open("wavlog.txt", "w", newline="") as f:
f.writelines(lines)
# 戻り値のメッセージを昼夜で分ける
if is_night:
return f"Logged only (Night time skip): {wav_file}"
else:
return f"Played and Logged: {wav_file}"
except Exception as e:
return f"Error: {e}"
finally:
# 昼間にエラーで止まった場合や、正常終了時、
# どちらの場合でも「最後に必ずリレーをLOWにする」安全対策
GPIO.output(RELAY_PIN, GPIO.LOW)
0 件のコメント:
コメントを投稿