#!/usr/bin python3
# -*- coding: utf-8 -*-
import subprocess
import sys
import os
import time
import csv
import schedule
import time

chk="STOP"
ret="none"

def get_ssid():
    global ssid
    cmd = 'iwconfig wlan0|grep ESSID'
    r = subprocess.run(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PI
PE)\
            .stdout.decode().rstrip()
    idx = r.find('ESSID:')
    ssid= r[idx + 7:-1]
    
def start_BR():
    global chk_url
    if "STOP"==chk:
        get_ssid()
        if "melon-5a" == ssid:
            #print ("ESSID=",ssid)
            shell_command="systemctl --user start local_url.service"
            subprocess.run(shell_command,shell=True)
            chk_url="local"
        else:
            #print ("ESSID=",ssid)
            shell_command="systemctl --user start global_url.service"
            subprocess.run(shell_command,shell=True)
            chk_url="global"
   
def stop_BR():
    if "START"==chk:
        if "local" == chk_url:
            shell_command="systemctl --user stop local_url.service"
            subprocess.run(shell_command,shell=True)
            #print ("location=",chk_url)
        else:
            shell_command="systemctl --user stop global_url.service"
            subprocess.run(shell_command,shell=True)
            #print ("location=",chk_url)
            
def bluetooth_chk():
    global chk
    cmd="bluetoothctl info"
    proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    text_origin = proc.stdout.read()
    text = text_origin.decode("utf-8")
    if "Missing" in text:
     stop_BR()
     chk="STOP"
     #print ("bluetooth=",chk)
    else: 
     start_BR()
     chk="START"  
     #print ("bluetooth=",chk)
     
def my_job():
    bluetooth_chk()
   
  
schedule.every(5).seconds.do(my_job)  # 5秒おきに実行

while True:
    schedule.run_pending()  
    time.sleep(1)

