Skip to content

Commit

Permalink
added 2 params
Browse files Browse the repository at this point in the history
  • Loading branch information
guirem committed May 27, 2020
1 parent 129ecf5 commit ecafe07
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 56 deletions.
24 changes: 13 additions & 11 deletions core/class/googlecast.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,17 @@ public function preUpdate()
if (!$found) { // try to guess based on manufacturer
$castType = $this->getConfiguration('cast_type');
$manufName = strtolower($this->getConfiguration('manufacturer', 'UNKOWN'));
if (strpos($manufName, 'google') !== false) {
if ($castType=='audio') {
$imgLogo = $imgRoot . 'model_googlehome.png';
}
if ($castType=='cast') {
$imgLogo = $imgRoot . 'model_chromecast_video.png';
}
if ($castType=='group') {
$imgLogo = $imgRoot . 'model_castgroup.png';
}
}
// if (strpos($manufName, 'google') !== false) {
// if ($castType=='audio') {
// $imgLogo = $imgRoot . 'model_googlehome.png';
// }
// if ($castType=='cast') {
// $imgLogo = $imgRoot . 'model_chromecast_video.png';
// }
// if ($castType=='group') {
// $imgLogo = $imgRoot . 'model_castgroup.png';
// }
// }
if (strpos($manufName, 'xiaomi') !== false) {
$imgLogo = $imgRoot . 'model_androidtv.png';
}
Expand Down Expand Up @@ -962,6 +962,8 @@ public static function deamon_start()
}
$cmd .= ' --ttsgapikey ' . config::byKey('tts_gapikey', 'googlecast', 'none');
$cmd .= ' --gcttsvoice ' . config::byKey('gctts_voice', 'googlecast', 'fr-FR-Standard-A');
$cmd .= ' --ttsdefaultrestoretime ' . config::byKey('tts_default_restoretime', 'googlecast', '1300');
$cmd .= ' --ttsdefaultsilenceduration ' . config::byKey('tts_default_silence_duration', 'googlecast', '300');
$cmd .= ' --daemonname local';
$cmd .= ' --cyclefactor ' . config::byKey('cyclefactor', 'googlecast', '1');
$cmd .= ' --defaultstatus ' . "'". config::byKey('defaultsatus', 'googlecast', " ") ."'";
Expand Down
21 changes: 16 additions & 5 deletions plugin_info/configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -320,16 +320,27 @@
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">{{Ne pas utiliser le cache (déconseillé)}}</label>
<div class="form-group">
<label class="col-lg-4 control-label">{{Delai avant restauration du volume initial}}</label>
<div class="col-lg-2">
<input type="checkbox" class="configKey" data-l1key="tts_disablecache"/>
<input class="configKey form-control" type="number" data-l1key="tts_default_restoretime" min="-1000" max="10000" placeholder="{{Durée en milisecondes}}" />
</div>
<div class="col-lg-2">ms (défaut: 1000)</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">{{Durée du silence ajouté avant la notification}}</label>
<div class="col-lg-2">
<input class="configKey form-control" type="number" data-l1key="tts_default_silence_duration" min="0" max="10000" placeholder="{{Durée en milisecondes}}" />
</div>
<div class="col-lg-2">ms (défaut: 300)</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label"></label>
<label class="col-lg-4 control-label">{{Ne pas utiliser le cache (déconseillé)}}</label>
<div class="col-lg-2">
<a class="btn btn-success cleanTTScache">{{Nettoyer tout le cache}}</a>
<input type="checkbox" class="configKey" data-l1key="tts_disablecache"/>
</div>
<div class="col-lg-2">
<a class="btn btn-warning cleanTTScache">{{Nettoyer tout le cache}}</a>
</div>
</div>
<div class="form-group">
Expand Down
12 changes: 12 additions & 0 deletions plugin_info/install.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ function googlecast_update()
if (config::byKey('gctts_voice', 'googlecast') == '') {
config::save('gctts_voice', 'fr-FR-Standard-A', 'googlecast');
}
if (config::byKey('tts_default_restoretime', 'googlecast') == '') {
config::save('tts_default_restoretime', '1300', 'googlecast');
}
if (config::byKey('tts_default_silence_duration', 'googlecast') == '') {
config::save('tts_default_silence_duration', '300', 'googlecast');
}

foreach (googlecast::byType('googlecast') as $googlecast) {
try {
Expand Down Expand Up @@ -93,6 +99,12 @@ function googlecast_install()
if (config::byKey('tts_disablecache', 'googlecast') == '') {
config::save('tts_disablecache', '0', 'googlecast');
}
if (config::byKey('tts_default_restoretime', 'googlecast') == '') {
config::save('tts_default_restoretime', '1300', 'googlecast');
}
if (config::byKey('tts_default_silence_duration', 'googlecast') == '') {
config::save('tts_default_silence_duration', '300', 'googlecast');
}

linkTemplate('dashboard/cmd.info.string.googlecast_playing.html');
linkTemplate('dashboard/cmd.action.message.googlecast_speak.html');
Expand Down
3 changes: 3 additions & 0 deletions resources/globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@
tts_gapi_voice = 'fr-FR-Standard-A'
tts_gapi_haskey = False

tts_default_restoredelay = 1300 # additionnal time in ms to add after tts (before vol up command)
tts_default_silenceduration = 300 # default silence duration added at tts start

localmedia_folder = 'localmedia'
localmedia_fullpath = os.path.abspath(os.path.join(
os.path.dirname(os.path.dirname(__file__)), localmedia_folder))
Expand Down
109 changes: 75 additions & 34 deletions resources/googlecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import sys
import argparse
import time
from datetime import datetime
from datetime import datetime, timedelta
import signal
import json
import traceback
Expand All @@ -51,6 +51,7 @@
try:
import pychromecast.pychromecast.controllers.dashcast as dashcast
import pychromecast.pychromecast.controllers.spotify as spotify
import pychromecast.pychromecast.controllers.youtube as youtube
except ImportError:
logging.error(
"ERROR: One or several pychromecast controllers are not loaded !")
Expand All @@ -60,7 +61,6 @@

try:
import pychromecast.pychromecast.customcontrollers.plex2 as plex
import pychromecast.pychromecast.customcontrollers.youtube as youtube
except ImportError:
logging.error("ERROR: Custom controllers not loaded !")
logging.error(traceback.format_exc())
Expand Down Expand Up @@ -398,6 +398,29 @@ def disconnect(self):
pass
self.free_memory()

def check_connection(self):
reset = False
castsocket = self.gcast.socket_client
try:
# if castsocket.heartbeat_controller.is_expired():
castsocket.heartbeat_controller.ping()
# castsocket.heartbeat_controller.reset()
except Exception:
logging.debug("JEEDOMCHROMECAST------ check_connection : ping failed")
reset = True
pass

if reset:
for channel in castsocket._open_channels:
castsocket.disconnect_channel(channel)
try:
castsocket.initialize_connection()
except Exception:
castsocket.stop.set()
pass

return not reset

def free_memory(self):
try:
self.gcast.socket_client.socket.shutdown(socket.SHUT_RDWR)
Expand Down Expand Up @@ -886,35 +909,31 @@ def action_handler(message):
if cmd == 'play_media':
fallbackMode = False

wptoken = None
if 'user' in command and 'pass' in command:
username = command['user']
password = command['pass']
wptoken = stoken.SpotifyWpToken(username, password)

if 'token' in command:
token = command['token']

keepGoing = True
if value is None:
if 'spdc' in command and 'spkey' in command:
spdc = command['spdc']
spkey = command['spkey']
spdc = "AQCgatcbOEWKU9btY2uaCYa-f40OilLICq-hzBoQRxhdCTfMTrmgxyVC0h-WCQ-H3aa4Cq4V-woqmRz3Fx8AL_RRutLHo38vk_iXNsY1YPw"
spkey = "cdb4b966-a7dc-4813-ad95-b55361902e8c"
data = stoken.start_session(spdc, spkey)
access_token = data[0]
expires = data[1] - int(time.time())
else:
logging.error(
"ACTION------ Missing content id for spotify")
"ACTION------ Missing spdc and/or spkey")
keepGoing = False
if token is None:

if value is None:
logging.error(
"ACTION------ Missing token paramaters for spotify")
"ACTION------ Missing content id for spotify")
keepGoing = False

if keepGoing is True:
player = jcast.loadPlayer(
app, {'quitapp': quit_app_before, 'wait': wait})
if wptoken is None:
player.launch_app(token)
else:
time.sleep(1)
player.launch_app(wptoken.value)
player.launch_app(access_token, expires)

spotifyClient = spotipy.Spotify(auth=token)
spotifyClient = spotipy.Spotify(auth=access_token)
time.sleep(1)

value = value.replace('spotify:', '')
Expand Down Expand Up @@ -947,7 +966,9 @@ def action_handler(message):
'spotify:', '')
logging.debug(
"ACTION------Spotify recently played : " + value)
# logging.debug("ACTION------Spotify recently played : " + str(recentlyPlayed))
# logging.debug("ACTION------Spotify recently played : " + str(recentlyPlayed))
spotifyClient.start_playback(
device_id=device_id, uris=['spotify:'+value])
elif 'track' not in value: # album or playlist
spotifyClient.start_playback(
device_id=device_id, context_uri='spotify:'+value)
Expand Down Expand Up @@ -1199,9 +1220,10 @@ def action_handler(message):
url, 'video/mp4', 'NOTIF', thumb=thumb, stream_type=streamtype)
player.block_until_active(timeout=2)
jcast.disable_notif = False
duration_total = duration + (globals.tts_default_restoredelay/1000)
sleep_done = False
if vol is not None:
time.sleep(duration+1)
time.sleep(duration_total)
if sleep > 0:
time.sleep(sleep)
sleep = 0
Expand All @@ -1215,15 +1237,15 @@ def action_handler(message):
gcast.media_controller.stop()
if quit:
if vol is None:
time.sleep(duration+1)
time.sleep(duration_total)
sleep_done = True
if sleep > 0:
time.sleep(sleep)
sleep = 0
gcast.quit_app()
if resume:
if vol is None and sleep_done is False:
time.sleep(duration+1)
time.sleep(duration_total)
if sleep > 0:
time.sleep(sleep)
sleep = 0
Expand Down Expand Up @@ -1256,11 +1278,11 @@ def action_handler(message):
forcetts = False
if 'forcetts' in command:
forcetts = True
silence = 300
silence = globals.tts_default_silenceduration
if 'silence' in command:
silence = int(command['silence'])
elif jcast.is_castgroup is True:
silence = 1000
silence = silence + 700
generateonly = False
if 'generateonly' in command:
generateonly = True
Expand Down Expand Up @@ -1309,14 +1331,17 @@ def action_handler(message):
gcast.media_controller.pause()
time.sleep(0.1)
gcast.set_volume(vol/100)
time.sleep(0.1)
# time.sleep(0.1)
streamtype = 'BUFFERED'
player.play_media(
url, 'audio/mp3', 'TTS', thumb=thumb, stream_type=streamtype)
player.block_until_active(timeout=2)
player.block_until_active(timeout=4)
duration_total = duration + (globals.tts_default_restoredelay/1000)
logging.debug("TTS------Estimated duration of tts media is " + str(duration_total) + " secondes")
jcast.disable_notif = False
vol_done = False
if vol is not None:
time.sleep(duration+(silence/1000)+1)
time.sleep(duration_total)
if sleep > 0:
time.sleep(sleep)
sleep = 0
Expand All @@ -1326,14 +1351,14 @@ def action_handler(message):

if quit:
if vol is None:
time.sleep(duration+(silence/1000)+1)
time.sleep(duration_total)
if sleep > 0:
time.sleep(sleep)
sleep = 0
gcast.quit_app()
if resume:
if vol is None and vol_done is False:
time.sleep(duration+(silence/1000)+1)
time.sleep(duration_total)
if sleep > 0:
time.sleep(sleep)
sleep = 0
Expand Down Expand Up @@ -1549,7 +1574,7 @@ def manage_resume(uuid, source='googlecast', forceapplaunch=False, origin='TTS')
return False


def get_tts_data(text, language, engine, speed, forcetts, calcduration, silence=300, quality='32k', ttsparams=None):
def get_tts_data(text, language, engine, speed, forcetts, calcduration, silence=100, quality='32k', ttsparams=None):
srclanguage = language
if engine == 'gttsapidev': # removed this engine but failover to gttsapi
engine = 'gttsapi'
Expand Down Expand Up @@ -1817,7 +1842,7 @@ def logByTTS(text_id):
else:
text = "Un erreur s'est produite !"
url, duration, mp3filename = get_tts_data(
text, lang, engine, speed, False, False, 300)
text, lang, engine, speed, False, False, globals.tts_default_silenceduration)
thumb = globals.JEEDOM_WEB + '/plugins/googlecast/desktop/images/tts.png'
jcast = None # TODO: get googlecast device first
player = jcast.loadPlayer('media', {'quitapp': False, 'wait': 0})
Expand Down Expand Up @@ -1911,6 +1936,7 @@ def start(cycle=2):

except Exception:
logging.error("GLOBAL------Exception on main loop")
shutdown()

except KeyboardInterrupt:
logging.error("GLOBAL------KeyboardInterrupt, shutdown")
Expand Down Expand Up @@ -2153,6 +2179,11 @@ def scanner(name='UNKNOWN SOURCE'):
if known in globals.GCAST_DEVICES:
if globals.GCAST_DEVICES[known].is_connected is True:
is_not_available = False

# try to ping it to confirm it's well connected
con_ok = globals.GCAST_DEVICES[known].check_connection()
if not con_ok:
logging.debug("SCANNER------Seen as connected but ping failed, trying to reconnect " + known)
else:
# something went wrong so disconnect completely
globals.GCAST_DEVICES[known].disconnect()
Expand Down Expand Up @@ -2333,6 +2364,8 @@ def shutdown():
parser.add_argument("--ttsgapikey", help="TTS Google Speech API Key", type=str)
parser.add_argument(
"--gcttsvoice", help="TTS Google Speech API default voice", type=str)
parser.add_argument("--ttsdefaultrestoretime", help="TTS Default restore volume delay", type=str)
parser.add_argument("--ttsdefaultsilenceduration", help="TTS Default silence duration", type=str)
parser.add_argument("--socketport", help="Socket Port", type=str)
parser.add_argument("--sockethost", help="Socket Host", type=str)
parser.add_argument("--daemonname", help="Daemon Name", type=str)
Expand Down Expand Up @@ -2375,6 +2408,10 @@ def shutdown():
globals.tts_gapi_haskey = True
if args.gcttsvoice:
globals.tts_gapi_voice = args.gcttsvoice
if args.ttsdefaultrestoretime:
globals.tts_default_restoredelay = int(args.ttsdefaultrestoretime)
if args.ttsdefaultsilenceduration:
globals.tts_default_silenceduration = int(args.ttsdefaultsilenceduration)
if args.cycle:
globals.cycle_event = float(args.cycle)
if args.cyclemain:
Expand Down Expand Up @@ -2422,6 +2459,10 @@ def shutdown():
str(globals.tts_gapi_voice))
else:
logging.info('GLOBAL------TTS Google API Key (optional) : NOK')
logging.info('GLOBAL------TTS default delay before volume restore : ' +
str(globals.tts_default_restoredelay) + ' ms')
logging.info('GLOBAL------TTS default silence before tts : ' +
str(globals.tts_default_silenceduration) + ' ms')
logging.info('GLOBAL------Cache status : '+str(globals.tts_cacheenabled))
logging.info('GLOBAL------Callback : '+str(globals.callback))
logging.info('GLOBAL------Event cycle : '+str(globals.cycle_event))
Expand Down
6 changes: 3 additions & 3 deletions resources/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ if [[ ! -z $pip3cmd ]]; then # pip3 found
echo 87 > /tmp/dependancy_googlecast_in_progress
echo ""
echo "-- Installation of python library 'zeroconf' with command $pip3cmd"
$(sudo $pip3cmd install 'zeroconf<0.24.4,>=0.22.0' > /tmp/dependancy_googlecast)
$(sudo $pip3cmd install 'zeroconf>=0.25.1' > /tmp/dependancy_googlecast)
cat /tmp/dependancy_googlecast
echo 92 > /tmp/dependancy_googlecast_in_progress
echo ""
Expand All @@ -102,8 +102,8 @@ if [[ ! -z $pip3cmd ]]; then # pip3 found
cat /tmp/dependancy_googlecast
echo 96 > /tmp/dependancy_googlecast_in_progress
echo ""
echo "-- Installation of python library 'tqdm, websocket-client' for plex with command $pip3cmd"
$(sudo $pip3cmd install tqdm websocket-client > /tmp/dependancy_googlecast)
echo "-- Installation of python library 'tqdm, websocket-client, casttube' for plex/youtube with command $pip3cmd"
$(sudo $pip3cmd install tqdm websocket-client casttube > /tmp/dependancy_googlecast)
cat /tmp/dependancy_googlecast
echo 100 > /tmp/dependancy_googlecast_in_progress
echo ""
Expand Down
Loading

0 comments on commit ecafe07

Please sign in to comment.