2017-10-04 06:28:44 +00:00
|
|
|
# Copyright 2017 Mycroft AI Inc.
|
2016-05-26 16:16:13 +00:00
|
|
|
#
|
2017-10-04 06:28:44 +00:00
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
2016-05-26 16:16:13 +00:00
|
|
|
#
|
2017-10-04 06:28:44 +00:00
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
2016-05-26 16:16:13 +00:00
|
|
|
#
|
2017-10-04 06:28:44 +00:00
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2016-05-26 16:16:13 +00:00
|
|
|
#
|
2016-05-20 14:16:01 +00:00
|
|
|
import imp
|
2017-06-16 21:40:12 +00:00
|
|
|
import operator
|
2017-09-18 19:14:21 +00:00
|
|
|
import sys
|
|
|
|
import time
|
2017-12-15 11:07:16 +00:00
|
|
|
import csv
|
2018-02-15 11:40:38 +00:00
|
|
|
import inspect
|
2018-05-03 10:32:21 +00:00
|
|
|
from inspect import signature
|
2018-02-15 11:40:38 +00:00
|
|
|
from datetime import datetime, timedelta
|
2017-06-30 11:03:03 +00:00
|
|
|
|
2017-09-18 19:14:21 +00:00
|
|
|
import abc
|
|
|
|
import re
|
2017-08-17 09:49:00 +00:00
|
|
|
from adapt.intent import Intent, IntentBuilder
|
2018-02-14 13:41:12 +00:00
|
|
|
from os.path import join, abspath, dirname, basename, exists
|
2018-07-05 18:56:54 +00:00
|
|
|
from threading import Event, Timer
|
2017-04-17 17:25:27 +00:00
|
|
|
|
2018-03-01 02:04:22 +00:00
|
|
|
from mycroft import dialog
|
2017-11-16 01:09:48 +00:00
|
|
|
from mycroft.api import DeviceApi
|
2018-02-23 07:49:06 +00:00
|
|
|
from mycroft.audio import wait_while_speaking
|
2016-05-20 14:16:01 +00:00
|
|
|
from mycroft.client.enclosure.api import EnclosureAPI
|
2017-09-23 12:13:50 +00:00
|
|
|
from mycroft.configuration import Configuration
|
2016-05-20 14:16:01 +00:00
|
|
|
from mycroft.dialog import DialogLoader
|
|
|
|
from mycroft.filesystem import FileSystemAccess
|
|
|
|
from mycroft.messagebus.message import Message
|
2017-12-27 11:45:31 +00:00
|
|
|
from mycroft.metrics import report_metric, report_timing, Stopwatch
|
2017-04-13 05:26:45 +00:00
|
|
|
from mycroft.skills.settings import SkillSettings
|
2018-05-10 23:01:07 +00:00
|
|
|
from mycroft.skills.skill_data import (load_vocabulary, load_regex, to_alnum,
|
2018-02-23 06:51:55 +00:00
|
|
|
munge_regex, munge_intent_parser)
|
2018-08-12 08:29:44 +00:00
|
|
|
from mycroft.util import camel_case_split, resolve_resource_file
|
2017-09-18 19:14:21 +00:00
|
|
|
from mycroft.util.log import LOG
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
MainModule = '__init__'
|
|
|
|
|
|
|
|
|
2017-12-21 13:12:12 +00:00
|
|
|
def dig_for_message():
|
|
|
|
"""
|
|
|
|
Dig Through the stack for message.
|
|
|
|
"""
|
|
|
|
stack = inspect.stack()
|
|
|
|
# Limit search to 10 frames back
|
|
|
|
stack = stack if len(stack) < 10 else stack[:10]
|
|
|
|
local_vars = [frame[0].f_locals for frame in stack]
|
|
|
|
for l in local_vars:
|
|
|
|
if 'message' in l and isinstance(l['message'], Message):
|
|
|
|
return l['message']
|
|
|
|
|
|
|
|
|
2018-02-14 13:41:12 +00:00
|
|
|
def unmunge_message(message, skill_id):
|
|
|
|
"""Restore message keywords by removing the Letterified skill ID.
|
2017-08-21 15:05:03 +00:00
|
|
|
|
2018-02-14 13:41:12 +00:00
|
|
|
Args:
|
|
|
|
message (Message): Intent result message
|
2018-05-10 23:01:07 +00:00
|
|
|
skill_id (str): skill identifier
|
2017-08-21 15:05:03 +00:00
|
|
|
|
2018-02-14 13:41:12 +00:00
|
|
|
Returns:
|
|
|
|
Message without clear keywords
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
2018-02-15 20:11:21 +00:00
|
|
|
if isinstance(message, Message) and isinstance(message.data, dict):
|
2018-05-10 23:01:07 +00:00
|
|
|
skill_id = to_alnum(skill_id)
|
2018-07-19 07:03:43 +00:00
|
|
|
for key in list(message.data.keys()):
|
|
|
|
if key.startswith(skill_id):
|
|
|
|
# replace the munged key with the real one
|
2018-02-23 06:51:55 +00:00
|
|
|
new_key = key[len(skill_id):]
|
|
|
|
message.data[new_key] = message.data.pop(key)
|
2018-02-15 20:11:21 +00:00
|
|
|
|
2017-12-12 19:49:10 +00:00
|
|
|
return message
|
2016-06-28 20:20:48 +00:00
|
|
|
|
|
|
|
|
2016-05-20 14:16:01 +00:00
|
|
|
def open_intent_envelope(message):
|
2017-08-21 15:05:03 +00:00
|
|
|
""" Convert dictionary received over messagebus to Intent. """
|
2016-09-04 01:24:18 +00:00
|
|
|
intent_dict = message.data
|
2016-05-20 14:16:01 +00:00
|
|
|
return Intent(intent_dict.get('name'),
|
|
|
|
intent_dict.get('requires'),
|
|
|
|
intent_dict.get('at_least_one'),
|
|
|
|
intent_dict.get('optional'))
|
|
|
|
|
|
|
|
|
2017-09-11 11:11:56 +00:00
|
|
|
def load_skill(skill_descriptor, emitter, skill_id, BLACKLISTED_SKILLS=None):
|
2017-08-21 12:05:04 +00:00
|
|
|
"""
|
|
|
|
load skill from skill descriptor.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
skill_descriptor: descriptor of skill to load
|
|
|
|
emitter: messagebus emitter
|
|
|
|
skill_id: id number for skill
|
2017-11-09 10:34:00 +00:00
|
|
|
Returns:
|
|
|
|
MycroftSkill: the loaded skill or None on failure
|
2017-08-21 12:05:04 +00:00
|
|
|
"""
|
2017-09-11 11:11:56 +00:00
|
|
|
BLACKLISTED_SKILLS = BLACKLISTED_SKILLS or []
|
2018-05-08 00:24:26 +00:00
|
|
|
path = skill_descriptor["path"]
|
|
|
|
name = basename(path)
|
|
|
|
LOG.info("ATTEMPTING TO LOAD SKILL: {} with ID {}".format(
|
|
|
|
name, skill_id
|
|
|
|
))
|
|
|
|
if name in BLACKLISTED_SKILLS:
|
|
|
|
LOG.info("SKILL IS BLACKLISTED " + name)
|
|
|
|
return None
|
|
|
|
main_file = join(path, MainModule + '.py')
|
2016-05-20 14:16:01 +00:00
|
|
|
try:
|
2018-05-08 00:24:26 +00:00
|
|
|
with open(main_file, 'rb') as fp:
|
|
|
|
skill_module = imp.load_module(
|
|
|
|
name.replace('.', '_'), fp, main_file,
|
|
|
|
('.py', 'rb', imp.PY_SOURCE)
|
|
|
|
)
|
2016-05-20 22:15:53 +00:00
|
|
|
if (hasattr(skill_module, 'create_skill') and
|
|
|
|
callable(skill_module.create_skill)):
|
|
|
|
# v2 skills framework
|
2016-05-20 14:16:01 +00:00
|
|
|
skill = skill_module.create_skill()
|
2017-12-13 22:25:33 +00:00
|
|
|
skill.settings.allow_overwrite = True
|
2017-12-19 23:23:11 +00:00
|
|
|
skill.settings.load_skill_settings_from_file()
|
2016-05-20 14:16:01 +00:00
|
|
|
skill.bind(emitter)
|
2017-08-17 17:09:17 +00:00
|
|
|
skill.skill_id = skill_id
|
2018-05-08 00:24:26 +00:00
|
|
|
skill.load_data_files(path)
|
2017-06-30 11:03:03 +00:00
|
|
|
# Set up intent handlers
|
2017-02-05 16:01:12 +00:00
|
|
|
skill._register_decorated()
|
2018-07-14 09:36:16 +00:00
|
|
|
skill.initialize()
|
2018-05-08 00:24:26 +00:00
|
|
|
LOG.info("Loaded " + name)
|
2017-11-09 10:34:00 +00:00
|
|
|
|
|
|
|
# The very first time a skill is run, speak the intro
|
|
|
|
first_run = skill.settings.get("__mycroft_skill_firstrun", True)
|
|
|
|
if first_run:
|
2018-05-08 00:24:26 +00:00
|
|
|
LOG.info("First run of " + name)
|
2017-11-09 10:34:00 +00:00
|
|
|
skill.settings["__mycroft_skill_firstrun"] = False
|
|
|
|
skill.settings.store()
|
|
|
|
intro = skill.get_intro_message()
|
|
|
|
if intro:
|
|
|
|
skill.speak(intro)
|
2016-05-20 14:16:01 +00:00
|
|
|
return skill
|
|
|
|
else:
|
2018-05-08 00:24:26 +00:00
|
|
|
LOG.warning("Module {} does not appear to be skill".format(name))
|
|
|
|
except Exception:
|
|
|
|
LOG.exception("Failed to load skill: " + name)
|
2016-05-20 14:16:01 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
2018-05-08 00:24:26 +00:00
|
|
|
def create_skill_descriptor(skill_path):
|
|
|
|
return {"path": skill_path}
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
|
2017-09-14 21:17:02 +00:00
|
|
|
def get_handler_name(handler):
|
|
|
|
"""
|
|
|
|
Return name (including class if available) of handler
|
|
|
|
function.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
handler (function): Function to be named
|
|
|
|
|
|
|
|
Returns: handler name as string
|
|
|
|
"""
|
|
|
|
name = ''
|
2017-09-28 15:53:57 +00:00
|
|
|
if '__self__' in dir(handler) and 'name' in dir(handler.__self__):
|
2017-09-14 21:17:02 +00:00
|
|
|
name += handler.__self__.name + '.'
|
|
|
|
name += handler.__name__
|
|
|
|
return name
|
|
|
|
|
|
|
|
|
2017-01-31 06:28:04 +00:00
|
|
|
def intent_handler(intent_parser):
|
2017-02-05 15:59:46 +00:00
|
|
|
""" Decorator for adding a method as an intent handler. """
|
2017-08-17 17:09:17 +00:00
|
|
|
|
2017-01-31 06:28:04 +00:00
|
|
|
def real_decorator(func):
|
2018-03-01 00:53:56 +00:00
|
|
|
# Store the intent_parser inside the function
|
|
|
|
# This will be used later to call register_intent
|
|
|
|
if not hasattr(func, 'intents'):
|
|
|
|
func.intents = []
|
|
|
|
func.intents.append(intent_parser)
|
|
|
|
return func
|
2017-08-17 17:09:17 +00:00
|
|
|
|
2017-01-31 06:28:04 +00:00
|
|
|
return real_decorator
|
|
|
|
|
|
|
|
|
2017-08-17 15:44:46 +00:00
|
|
|
def intent_file_handler(intent_file):
|
|
|
|
""" Decorator for adding a method as an intent file handler. """
|
2017-09-28 15:53:57 +00:00
|
|
|
|
2017-08-17 15:44:46 +00:00
|
|
|
def real_decorator(func):
|
2018-03-01 00:53:56 +00:00
|
|
|
# Store the intent_file inside the function
|
|
|
|
# This will be used later to call register_intent_file
|
|
|
|
if not hasattr(func, 'intent_files'):
|
|
|
|
func.intent_files = []
|
|
|
|
func.intent_files.append(intent_file)
|
|
|
|
return func
|
2017-09-28 15:53:57 +00:00
|
|
|
|
2017-08-17 15:44:46 +00:00
|
|
|
return real_decorator
|
|
|
|
|
|
|
|
|
2017-11-09 10:34:00 +00:00
|
|
|
#######################################################################
|
|
|
|
# MycroftSkill base class
|
|
|
|
#######################################################################
|
2016-05-20 14:16:01 +00:00
|
|
|
class MycroftSkill(object):
|
|
|
|
"""
|
2016-05-20 22:15:53 +00:00
|
|
|
Abstract base class which provides common behaviour and parameters to all
|
|
|
|
Skills implementation.
|
2016-05-20 14:16:01 +00:00
|
|
|
"""
|
|
|
|
|
2017-07-18 06:40:55 +00:00
|
|
|
def __init__(self, name=None, emitter=None):
|
|
|
|
self.name = name or self.__class__.__name__
|
2017-08-31 19:17:48 +00:00
|
|
|
# Get directory of skill
|
|
|
|
self._dir = dirname(abspath(sys.modules[self.__module__].__file__))
|
2018-04-09 22:07:51 +00:00
|
|
|
self.settings = SkillSettings(self._dir, self.name)
|
2017-08-31 19:17:48 +00:00
|
|
|
|
2016-05-20 14:16:01 +00:00
|
|
|
self.bind(emitter)
|
2017-09-23 12:13:50 +00:00
|
|
|
self.config_core = Configuration.get()
|
2018-04-05 04:12:55 +00:00
|
|
|
self.config = self.config_core.get(self.name) or {}
|
2016-05-20 14:16:01 +00:00
|
|
|
self.dialog_renderer = None
|
2017-05-31 19:53:21 +00:00
|
|
|
self.vocab_dir = None
|
2017-11-16 01:09:48 +00:00
|
|
|
self.root_dir = None
|
2017-07-18 06:40:55 +00:00
|
|
|
self.file_system = FileSystemAccess(join('skills', self.name))
|
2016-05-20 14:16:01 +00:00
|
|
|
self.registered_intents = []
|
2017-09-18 18:55:58 +00:00
|
|
|
self.log = LOG.create_logger(self.name)
|
2018-02-13 08:54:12 +00:00
|
|
|
self.reload_skill = True # allow reloading
|
2017-04-17 17:25:27 +00:00
|
|
|
self.events = []
|
2018-03-15 10:42:08 +00:00
|
|
|
self.scheduled_repeats = []
|
Fix named event scheduling/deleting (#1705)
While working on the Alarm skill I discovered several issues with the
event scheduler. This PR cleans up those findings and resolves several
other potential issues:
1) To avoid thread synchronization issues, the EventScheduler had several
queues which independently held objects to be added/deleted/updated. However, the order of the events was undefined and got mixed since they were all batched together. So, for instance, if skill code performed:
self.add_event("foo", self.handle_foo)
if SomeReason:
self.cancel_event("foo")
The actual order of queue handling would perform Remove first, then Add which resulted in "foo" not being found for delete, but then added and left as an active event.
Now the EventScheduler protects the list using a Lock and the queues have been removed. Modifications to the list happen immediately after obtaining the lock and are not batched up.
2) One-time events were triggered while the event was still in the EventScheduler list. Now the entry is removed before invoking the handler.
3) Within the MycroftSkill.add_event(name, handler) is a local 'wrapper' method that actually makes the callback. The MycroftSkill.remove_event(name) method attempted to find entries in the events list and the associated handler entries in the self.emitter to remove. However, the emitter actually held the wrapper(handler), not the handler itself. So the emitter handlers were left behind.
This was a quiet bug until the next time you scheduled an event of the same name. When that second event finally triggered, it would fire off both the new and the old handler -- which snowballed in the 'skill-alarm:Beep' case, doubling and redoubling with every beep.
Now this cancels all the emitter listeners by name. There is a very slim chance that someone has registered a listener with the same name, but since it is namespaced to "skill-name:Event" I think this is pretty safe.
Not technically related, but a failure that has been lurking for
some time and is a French unit test that doesn't work depending
on the time of day when the test is run.
2018-07-30 20:08:13 +00:00
|
|
|
self.skill_id = '' # will be set from the path, so guaranteed unique
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def location(self):
|
2017-02-03 10:08:43 +00:00
|
|
|
""" Get the JSON data struction holding location information. """
|
|
|
|
# TODO: Allow Enclosure to override this for devices that
|
|
|
|
# contain a GPS.
|
2016-05-20 14:16:01 +00:00
|
|
|
return self.config_core.get('location')
|
|
|
|
|
2017-02-03 10:08:43 +00:00
|
|
|
@property
|
|
|
|
def location_pretty(self):
|
|
|
|
""" Get a more 'human' version of the location as a string. """
|
|
|
|
loc = self.location
|
|
|
|
if type(loc) is dict and loc["city"]:
|
|
|
|
return loc["city"]["name"]
|
|
|
|
return None
|
2017-02-15 20:57:15 +00:00
|
|
|
|
2017-02-03 10:08:43 +00:00
|
|
|
@property
|
|
|
|
def location_timezone(self):
|
|
|
|
""" Get the timezone code, such as 'America/Los_Angeles' """
|
|
|
|
loc = self.location
|
|
|
|
if type(loc) is dict and loc["timezone"]:
|
|
|
|
return loc["timezone"]["code"]
|
|
|
|
return None
|
|
|
|
|
2016-05-20 14:16:01 +00:00
|
|
|
@property
|
|
|
|
def lang(self):
|
|
|
|
return self.config_core.get('lang')
|
|
|
|
|
|
|
|
def bind(self, emitter):
|
2017-08-21 15:05:03 +00:00
|
|
|
""" Register emitter with skill. """
|
2016-05-20 14:16:01 +00:00
|
|
|
if emitter:
|
2018-07-05 18:56:54 +00:00
|
|
|
self.emitter = emitter # TODO:18.08 - move to self.messagbus name
|
2017-06-16 18:31:44 +00:00
|
|
|
self.enclosure = EnclosureAPI(emitter, self.name)
|
2018-07-05 18:56:54 +00:00
|
|
|
self.add_event('mycroft.stop', self.__handle_stop)
|
2017-06-29 20:54:18 +00:00
|
|
|
self.add_event('mycroft.skill.enable_intent',
|
|
|
|
self.handle_enable_intent)
|
|
|
|
self.add_event('mycroft.skill.disable_intent',
|
|
|
|
self.handle_disable_intent)
|
2016-05-20 14:16:01 +00:00
|
|
|
|
2018-04-09 22:07:51 +00:00
|
|
|
name = 'mycroft.skills.settings.update'
|
|
|
|
func = self.settings.run_poll
|
|
|
|
emitter.on(name, func)
|
|
|
|
self.events.append((name, func))
|
|
|
|
|
2016-05-20 14:16:01 +00:00
|
|
|
def detach(self):
|
2017-03-14 21:01:48 +00:00
|
|
|
for (name, intent) in self.registered_intents:
|
2017-08-17 17:09:17 +00:00
|
|
|
name = str(self.skill_id) + ':' + name
|
2016-09-04 01:24:18 +00:00
|
|
|
self.emitter.emit(Message("detach_intent", {"intent_name": name}))
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
def initialize(self):
|
|
|
|
"""
|
2017-12-05 23:57:28 +00:00
|
|
|
Invoked after the skill is fully constructed and registered with the
|
|
|
|
system. Use to perform any final setup needed for the skill.
|
2016-05-20 14:16:01 +00:00
|
|
|
"""
|
2017-12-05 17:18:12 +00:00
|
|
|
pass
|
2016-05-20 14:16:01 +00:00
|
|
|
|
2017-11-09 10:34:00 +00:00
|
|
|
def get_intro_message(self):
|
|
|
|
"""
|
|
|
|
Get a message to speak on first load of the skill. Useful
|
|
|
|
for post-install setup instructions.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: message that will be spoken to the user
|
|
|
|
"""
|
|
|
|
return None
|
|
|
|
|
2017-08-17 17:09:17 +00:00
|
|
|
def converse(self, utterances, lang="en-us"):
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
|
|
|
Handle conversation. This method can be used to override the normal
|
|
|
|
intent handler after the skill has been invoked once.
|
|
|
|
|
|
|
|
To enable this override thise converse method and return True to
|
|
|
|
indicate that the utterance has been handled.
|
|
|
|
|
|
|
|
Args:
|
2017-12-04 23:53:49 +00:00
|
|
|
utterances (list): The utterances from the user
|
2017-08-21 15:05:03 +00:00
|
|
|
lang: language the utterance is in
|
|
|
|
|
|
|
|
Returns: True if an utterance was handled, otherwise False
|
|
|
|
"""
|
2017-08-17 17:09:17 +00:00
|
|
|
return False
|
|
|
|
|
2017-12-04 23:53:49 +00:00
|
|
|
def __get_response(self):
|
|
|
|
"""
|
2017-12-07 20:58:36 +00:00
|
|
|
Helper to get a reponse from the user
|
|
|
|
|
2017-12-04 23:53:49 +00:00
|
|
|
Returns:
|
2017-12-07 20:58:36 +00:00
|
|
|
str: user's response or None on a timeout
|
2017-12-04 23:53:49 +00:00
|
|
|
"""
|
|
|
|
event = Event()
|
|
|
|
|
|
|
|
def converse(utterances, lang="en-us"):
|
|
|
|
converse.response = utterances[0] if utterances else None
|
|
|
|
event.set()
|
|
|
|
return True
|
|
|
|
|
2017-12-07 20:58:36 +00:00
|
|
|
# install a temporary conversation handler
|
2017-12-04 23:53:49 +00:00
|
|
|
self.make_active()
|
|
|
|
converse.response = None
|
|
|
|
default_converse = self.converse
|
|
|
|
self.converse = converse
|
2017-12-07 21:34:48 +00:00
|
|
|
event.wait(15) # 10 for listener, 5 for SST, then timeout
|
2017-12-04 23:53:49 +00:00
|
|
|
self.converse = default_converse
|
|
|
|
return converse.response
|
|
|
|
|
2017-12-07 20:58:36 +00:00
|
|
|
def get_response(self, dialog='', data=None, announcement='',
|
|
|
|
validator=None, on_fail=None, num_retries=-1):
|
2017-12-04 23:53:49 +00:00
|
|
|
"""
|
2017-12-07 20:58:36 +00:00
|
|
|
Prompt user and wait for response
|
|
|
|
|
|
|
|
The given dialog or announcement will be spoken, the immediately
|
|
|
|
listen and return user response. The response can optionally be
|
|
|
|
validated.
|
|
|
|
|
|
|
|
Example:
|
|
|
|
color = self.get_response('ask.favorite.color')
|
2017-12-04 23:53:49 +00:00
|
|
|
|
|
|
|
Args:
|
2017-12-07 20:58:36 +00:00
|
|
|
dialog (str): Announcement dialog to read to the user
|
2017-12-04 23:53:49 +00:00
|
|
|
data (dict): Data used to render the dialog
|
2017-12-07 20:58:36 +00:00
|
|
|
announcement (str): Literal string (overrides dialog)
|
2017-12-04 23:53:49 +00:00
|
|
|
validator (any): Function with following signature
|
|
|
|
def validator(utterance):
|
2017-12-07 20:58:36 +00:00
|
|
|
return utterance != "red"
|
|
|
|
on_fail (any): Dialog or function returning literal string
|
|
|
|
to speak on invalid input. For example:
|
2017-12-04 23:53:49 +00:00
|
|
|
def on_fail(utterance):
|
2017-12-07 20:58:36 +00:00
|
|
|
return "nobody likes the color red, pick another"
|
|
|
|
num_retries (int): Times to ask user for input, -1 for infinite
|
|
|
|
NOTE: User can not respond and timeout or say "cancel" to stop
|
|
|
|
|
2017-12-04 23:53:49 +00:00
|
|
|
Returns:
|
2017-12-07 20:58:36 +00:00
|
|
|
str: User's reply or None if timed out or canceled
|
2017-12-04 23:53:49 +00:00
|
|
|
"""
|
|
|
|
data = data or {}
|
|
|
|
|
2017-12-07 21:34:48 +00:00
|
|
|
def get_announcement():
|
2018-07-19 07:00:17 +00:00
|
|
|
nonlocal announcement
|
|
|
|
# The dialog param can be either a spoken string or a dialog file
|
|
|
|
# TODO: 18.08 merge dialog/announcement
|
|
|
|
if not exists(join(self.root_dir, 'dialog', self.lang,
|
|
|
|
dialog + '.dialog')) and not announcement:
|
|
|
|
announcement = dialog
|
2017-12-07 21:34:48 +00:00
|
|
|
return announcement or self.dialog_renderer.render(dialog, data)
|
|
|
|
|
|
|
|
if not get_announcement():
|
2017-12-07 20:58:36 +00:00
|
|
|
raise ValueError('announcement or dialog message required')
|
2017-12-04 23:53:49 +00:00
|
|
|
|
|
|
|
def on_fail_default(utterance):
|
|
|
|
fail_data = data.copy()
|
|
|
|
fail_data['utterance'] = utterance
|
|
|
|
if on_fail:
|
|
|
|
return self.dialog_renderer.render(on_fail, fail_data)
|
|
|
|
else:
|
2017-12-07 21:34:48 +00:00
|
|
|
return get_announcement()
|
2017-12-04 23:53:49 +00:00
|
|
|
|
|
|
|
def is_cancel(utterance):
|
2018-07-17 06:35:55 +00:00
|
|
|
return self.is_match(utterance, 'cancel')
|
2017-12-07 20:58:36 +00:00
|
|
|
|
2017-12-07 21:49:52 +00:00
|
|
|
def validator_default(utterance):
|
2017-12-07 20:58:36 +00:00
|
|
|
# accept anything except 'cancel'
|
|
|
|
return not is_cancel(utterance)
|
2017-12-04 23:53:49 +00:00
|
|
|
|
2017-12-07 21:49:52 +00:00
|
|
|
validator = validator or validator_default
|
2017-12-04 23:53:49 +00:00
|
|
|
on_fail_fn = on_fail if callable(on_fail) else on_fail_default
|
|
|
|
|
2017-12-07 21:34:48 +00:00
|
|
|
self.speak(get_announcement(), expect_response=True)
|
2018-02-23 07:49:06 +00:00
|
|
|
wait_while_speaking()
|
2017-12-04 23:53:49 +00:00
|
|
|
num_fails = 0
|
|
|
|
while True:
|
|
|
|
response = self.__get_response()
|
|
|
|
|
|
|
|
if response is None:
|
2017-12-07 20:58:36 +00:00
|
|
|
# if nothing said, prompt one more time
|
2017-12-04 23:53:49 +00:00
|
|
|
num_none_fails = 1 if num_retries < 0 else num_retries
|
|
|
|
if num_fails >= num_none_fails:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
if validator(response):
|
|
|
|
return response
|
|
|
|
|
2017-12-07 20:58:36 +00:00
|
|
|
# catch user saying 'cancel'
|
2017-12-04 23:53:49 +00:00
|
|
|
if is_cancel(response):
|
|
|
|
return None
|
|
|
|
|
|
|
|
num_fails += 1
|
|
|
|
if 0 < num_retries < num_fails:
|
|
|
|
return None
|
|
|
|
|
|
|
|
line = on_fail_fn(response)
|
|
|
|
self.speak(line, expect_response=True)
|
|
|
|
|
2018-07-17 06:35:55 +00:00
|
|
|
def ask_yesno(self, prompt, data=None):
|
|
|
|
"""
|
|
|
|
Read prompt and wait for a yes/no answer
|
|
|
|
|
|
|
|
This automatically deals with translation and common variants,
|
|
|
|
such as 'yeah', 'sure', etc.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
prompt (str): a dialog id or string to read
|
|
|
|
Returns:
|
|
|
|
string: 'yes', 'no' or whatever the user response if not
|
|
|
|
one of those, including None
|
|
|
|
"""
|
|
|
|
resp = self.get_response(dialog=prompt, data=data)
|
|
|
|
|
|
|
|
if self.is_match(resp, 'yes'):
|
|
|
|
return 'yes'
|
|
|
|
|
|
|
|
if self.is_match(resp, 'no'):
|
|
|
|
return 'no'
|
|
|
|
|
|
|
|
return resp
|
|
|
|
|
|
|
|
def is_match(self, utt, voc_filename, lang=None):
|
|
|
|
""" Determine if the given utterance contains the vocabular proviced
|
|
|
|
|
|
|
|
This checks for vocabulary match in the utternce instead of the other
|
|
|
|
way around to allow the user to say things like "yes, please" and
|
|
|
|
still match against voc files with only "yes" in it.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
utt (str): Utterance to be tested
|
|
|
|
voc_filename (str): Name of vocabulary file (e.g. 'yes' for
|
|
|
|
'res/text/en-us/yes.voc')
|
|
|
|
lang (str): Language code, defaults to self.long
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: True if the utterance has the given vocabulary it
|
|
|
|
"""
|
|
|
|
lang = lang or self.lang
|
|
|
|
voc = join('text', self.lang, voc_filename+".voc")
|
|
|
|
with open(resolve_resource_file(voc)) as f:
|
|
|
|
words = list(filter(bool, f.read().split('\n')))
|
|
|
|
if (utt and any(i.strip() in utt for i in words)):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2017-11-18 01:16:00 +00:00
|
|
|
def report_metric(self, name, data):
|
|
|
|
"""
|
|
|
|
Report a skill metric to the Mycroft servers
|
|
|
|
|
|
|
|
Args:
|
2017-12-01 21:17:40 +00:00
|
|
|
name (str): Name of metric. Must use only letters and hyphens
|
2017-11-18 01:16:00 +00:00
|
|
|
data (dict): JSON dictionary to report. Must be valid JSON
|
|
|
|
"""
|
2017-12-01 21:17:40 +00:00
|
|
|
report_metric(basename(self.root_dir) + ':' + name, data)
|
2017-11-18 01:16:00 +00:00
|
|
|
|
2017-11-16 01:09:48 +00:00
|
|
|
def send_email(self, title, body):
|
|
|
|
"""
|
|
|
|
Send an email to the registered user's email
|
|
|
|
|
|
|
|
Args:
|
|
|
|
title (str): Title of email
|
|
|
|
body (str): HTML body of email. This supports
|
|
|
|
simple HTML like bold and italics
|
|
|
|
"""
|
|
|
|
DeviceApi().send_email(title, body, basename(self.root_dir))
|
|
|
|
|
2017-08-17 17:09:17 +00:00
|
|
|
def make_active(self):
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
|
|
|
Bump skill to active_skill list in intent_service
|
|
|
|
this enables converse method to be called even without skill being
|
|
|
|
used in last 5 minutes
|
|
|
|
"""
|
2017-08-17 17:09:17 +00:00
|
|
|
self.emitter.emit(Message('active_skill_request',
|
|
|
|
{"skill_id": self.skill_id}))
|
|
|
|
|
2017-02-05 15:59:46 +00:00
|
|
|
def _register_decorated(self):
|
|
|
|
"""
|
2017-11-09 10:34:00 +00:00
|
|
|
Register all intent handlers that have been decorated with an intent.
|
2018-03-01 00:53:56 +00:00
|
|
|
|
|
|
|
Looks for all functions that have been marked by a decorator
|
|
|
|
and read the intent data from them
|
2017-02-05 15:59:46 +00:00
|
|
|
"""
|
2018-03-01 00:53:56 +00:00
|
|
|
for attr_name in dir(self):
|
|
|
|
method = getattr(self, attr_name)
|
|
|
|
|
|
|
|
if hasattr(method, 'intents'):
|
|
|
|
for intent in getattr(method, 'intents'):
|
|
|
|
self.register_intent(intent, method)
|
|
|
|
|
|
|
|
if hasattr(method, 'intent_files'):
|
|
|
|
for intent_file in getattr(method, 'intent_files'):
|
|
|
|
self.register_intent_file(intent_file, method)
|
2017-01-31 06:28:04 +00:00
|
|
|
|
2017-12-07 02:32:20 +00:00
|
|
|
def translate(self, text, data=None):
|
|
|
|
"""
|
2017-12-07 07:41:38 +00:00
|
|
|
Load a translatable single string resource
|
|
|
|
|
|
|
|
The string is loaded from a file in the skill's dialog subdirectory
|
|
|
|
'dialog/<lang>/<text>.dialog'
|
|
|
|
The string is randomly chosen from the file and rendered, replacing
|
|
|
|
mustache placeholders with values found in the data dictionary.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
text (str): The base filename (no extension needed)
|
|
|
|
data (dict, optional): a JSON dictionary
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: A randomly chosen string from the file
|
2017-12-07 02:32:20 +00:00
|
|
|
"""
|
|
|
|
return self.dialog_renderer.render(text, data or {})
|
|
|
|
|
2017-12-15 11:07:16 +00:00
|
|
|
def translate_namedvalues(self, name, delim=None):
|
|
|
|
"""
|
|
|
|
Load translation dict containing names and values.
|
|
|
|
|
|
|
|
This loads a simple CSV from the 'dialog' folders.
|
|
|
|
The name is the first list item, the value is the
|
|
|
|
second. Lines prefixed with # or // get ignored
|
|
|
|
|
|
|
|
Args:
|
|
|
|
name (str): name of the .value file, no extension needed
|
|
|
|
delim (char): delimiter character used, default is ','
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict: name and value dictionary, or [] if load fails
|
|
|
|
"""
|
|
|
|
|
|
|
|
delim = delim or ','
|
|
|
|
result = {}
|
|
|
|
if not name.endswith(".value"):
|
|
|
|
name += ".value"
|
|
|
|
|
|
|
|
try:
|
|
|
|
with open(join(self.root_dir, 'dialog', self.lang, name)) as f:
|
|
|
|
reader = csv.reader(f, delimiter=delim)
|
|
|
|
for row in reader:
|
|
|
|
# skip blank or comment lines
|
|
|
|
if not row or row[0].startswith("#"):
|
|
|
|
continue
|
|
|
|
if len(row) != 2:
|
|
|
|
continue
|
|
|
|
|
|
|
|
result[row[0]] = row[1]
|
|
|
|
|
|
|
|
return result
|
2017-12-15 11:40:41 +00:00
|
|
|
except Exception:
|
2017-12-15 11:07:16 +00:00
|
|
|
return {}
|
2017-12-15 11:19:11 +00:00
|
|
|
|
2017-12-07 02:32:20 +00:00
|
|
|
def translate_template(self, template_name, data=None):
|
|
|
|
"""
|
2017-12-07 07:41:38 +00:00
|
|
|
Load a translatable template
|
|
|
|
|
|
|
|
The strings are loaded from a template file in the skill's dialog
|
|
|
|
subdirectory.
|
|
|
|
'dialog/<lang>/<template_name>.template'
|
|
|
|
The strings are loaded and rendered, replacing mustache placeholders
|
|
|
|
with values found in the data dictionary.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
template_name (str): The base filename (no extension needed)
|
|
|
|
data (dict, optional): a JSON dictionary
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
list of str: The loaded template file
|
2017-12-07 02:32:20 +00:00
|
|
|
"""
|
|
|
|
return self.__translate_file(template_name + '.template', data)
|
|
|
|
|
|
|
|
def translate_list(self, list_name, data=None):
|
|
|
|
"""
|
2017-12-07 07:41:38 +00:00
|
|
|
Load a list of translatable string resources
|
|
|
|
|
|
|
|
The strings are loaded from a list file in the skill's dialog
|
|
|
|
subdirectory.
|
|
|
|
'dialog/<lang>/<list_name>.list'
|
|
|
|
The strings are loaded and rendered, replacing mustache placeholders
|
|
|
|
with values found in the data dictionary.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
list_name (str): The base filename (no extension needed)
|
|
|
|
data (dict, optional): a JSON dictionary
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
list of str: The loaded list of strings with items in consistent
|
|
|
|
positions regardless of the language.
|
2017-12-07 02:32:20 +00:00
|
|
|
"""
|
|
|
|
return self.__translate_file(list_name + '.list', data)
|
|
|
|
|
|
|
|
def __translate_file(self, name, data):
|
|
|
|
"""Load and render lines from dialog/<lang>/<name>"""
|
|
|
|
with open(join(self.root_dir, 'dialog', self.lang, name)) as f:
|
2017-12-12 19:47:01 +00:00
|
|
|
text = f.read().replace('{{', '{').replace('}}', '}')
|
2017-12-07 02:32:20 +00:00
|
|
|
return text.format(**data or {}).split('\n')
|
|
|
|
|
2018-03-01 02:04:22 +00:00
|
|
|
def add_event(self, name, handler, handler_info=None, once=False):
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
|
|
|
Create event handler for executing intent
|
|
|
|
|
|
|
|
Args:
|
2017-11-27 13:53:30 +00:00
|
|
|
name: IntentParser name
|
|
|
|
handler: method to call
|
|
|
|
handler_info: base message when reporting skill event handler
|
|
|
|
status on messagebus.
|
2018-03-01 02:04:22 +00:00
|
|
|
once: optional parameter, Event handler will be
|
|
|
|
removed after it has been run once.
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
2017-09-28 15:53:57 +00:00
|
|
|
|
2017-05-31 19:53:21 +00:00
|
|
|
def wrapper(message):
|
2018-03-01 02:04:22 +00:00
|
|
|
skill_data = {'name': get_handler_name(handler)}
|
2018-03-07 16:13:20 +00:00
|
|
|
stopwatch = Stopwatch()
|
2017-05-31 19:53:21 +00:00
|
|
|
try:
|
2018-03-01 02:04:22 +00:00
|
|
|
message = unmunge_message(message, self.skill_id)
|
2017-09-14 15:18:51 +00:00
|
|
|
# Indicate that the skill handler is starting
|
2017-11-27 13:53:30 +00:00
|
|
|
if handler_info:
|
|
|
|
# Indicate that the skill handler is starting if requested
|
|
|
|
msg_type = handler_info + '.start'
|
2018-04-27 14:12:23 +00:00
|
|
|
self.emitter.emit(message.reply(msg_type, skill_data))
|
2017-12-21 00:05:14 +00:00
|
|
|
|
Fix named event scheduling/deleting (#1705)
While working on the Alarm skill I discovered several issues with the
event scheduler. This PR cleans up those findings and resolves several
other potential issues:
1) To avoid thread synchronization issues, the EventScheduler had several
queues which independently held objects to be added/deleted/updated. However, the order of the events was undefined and got mixed since they were all batched together. So, for instance, if skill code performed:
self.add_event("foo", self.handle_foo)
if SomeReason:
self.cancel_event("foo")
The actual order of queue handling would perform Remove first, then Add which resulted in "foo" not being found for delete, but then added and left as an active event.
Now the EventScheduler protects the list using a Lock and the queues have been removed. Modifications to the list happen immediately after obtaining the lock and are not batched up.
2) One-time events were triggered while the event was still in the EventScheduler list. Now the entry is removed before invoking the handler.
3) Within the MycroftSkill.add_event(name, handler) is a local 'wrapper' method that actually makes the callback. The MycroftSkill.remove_event(name) method attempted to find entries in the events list and the associated handler entries in the self.emitter to remove. However, the emitter actually held the wrapper(handler), not the handler itself. So the emitter handlers were left behind.
This was a quiet bug until the next time you scheduled an event of the same name. When that second event finally triggered, it would fire off both the new and the old handler -- which snowballed in the 'skill-alarm:Beep' case, doubling and redoubling with every beep.
Now this cancels all the emitter listeners by name. There is a very slim chance that someone has registered a listener with the same name, but since it is namespaced to "skill-name:Event" I think this is pretty safe.
Not technically related, but a failure that has been lurking for
some time and is a French unit test that doesn't work depending
on the time of day when the test is run.
2018-07-30 20:08:13 +00:00
|
|
|
if once:
|
|
|
|
# Remove registered one-time handler before invoking,
|
|
|
|
# allowing them to re-schedule themselves.
|
|
|
|
self.remove_event(name)
|
|
|
|
|
2017-12-21 00:05:14 +00:00
|
|
|
with stopwatch:
|
2018-04-27 16:42:54 +00:00
|
|
|
if len(signature(handler).parameters) == 0:
|
2018-03-01 02:04:22 +00:00
|
|
|
handler()
|
2017-08-24 04:15:25 +00:00
|
|
|
else:
|
2018-03-01 02:04:22 +00:00
|
|
|
handler(message)
|
2017-12-21 00:05:14 +00:00
|
|
|
self.settings.store() # Store settings if they've changed
|
|
|
|
|
2017-09-14 21:17:02 +00:00
|
|
|
except Exception as e:
|
2017-12-06 09:55:54 +00:00
|
|
|
# Convert "MyFancySkill" to "My Fancy Skill" for speaking
|
2018-08-12 08:29:44 +00:00
|
|
|
handler_name = camel_case_split(self.name)
|
2018-03-01 02:04:22 +00:00
|
|
|
msg_data = {'skill': handler_name}
|
|
|
|
msg = dialog.get('skill.error', self.lang, msg_data)
|
|
|
|
self.speak(msg)
|
|
|
|
LOG.exception(msg)
|
2017-11-27 13:53:30 +00:00
|
|
|
# append exception information in message
|
2018-06-01 21:11:14 +00:00
|
|
|
skill_data['exception'] = repr(e)
|
2017-11-27 13:53:30 +00:00
|
|
|
finally:
|
|
|
|
# Indicate that the skill handler has completed
|
|
|
|
if handler_info:
|
|
|
|
msg_type = handler_info + '.complete'
|
2018-04-27 14:12:23 +00:00
|
|
|
self.emitter.emit(message.reply(msg_type, skill_data))
|
2017-11-27 13:53:30 +00:00
|
|
|
|
|
|
|
# Send timing metrics
|
|
|
|
context = message.context
|
|
|
|
if context and 'ident' in context:
|
|
|
|
report_timing(context['ident'], 'skill_handler', stopwatch,
|
|
|
|
{'handler': handler.__name__})
|
2017-09-28 15:53:57 +00:00
|
|
|
|
2017-05-31 19:53:21 +00:00
|
|
|
if handler:
|
2018-01-16 11:14:07 +00:00
|
|
|
if once:
|
|
|
|
self.emitter.once(name, wrapper)
|
|
|
|
else:
|
|
|
|
self.emitter.on(name, wrapper)
|
2017-05-31 19:53:21 +00:00
|
|
|
self.events.append((name, wrapper))
|
|
|
|
|
2017-10-30 15:13:44 +00:00
|
|
|
def remove_event(self, name):
|
|
|
|
"""
|
|
|
|
Removes an event from emitter and events list
|
|
|
|
|
|
|
|
Args:
|
2017-11-01 00:27:58 +00:00
|
|
|
name: Name of Intent or Scheduler Event
|
2018-02-13 08:54:12 +00:00
|
|
|
Returns:
|
|
|
|
bool: True if found and removed, False if not found
|
2017-10-30 15:13:44 +00:00
|
|
|
"""
|
2018-02-13 08:54:12 +00:00
|
|
|
removed = False
|
2017-10-30 15:17:46 +00:00
|
|
|
for _name, _handler in self.events:
|
|
|
|
if name == _name:
|
2018-01-16 11:14:07 +00:00
|
|
|
try:
|
|
|
|
self.events.remove((_name, _handler))
|
|
|
|
except ValueError:
|
|
|
|
pass
|
2018-02-15 20:52:18 +00:00
|
|
|
removed = True
|
Fix named event scheduling/deleting (#1705)
While working on the Alarm skill I discovered several issues with the
event scheduler. This PR cleans up those findings and resolves several
other potential issues:
1) To avoid thread synchronization issues, the EventScheduler had several
queues which independently held objects to be added/deleted/updated. However, the order of the events was undefined and got mixed since they were all batched together. So, for instance, if skill code performed:
self.add_event("foo", self.handle_foo)
if SomeReason:
self.cancel_event("foo")
The actual order of queue handling would perform Remove first, then Add which resulted in "foo" not being found for delete, but then added and left as an active event.
Now the EventScheduler protects the list using a Lock and the queues have been removed. Modifications to the list happen immediately after obtaining the lock and are not batched up.
2) One-time events were triggered while the event was still in the EventScheduler list. Now the entry is removed before invoking the handler.
3) Within the MycroftSkill.add_event(name, handler) is a local 'wrapper' method that actually makes the callback. The MycroftSkill.remove_event(name) method attempted to find entries in the events list and the associated handler entries in the self.emitter to remove. However, the emitter actually held the wrapper(handler), not the handler itself. So the emitter handlers were left behind.
This was a quiet bug until the next time you scheduled an event of the same name. When that second event finally triggered, it would fire off both the new and the old handler -- which snowballed in the 'skill-alarm:Beep' case, doubling and redoubling with every beep.
Now this cancels all the emitter listeners by name. There is a very slim chance that someone has registered a listener with the same name, but since it is namespaced to "skill-name:Event" I think this is pretty safe.
Not technically related, but a failure that has been lurking for
some time and is a French unit test that doesn't work depending
on the time of day when the test is run.
2018-07-30 20:08:13 +00:00
|
|
|
|
|
|
|
# Because of function wrappers, the emitter doesn't always directly
|
|
|
|
# hold the _handler function, it sometimes holds something like
|
|
|
|
# 'wrapper(_handler)'. So a call like:
|
|
|
|
# self.emitter.remove(_name, _handler)
|
|
|
|
# will not find it, leaving an event handler with that name left behind
|
|
|
|
# waiting to fire if it is ever re-installed and triggered.
|
|
|
|
# Remove all handlers with the given name, regardless of handler.
|
|
|
|
if removed:
|
|
|
|
self.emitter.remove_all_listeners(name)
|
2018-02-15 20:52:18 +00:00
|
|
|
return removed
|
2017-10-30 15:13:44 +00:00
|
|
|
|
2018-03-01 00:53:56 +00:00
|
|
|
def register_intent(self, intent_parser, handler):
|
2017-08-17 09:49:00 +00:00
|
|
|
"""
|
|
|
|
Register an Intent with the intent service.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
intent_parser: Intent or IntentBuilder object to parse
|
|
|
|
utterance for the handler.
|
2017-05-31 19:53:21 +00:00
|
|
|
handler: function to register with intent
|
2017-08-17 09:49:00 +00:00
|
|
|
"""
|
2018-06-02 06:56:15 +00:00
|
|
|
if isinstance(intent_parser, IntentBuilder):
|
2017-08-17 09:49:00 +00:00
|
|
|
intent_parser = intent_parser.build()
|
2018-06-02 06:56:15 +00:00
|
|
|
elif not isinstance(intent_parser, Intent):
|
2017-08-17 09:49:00 +00:00
|
|
|
raise ValueError('intent_parser is not an Intent')
|
|
|
|
|
2017-12-05 23:57:28 +00:00
|
|
|
# Default to the handler's function name if none given
|
|
|
|
name = intent_parser.name or handler.__name__
|
2017-12-12 19:49:10 +00:00
|
|
|
munge_intent_parser(intent_parser, name, self.skill_id)
|
2016-09-04 01:24:18 +00:00
|
|
|
self.emitter.emit(Message("register_intent", intent_parser.__dict__))
|
2017-03-14 21:01:48 +00:00
|
|
|
self.registered_intents.append((name, intent_parser))
|
2018-03-01 02:04:22 +00:00
|
|
|
self.add_event(intent_parser.name, handler, 'mycroft.skill.handler')
|
2016-05-20 14:16:01 +00:00
|
|
|
|
2018-03-01 00:53:56 +00:00
|
|
|
def register_intent_file(self, intent_file, handler):
|
2017-05-31 19:53:21 +00:00
|
|
|
"""
|
|
|
|
Register an Intent file with the intent service.
|
2017-10-03 02:27:03 +00:00
|
|
|
For example:
|
|
|
|
|
|
|
|
=== food.order.intent ===
|
|
|
|
Order some {food}.
|
|
|
|
Order some {food} from {place}.
|
|
|
|
I'm hungry.
|
|
|
|
Grab some {food} from {place}.
|
|
|
|
|
|
|
|
Optionally, you can also use <register_entity_file>
|
|
|
|
to specify some examples of {food} and {place}
|
|
|
|
|
|
|
|
In addition, instead of writing out multiple variations
|
|
|
|
of the same sentence you can write:
|
|
|
|
|
|
|
|
=== food.order.intent ===
|
|
|
|
(Order | Grab) some {food} (from {place} | ).
|
|
|
|
I'm hungry.
|
2017-03-29 17:28:10 +00:00
|
|
|
|
2017-05-31 19:53:21 +00:00
|
|
|
Args:
|
|
|
|
intent_file: name of file that contains example queries
|
|
|
|
that should activate the intent
|
|
|
|
handler: function to register with intent
|
|
|
|
"""
|
2017-10-03 02:27:03 +00:00
|
|
|
name = str(self.skill_id) + ':' + intent_file
|
2018-07-14 03:00:21 +00:00
|
|
|
data = {
|
2017-05-31 19:53:21 +00:00
|
|
|
"file_name": join(self.vocab_dir, intent_file),
|
2017-10-03 02:27:03 +00:00
|
|
|
"name": name
|
2018-07-14 03:00:21 +00:00
|
|
|
}
|
|
|
|
self.emitter.emit(Message("padatious:register_intent", data))
|
|
|
|
self.registered_intents.append((intent_file, data))
|
2018-03-01 02:04:22 +00:00
|
|
|
self.add_event(name, handler, 'mycroft.skill.handler')
|
2017-10-03 02:27:03 +00:00
|
|
|
|
|
|
|
def register_entity_file(self, entity_file):
|
|
|
|
"""
|
|
|
|
Register an Entity file with the intent service.
|
|
|
|
And Entity file lists the exact values that an entity can hold.
|
|
|
|
For example:
|
|
|
|
|
|
|
|
=== ask.day.intent ===
|
|
|
|
Is it {weekday}?
|
|
|
|
|
|
|
|
=== weekday.entity ===
|
|
|
|
Monday
|
|
|
|
Tuesday
|
|
|
|
...
|
|
|
|
|
|
|
|
Args:
|
|
|
|
entity_file: name of file that contains examples
|
|
|
|
of an entity. Must end with .entity
|
|
|
|
"""
|
|
|
|
if '.entity' not in entity_file:
|
|
|
|
raise ValueError('Invalid entity filename: ' + entity_file)
|
|
|
|
name = str(self.skill_id) + ':' + entity_file.replace('.entity', '')
|
|
|
|
self.emitter.emit(Message("padatious:register_entity", {
|
|
|
|
"file_name": join(self.vocab_dir, entity_file),
|
|
|
|
"name": name
|
2017-05-31 19:53:21 +00:00
|
|
|
}))
|
2017-03-13 17:01:57 +00:00
|
|
|
|
2017-06-29 20:54:18 +00:00
|
|
|
def handle_enable_intent(self, message):
|
|
|
|
"""
|
|
|
|
Listener to enable a registered intent if it belongs to this skill
|
|
|
|
"""
|
|
|
|
intent_name = message.data["intent_name"]
|
|
|
|
for (name, intent) in self.registered_intents:
|
|
|
|
if name == intent_name:
|
|
|
|
return self.enable_intent(intent_name)
|
2017-03-13 17:01:57 +00:00
|
|
|
|
2017-06-29 20:54:18 +00:00
|
|
|
def handle_disable_intent(self, message):
|
|
|
|
"""
|
|
|
|
Listener to disable a registered intent if it belongs to this skill
|
|
|
|
"""
|
|
|
|
intent_name = message.data["intent_name"]
|
2017-03-14 21:01:48 +00:00
|
|
|
for (name, intent) in self.registered_intents:
|
2017-03-13 17:01:57 +00:00
|
|
|
if name == intent_name:
|
2017-06-29 20:54:18 +00:00
|
|
|
return self.disable_intent(intent_name)
|
|
|
|
|
|
|
|
def disable_intent(self, intent_name):
|
|
|
|
"""
|
|
|
|
Disable a registered intent if it belongs to this skill
|
|
|
|
|
|
|
|
Args:
|
|
|
|
intent_name: name of the intent to be disabled
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: True if disabled, False if it wasn't registered
|
|
|
|
"""
|
|
|
|
names = [intent_tuple[0] for intent_tuple in self.registered_intents]
|
|
|
|
if intent_name in names:
|
|
|
|
LOG.debug('Disabling intent ' + intent_name)
|
|
|
|
name = str(self.skill_id) + ':' + intent_name
|
|
|
|
self.emitter.emit(
|
|
|
|
Message("detach_intent", {"intent_name": name}))
|
|
|
|
return True
|
|
|
|
LOG.error('Could not disable ' + intent_name +
|
|
|
|
', it hasn\'t been registered.')
|
|
|
|
return False
|
|
|
|
|
|
|
|
def enable_intent(self, intent_name):
|
|
|
|
"""
|
|
|
|
(Re)Enable a registered intentif it belongs to this skill
|
|
|
|
|
|
|
|
Args:
|
|
|
|
intent_name: name of the intent to be enabled
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool: True if enabled, False if it wasn't registered
|
|
|
|
"""
|
|
|
|
names = [intent[0] for intent in self.registered_intents]
|
|
|
|
intents = [intent[1] for intent in self.registered_intents]
|
|
|
|
if intent_name in names:
|
|
|
|
intent = intents[names.index(intent_name)]
|
|
|
|
self.registered_intents.remove((intent_name, intent))
|
2018-07-14 03:00:21 +00:00
|
|
|
if ".intent" in intent_name:
|
2018-07-14 03:31:39 +00:00
|
|
|
self.register_intent_file(intent_name, None)
|
2018-07-14 03:00:21 +00:00
|
|
|
else:
|
2018-07-14 03:31:39 +00:00
|
|
|
intent.name = intent_name
|
2018-07-14 03:00:21 +00:00
|
|
|
self.register_intent(intent, None)
|
2017-06-29 20:54:18 +00:00
|
|
|
LOG.debug('Enabling intent ' + intent_name)
|
|
|
|
return True
|
|
|
|
LOG.error('Could not enable ' + intent_name + ', it hasn\'t been '
|
|
|
|
'registered.')
|
|
|
|
return False
|
2016-05-20 14:16:01 +00:00
|
|
|
|
2017-06-19 14:36:24 +00:00
|
|
|
def set_context(self, context, word=''):
|
2017-08-04 10:51:06 +00:00
|
|
|
"""
|
|
|
|
Add context to intent service
|
|
|
|
|
|
|
|
Args:
|
|
|
|
context: Keyword
|
|
|
|
word: word connected to keyword
|
|
|
|
"""
|
2018-02-08 19:03:46 +00:00
|
|
|
if not isinstance(context, str):
|
2017-08-04 10:51:06 +00:00
|
|
|
raise ValueError('context should be a string')
|
2018-02-08 19:03:46 +00:00
|
|
|
if not isinstance(word, str):
|
2017-08-04 10:51:06 +00:00
|
|
|
raise ValueError('word should be a string')
|
2018-05-10 23:01:07 +00:00
|
|
|
context = to_alnum(self.skill_id) + context
|
2017-08-17 17:09:17 +00:00
|
|
|
self.emitter.emit(Message('add_context',
|
|
|
|
{'context': context, 'word': word}))
|
2017-06-19 14:36:24 +00:00
|
|
|
|
|
|
|
def remove_context(self, context):
|
2017-08-04 10:51:06 +00:00
|
|
|
"""
|
|
|
|
remove_context removes a keyword from from the context manager.
|
|
|
|
"""
|
2018-02-08 19:03:46 +00:00
|
|
|
if not isinstance(context, str):
|
2017-08-04 10:51:06 +00:00
|
|
|
raise ValueError('context should be a string')
|
2017-06-19 14:36:24 +00:00
|
|
|
self.emitter.emit(Message('remove_context', {'context': context}))
|
|
|
|
|
2016-05-20 14:16:01 +00:00
|
|
|
def register_vocabulary(self, entity, entity_type):
|
2017-08-21 15:05:03 +00:00
|
|
|
""" Register a word to an keyword
|
|
|
|
|
|
|
|
Args:
|
|
|
|
entity: word to register
|
|
|
|
entity_type: Intent handler entity to tie the word to
|
|
|
|
"""
|
2016-09-04 01:24:18 +00:00
|
|
|
self.emitter.emit(Message('register_vocab', {
|
2018-05-10 23:01:07 +00:00
|
|
|
'start': entity, 'end': to_alnum(self.skill_id) + entity_type
|
2016-09-04 01:24:18 +00:00
|
|
|
}))
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
def register_regex(self, regex_str):
|
2018-02-23 06:51:55 +00:00
|
|
|
""" Register a new regex.
|
|
|
|
Args:
|
|
|
|
regex_str: Regex string
|
|
|
|
"""
|
|
|
|
regex = munge_regex(regex_str, self.skill_id)
|
|
|
|
re.compile(regex) # validate regex
|
|
|
|
self.emitter.emit(Message('register_vocab', {'regex': regex}))
|
2016-05-20 14:16:01 +00:00
|
|
|
|
2017-03-17 19:17:52 +00:00
|
|
|
def speak(self, utterance, expect_response=False):
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
|
|
|
Speak a sentence.
|
|
|
|
|
|
|
|
Args:
|
2017-12-07 07:41:38 +00:00
|
|
|
utterance (str): sentence mycroft should speak
|
|
|
|
expect_response (bool): set to True if Mycroft should listen
|
|
|
|
for a response immediately after
|
|
|
|
speaking the utterance.
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
2017-06-16 18:31:44 +00:00
|
|
|
# registers the skill as being active
|
|
|
|
self.enclosure.register(self.name)
|
2017-03-17 19:17:52 +00:00
|
|
|
data = {'utterance': utterance,
|
|
|
|
'expect_response': expect_response}
|
2017-12-21 13:12:12 +00:00
|
|
|
message = dig_for_message()
|
|
|
|
if message:
|
|
|
|
self.emitter.emit(message.reply("speak", data))
|
|
|
|
else:
|
|
|
|
self.emitter.emit(Message("speak", data))
|
2016-05-20 14:16:01 +00:00
|
|
|
|
2017-09-12 05:58:41 +00:00
|
|
|
def speak_dialog(self, key, data=None, expect_response=False):
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
2017-12-07 07:41:38 +00:00
|
|
|
Speak a random sentence from a dialog file.
|
2017-08-21 15:05:03 +00:00
|
|
|
|
|
|
|
Args
|
2017-12-07 07:41:38 +00:00
|
|
|
key (str): dialog file key (filename without extension)
|
|
|
|
data (dict): information used to populate sentence
|
|
|
|
expect_response (bool): set to True if Mycroft should listen
|
|
|
|
for a response immediately after
|
|
|
|
speaking the utterance.
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
2017-09-12 05:58:41 +00:00
|
|
|
data = data or {}
|
2017-08-25 12:26:33 +00:00
|
|
|
self.speak(self.dialog_renderer.render(key, data), expect_response)
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
def init_dialog(self, root_directory):
|
2017-02-04 20:00:22 +00:00
|
|
|
dialog_dir = join(root_directory, 'dialog', self.lang)
|
2017-08-22 06:45:06 +00:00
|
|
|
if exists(dialog_dir):
|
2017-02-04 20:00:22 +00:00
|
|
|
self.dialog_renderer = DialogLoader().load(dialog_dir)
|
|
|
|
else:
|
2017-09-18 18:55:58 +00:00
|
|
|
LOG.debug('No dialog loaded, ' + dialog_dir + ' does not exist')
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
def load_data_files(self, root_directory):
|
|
|
|
self.init_dialog(root_directory)
|
|
|
|
self.load_vocab_files(join(root_directory, 'vocab', self.lang))
|
2016-07-08 23:11:18 +00:00
|
|
|
regex_path = join(root_directory, 'regex', self.lang)
|
2017-11-16 01:09:48 +00:00
|
|
|
self.root_dir = root_directory
|
2017-08-22 06:45:06 +00:00
|
|
|
if exists(regex_path):
|
2016-07-08 23:11:18 +00:00
|
|
|
self.load_regex_files(regex_path)
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
def load_vocab_files(self, vocab_dir):
|
2017-05-31 19:53:21 +00:00
|
|
|
self.vocab_dir = vocab_dir
|
2017-08-22 06:45:06 +00:00
|
|
|
if exists(vocab_dir):
|
2017-12-12 19:49:10 +00:00
|
|
|
load_vocabulary(vocab_dir, self.emitter, self.skill_id)
|
2017-02-04 20:00:22 +00:00
|
|
|
else:
|
2017-09-18 18:55:58 +00:00
|
|
|
LOG.debug('No vocab loaded, ' + vocab_dir + ' does not exist')
|
2016-05-20 14:16:01 +00:00
|
|
|
|
2016-06-28 20:20:48 +00:00
|
|
|
def load_regex_files(self, regex_dir):
|
2017-12-12 19:49:10 +00:00
|
|
|
load_regex(regex_dir, self.emitter, self.skill_id)
|
2016-06-28 20:20:48 +00:00
|
|
|
|
2016-05-20 14:16:01 +00:00
|
|
|
def __handle_stop(self, event):
|
2017-08-03 12:14:31 +00:00
|
|
|
"""
|
|
|
|
Handler for the "mycroft.stop" signal. Runs the user defined
|
|
|
|
`stop()` method.
|
|
|
|
"""
|
2018-07-05 18:56:54 +00:00
|
|
|
|
|
|
|
def __stop_timeout():
|
|
|
|
# The self.stop() call took more than 100ms, assume it handled Stop
|
|
|
|
self.emitter.emit(
|
|
|
|
Message("mycroft.stop.handled",
|
|
|
|
{"skill_id": str(self.skill_id) + ":"}))
|
|
|
|
|
|
|
|
timer = Timer(0.1, __stop_timeout) # set timer for 100ms
|
2017-08-03 12:14:31 +00:00
|
|
|
try:
|
2018-07-05 18:56:54 +00:00
|
|
|
if self.stop():
|
|
|
|
self.emitter.emit(
|
|
|
|
Message("mycroft.stop.handled",
|
|
|
|
{"by": "skill:"+str(self.skill_id)}))
|
|
|
|
timer.cancel()
|
2017-08-03 12:14:31 +00:00
|
|
|
except:
|
2018-07-05 18:56:54 +00:00
|
|
|
timer.cancel()
|
2017-09-18 18:55:58 +00:00
|
|
|
LOG.error("Failed to stop skill: {}".format(self.name),
|
2017-09-18 19:14:21 +00:00
|
|
|
exc_info=True)
|
2016-05-20 14:16:01 +00:00
|
|
|
|
|
|
|
@abc.abstractmethod
|
|
|
|
def stop(self):
|
|
|
|
pass
|
|
|
|
|
2017-01-27 18:32:20 +00:00
|
|
|
def shutdown(self):
|
2017-01-28 00:36:19 +00:00
|
|
|
"""
|
2017-02-15 20:57:15 +00:00
|
|
|
This method is intended to be called during the skill
|
|
|
|
process termination. The skill implementation must
|
|
|
|
shutdown all processes and operations in execution.
|
2017-01-28 00:36:19 +00:00
|
|
|
"""
|
2018-04-12 02:10:45 +00:00
|
|
|
pass
|
|
|
|
|
2018-06-22 05:59:51 +00:00
|
|
|
def default_shutdown(self):
|
|
|
|
"""Parent function called internally to shut down everything.
|
|
|
|
|
|
|
|
Shuts down known entities and calls skill specific shutdown method.
|
|
|
|
"""
|
2018-04-12 09:11:04 +00:00
|
|
|
try:
|
|
|
|
self.shutdown()
|
2018-05-14 21:20:25 +00:00
|
|
|
except Exception as e:
|
2018-04-12 09:11:04 +00:00
|
|
|
LOG.error('Skill specific shutdown function encountered '
|
|
|
|
'an error: {}'.format(repr(e)))
|
2017-04-23 20:54:22 +00:00
|
|
|
# Store settings
|
2018-06-22 05:59:51 +00:00
|
|
|
if exists(self._dir):
|
|
|
|
self.settings.store()
|
|
|
|
self.settings.stop_polling()
|
2017-04-17 17:25:27 +00:00
|
|
|
# removing events
|
2018-03-15 10:42:08 +00:00
|
|
|
self.cancel_all_repeating_events()
|
2017-04-17 17:25:27 +00:00
|
|
|
for e, f in self.events:
|
|
|
|
self.emitter.remove(e, f)
|
2018-03-06 15:52:55 +00:00
|
|
|
self.events = [] # Remove reference to wrappers
|
2017-04-17 17:25:27 +00:00
|
|
|
|
|
|
|
self.emitter.emit(
|
2017-08-18 02:38:00 +00:00
|
|
|
Message("detach_skill", {"skill_id": str(self.skill_id) + ":"}))
|
2017-08-03 12:14:31 +00:00
|
|
|
try:
|
|
|
|
self.stop()
|
|
|
|
except:
|
2017-09-18 18:55:58 +00:00
|
|
|
LOG.error("Failed to stop skill: {}".format(self.name),
|
2017-09-18 19:14:21 +00:00
|
|
|
exc_info=True)
|
2017-07-14 15:08:34 +00:00
|
|
|
|
2017-09-24 10:25:19 +00:00
|
|
|
def _unique_name(self, name):
|
|
|
|
"""
|
|
|
|
Return a name unique to this skill using the format
|
|
|
|
[skill_id]:[name].
|
|
|
|
|
|
|
|
Args:
|
|
|
|
name: Name to use internally
|
|
|
|
|
2017-11-09 10:34:00 +00:00
|
|
|
Returns:
|
|
|
|
str: name unique to this skill
|
2017-09-24 10:25:19 +00:00
|
|
|
"""
|
2018-04-03 14:50:53 +00:00
|
|
|
return str(self.skill_id) + ':' + (name or '')
|
2017-09-24 10:25:19 +00:00
|
|
|
|
2017-09-12 05:58:41 +00:00
|
|
|
def _schedule_event(self, handler, when, data=None, name=None,
|
2017-08-30 17:19:06 +00:00
|
|
|
repeat=None):
|
|
|
|
"""
|
2018-02-13 08:54:12 +00:00
|
|
|
Underlying method for schedule_event and schedule_repeating_event.
|
2017-09-01 20:41:06 +00:00
|
|
|
Takes scheduling information and sends it of on the message bus.
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
|
|
|
if not name:
|
|
|
|
name = self.name + handler.__name__
|
2017-09-24 10:25:19 +00:00
|
|
|
name = self._unique_name(name)
|
2018-04-06 09:34:36 +00:00
|
|
|
if repeat:
|
|
|
|
self.scheduled_repeats.append(name)
|
2017-09-24 10:25:19 +00:00
|
|
|
|
2018-01-16 11:14:07 +00:00
|
|
|
data = data or {}
|
|
|
|
self.add_event(name, handler, once=not repeat)
|
2017-08-30 17:19:06 +00:00
|
|
|
event_data = {}
|
2017-09-01 20:41:06 +00:00
|
|
|
event_data['time'] = time.mktime(when.timetuple())
|
2017-08-30 17:19:06 +00:00
|
|
|
event_data['event'] = name
|
|
|
|
event_data['repeat'] = repeat
|
|
|
|
event_data['data'] = data
|
|
|
|
self.emitter.emit(Message('mycroft.scheduler.schedule_event',
|
|
|
|
data=event_data))
|
|
|
|
|
2017-09-12 05:58:41 +00:00
|
|
|
def schedule_event(self, handler, when, data=None, name=None):
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
2017-09-01 20:41:06 +00:00
|
|
|
Schedule a single event.
|
2017-08-30 17:19:06 +00:00
|
|
|
|
|
|
|
Args:
|
2017-09-01 20:41:06 +00:00
|
|
|
handler: method to be called
|
|
|
|
when (datetime): when the handler should be called
|
Fix named event scheduling/deleting (#1705)
While working on the Alarm skill I discovered several issues with the
event scheduler. This PR cleans up those findings and resolves several
other potential issues:
1) To avoid thread synchronization issues, the EventScheduler had several
queues which independently held objects to be added/deleted/updated. However, the order of the events was undefined and got mixed since they were all batched together. So, for instance, if skill code performed:
self.add_event("foo", self.handle_foo)
if SomeReason:
self.cancel_event("foo")
The actual order of queue handling would perform Remove first, then Add which resulted in "foo" not being found for delete, but then added and left as an active event.
Now the EventScheduler protects the list using a Lock and the queues have been removed. Modifications to the list happen immediately after obtaining the lock and are not batched up.
2) One-time events were triggered while the event was still in the EventScheduler list. Now the entry is removed before invoking the handler.
3) Within the MycroftSkill.add_event(name, handler) is a local 'wrapper' method that actually makes the callback. The MycroftSkill.remove_event(name) method attempted to find entries in the events list and the associated handler entries in the self.emitter to remove. However, the emitter actually held the wrapper(handler), not the handler itself. So the emitter handlers were left behind.
This was a quiet bug until the next time you scheduled an event of the same name. When that second event finally triggered, it would fire off both the new and the old handler -- which snowballed in the 'skill-alarm:Beep' case, doubling and redoubling with every beep.
Now this cancels all the emitter listeners by name. There is a very slim chance that someone has registered a listener with the same name, but since it is namespaced to "skill-name:Event" I think this is pretty safe.
Not technically related, but a failure that has been lurking for
some time and is a French unit test that doesn't work depending
on the time of day when the test is run.
2018-07-30 20:08:13 +00:00
|
|
|
(local time)
|
2017-09-01 20:41:06 +00:00
|
|
|
data (dict, optional): data to send when the handler is called
|
|
|
|
name (str, optional): friendly name parameter
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
2017-09-12 05:58:41 +00:00
|
|
|
data = data or {}
|
2017-09-01 20:41:06 +00:00
|
|
|
self._schedule_event(handler, when, data, name)
|
2017-08-30 17:19:06 +00:00
|
|
|
|
2017-09-01 20:41:06 +00:00
|
|
|
def schedule_repeating_event(self, handler, when, frequency,
|
2017-09-12 05:58:41 +00:00
|
|
|
data=None, name=None):
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
2017-09-01 20:41:06 +00:00
|
|
|
Schedule a repeating event.
|
2017-08-30 17:19:06 +00:00
|
|
|
|
|
|
|
Args:
|
2017-09-01 20:41:06 +00:00
|
|
|
handler: method to be called
|
2018-02-15 11:40:38 +00:00
|
|
|
when (datetime): time for calling the handler or None
|
|
|
|
to initially trigger <frequency>
|
|
|
|
seconds from now
|
2017-09-01 20:41:06 +00:00
|
|
|
frequency (float/int): time in seconds between calls
|
|
|
|
data (dict, optional): data to send along to the handler
|
|
|
|
name (str, optional): friendly name parameter
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
2018-03-15 10:42:08 +00:00
|
|
|
# Do not schedule if this event is already scheduled by the skill
|
|
|
|
if name not in self.scheduled_repeats:
|
|
|
|
data = data or {}
|
|
|
|
if not when:
|
|
|
|
when = datetime.now() + timedelta(seconds=frequency)
|
|
|
|
self._schedule_event(handler, when, data, name, frequency)
|
|
|
|
else:
|
|
|
|
LOG.debug('The event is already scheduled, cancel previous '
|
|
|
|
'event if this scheduling should replace the last.')
|
2017-08-30 17:19:06 +00:00
|
|
|
|
2017-11-02 17:34:05 +00:00
|
|
|
def update_scheduled_event(self, name, data=None):
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
2017-09-01 20:41:06 +00:00
|
|
|
Change data of event.
|
2017-08-30 17:19:06 +00:00
|
|
|
|
|
|
|
Args:
|
2017-09-01 20:41:06 +00:00
|
|
|
name (str): Name of event
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
2017-09-12 05:58:41 +00:00
|
|
|
data = data or {}
|
2017-08-30 17:19:06 +00:00
|
|
|
data = {
|
2017-09-24 10:25:19 +00:00
|
|
|
'event': self._unique_name(name),
|
2017-08-30 17:19:06 +00:00
|
|
|
'data': data
|
|
|
|
}
|
2017-09-24 10:25:19 +00:00
|
|
|
self.emitter.emit(Message('mycroft.schedule.update_event', data=data))
|
2017-08-30 17:19:06 +00:00
|
|
|
|
2017-11-02 19:57:13 +00:00
|
|
|
def cancel_scheduled_event(self, name):
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
|
|
|
Cancel a pending event. The event will no longer be scheduled
|
|
|
|
to be executed
|
2017-09-01 20:41:06 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
name (str): Name of event
|
2017-08-30 17:19:06 +00:00
|
|
|
"""
|
2017-10-31 17:54:24 +00:00
|
|
|
unique_name = self._unique_name(name)
|
|
|
|
data = {'event': unique_name}
|
2018-03-15 10:42:08 +00:00
|
|
|
if name in self.scheduled_repeats:
|
|
|
|
self.scheduled_repeats.remove(name)
|
2018-02-13 08:54:12 +00:00
|
|
|
if self.remove_event(unique_name):
|
|
|
|
self.emitter.emit(Message('mycroft.scheduler.remove_event',
|
|
|
|
data=data))
|
2017-08-30 17:19:06 +00:00
|
|
|
|
2017-11-02 17:34:05 +00:00
|
|
|
def get_scheduled_event_status(self, name):
|
2017-11-01 00:27:58 +00:00
|
|
|
"""
|
2017-11-02 17:34:05 +00:00
|
|
|
Get scheduled event data and return the amount of time left
|
2017-11-01 00:27:58 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
name (str): Name of event
|
|
|
|
|
|
|
|
Return:
|
2017-11-09 10:34:00 +00:00
|
|
|
int: the time left in seconds
|
2017-11-01 00:27:58 +00:00
|
|
|
"""
|
|
|
|
event_name = self._unique_name(name)
|
|
|
|
data = {'name': event_name}
|
|
|
|
|
2017-11-01 17:37:07 +00:00
|
|
|
# making event_status an object so it's refrence can be changed
|
|
|
|
event_status = [None]
|
2017-11-02 19:57:13 +00:00
|
|
|
finished_callback = [False]
|
2017-11-01 00:27:58 +00:00
|
|
|
|
2017-11-02 19:57:13 +00:00
|
|
|
def callback(message):
|
|
|
|
if message.data is not None:
|
2017-11-02 17:34:05 +00:00
|
|
|
event_time = int(message.data[0][0])
|
|
|
|
current_time = int(time.time())
|
|
|
|
time_left_in_seconds = event_time - current_time
|
|
|
|
event_status[0] = time_left_in_seconds
|
2017-11-02 19:57:13 +00:00
|
|
|
finished_callback[0] = True
|
2017-11-01 00:27:58 +00:00
|
|
|
|
|
|
|
emitter_name = 'mycroft.event_status.callback.{}'.format(event_name)
|
2017-11-02 19:57:13 +00:00
|
|
|
self.emitter.once(emitter_name, callback)
|
2017-11-01 00:27:58 +00:00
|
|
|
self.emitter.emit(Message('mycroft.scheduler.get_event', data=data))
|
|
|
|
|
2017-11-01 17:37:07 +00:00
|
|
|
start_wait = time.time()
|
2017-11-02 19:57:13 +00:00
|
|
|
while finished_callback[0] is False and time.time() - start_wait < 3.0:
|
2017-11-01 17:37:07 +00:00
|
|
|
time.sleep(0.1)
|
|
|
|
if time.time() - start_wait > 3.0:
|
|
|
|
raise Exception("Event Status Messagebus Timeout")
|
|
|
|
return event_status[0]
|
2017-11-01 00:27:58 +00:00
|
|
|
|
2018-03-15 10:42:08 +00:00
|
|
|
def cancel_all_repeating_events(self):
|
|
|
|
""" Cancel any repeating events started by the skill. """
|
|
|
|
for e in self.scheduled_repeats:
|
|
|
|
self.cancel_scheduled_event(e)
|
|
|
|
|
2017-07-14 15:08:34 +00:00
|
|
|
|
2017-11-09 10:34:00 +00:00
|
|
|
#######################################################################
|
|
|
|
# FallbackSkill base class
|
|
|
|
#######################################################################
|
2017-07-14 15:08:34 +00:00
|
|
|
class FallbackSkill(MycroftSkill):
|
2017-08-21 15:05:03 +00:00
|
|
|
"""
|
|
|
|
FallbackSkill is used to declare a fallback to be called when
|
|
|
|
no skill is matching an intent. The fallbackSkill implements a
|
|
|
|
number of fallback handlers to be called in an order determined
|
|
|
|
by their priority.
|
|
|
|
"""
|
2017-07-14 15:08:34 +00:00
|
|
|
fallback_handlers = {}
|
|
|
|
|
2017-08-09 12:18:14 +00:00
|
|
|
def __init__(self, name=None, emitter=None):
|
2017-07-14 15:08:34 +00:00
|
|
|
MycroftSkill.__init__(self, name, emitter)
|
|
|
|
|
2017-08-09 12:24:21 +00:00
|
|
|
# list of fallback handlers registered by this instance
|
|
|
|
self.instance_fallback_handlers = []
|
|
|
|
|
2017-07-14 15:12:41 +00:00
|
|
|
@classmethod
|
|
|
|
def make_intent_failure_handler(cls, ws):
|
2017-08-21 15:05:03 +00:00
|
|
|
"""Goes through all fallback handlers until one returns True"""
|
2017-07-14 15:08:34 +00:00
|
|
|
|
|
|
|
def handler(message):
|
2017-09-28 15:53:57 +00:00
|
|
|
# indicate fallback handling start
|
2018-04-27 14:12:23 +00:00
|
|
|
ws.emit(message.reply("mycroft.skill.handler.start",
|
|
|
|
data={'handler': "fallback"}))
|
2017-07-14 15:08:34 +00:00
|
|
|
|
2017-12-21 00:05:14 +00:00
|
|
|
stopwatch = Stopwatch()
|
|
|
|
handler_name = None
|
|
|
|
with stopwatch:
|
|
|
|
for _, handler in sorted(cls.fallback_handlers.items(),
|
|
|
|
key=operator.itemgetter(0)):
|
|
|
|
try:
|
|
|
|
if handler(message):
|
|
|
|
# indicate completion
|
|
|
|
handler_name = get_handler_name(handler)
|
2018-04-27 14:12:23 +00:00
|
|
|
ws.emit(message.reply(
|
2017-12-21 00:05:14 +00:00
|
|
|
'mycroft.skill.handler.complete',
|
|
|
|
data={'handler': "fallback",
|
|
|
|
"fallback_handler": handler_name}))
|
|
|
|
break
|
|
|
|
except Exception:
|
|
|
|
LOG.exception('Exception in fallback.')
|
|
|
|
else: # No fallback could handle the utterance
|
2018-04-27 14:12:23 +00:00
|
|
|
ws.emit(message.reply('complete_intent_failure'))
|
2017-12-21 00:05:14 +00:00
|
|
|
warning = "No fallback could handle intent."
|
|
|
|
LOG.warning(warning)
|
|
|
|
# indicate completion with exception
|
2018-04-27 14:12:23 +00:00
|
|
|
ws.emit(message.reply('mycroft.skill.handler.complete',
|
|
|
|
data={'handler': "fallback",
|
|
|
|
'exception': warning}))
|
2017-12-21 00:05:14 +00:00
|
|
|
|
|
|
|
# Send timing metric
|
|
|
|
if message.context and message.context['ident']:
|
|
|
|
ident = message.context['ident']
|
2017-12-27 11:45:31 +00:00
|
|
|
report_timing(ident, 'fallback_handler', stopwatch,
|
|
|
|
{'handler': handler_name})
|
2018-03-01 00:53:56 +00:00
|
|
|
|
2017-07-14 15:08:34 +00:00
|
|
|
return handler
|
|
|
|
|
2017-07-14 15:12:41 +00:00
|
|
|
@classmethod
|
2017-08-09 12:24:21 +00:00
|
|
|
def _register_fallback(cls, handler, priority):
|
2017-07-14 15:08:34 +00:00
|
|
|
"""
|
|
|
|
Register a function to be called as a general info fallback
|
|
|
|
Fallback should receive message and return
|
|
|
|
a boolean (True if succeeded or False if failed)
|
|
|
|
|
|
|
|
Lower priority gets run first
|
|
|
|
0 for high priority 100 for low priority
|
|
|
|
"""
|
2017-07-14 15:12:41 +00:00
|
|
|
while priority in cls.fallback_handlers:
|
2017-07-14 15:08:34 +00:00
|
|
|
priority += 1
|
|
|
|
|
2017-07-14 15:12:41 +00:00
|
|
|
cls.fallback_handlers[priority] = handler
|
2017-07-14 15:08:34 +00:00
|
|
|
|
2017-08-09 12:24:21 +00:00
|
|
|
def register_fallback(self, handler, priority):
|
|
|
|
"""
|
|
|
|
register a fallback with the list of fallback handlers
|
|
|
|
and with the list of handlers registered by this instance
|
|
|
|
"""
|
2018-03-01 00:53:56 +00:00
|
|
|
|
2017-12-04 23:53:49 +00:00
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
if handler(*args, **kwargs):
|
|
|
|
self.make_active()
|
|
|
|
return True
|
|
|
|
return False
|
2018-03-01 00:53:56 +00:00
|
|
|
|
2017-12-04 23:53:49 +00:00
|
|
|
self.instance_fallback_handlers.append(wrapper)
|
2017-08-09 12:24:21 +00:00
|
|
|
self._register_fallback(handler, priority)
|
|
|
|
|
2017-07-14 15:12:41 +00:00
|
|
|
@classmethod
|
|
|
|
def remove_fallback(cls, handler_to_del):
|
2017-08-09 12:24:21 +00:00
|
|
|
"""
|
|
|
|
Remove a fallback handler
|
|
|
|
|
|
|
|
Args:
|
|
|
|
handler_to_del: reference to handler
|
|
|
|
"""
|
2017-07-14 15:12:41 +00:00
|
|
|
for priority, handler in cls.fallback_handlers.items():
|
2017-07-14 15:08:34 +00:00
|
|
|
if handler == handler_to_del:
|
2017-07-14 15:12:41 +00:00
|
|
|
del cls.fallback_handlers[priority]
|
2017-07-14 15:08:34 +00:00
|
|
|
return
|
2017-09-18 18:55:58 +00:00
|
|
|
LOG.warning('Could not remove fallback!')
|
2017-08-09 12:24:21 +00:00
|
|
|
|
|
|
|
def remove_instance_handlers(self):
|
|
|
|
"""
|
|
|
|
Remove all fallback handlers registered by the fallback skill.
|
|
|
|
"""
|
|
|
|
while len(self.instance_fallback_handlers):
|
|
|
|
handler = self.instance_fallback_handlers.pop()
|
|
|
|
self.remove_fallback(handler)
|
|
|
|
|
2018-06-22 05:59:51 +00:00
|
|
|
def default_shutdown(self):
|
2017-08-09 12:24:21 +00:00
|
|
|
"""
|
|
|
|
Remove all registered handlers and perform skill shutdown.
|
|
|
|
"""
|
|
|
|
self.remove_instance_handlers()
|
2018-06-22 05:59:51 +00:00
|
|
|
super(FallbackSkill, self).default_shutdown()
|