code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
import random class Zombiedice: def __init__(self, player_int): ''' To initiate player, include player int STEP 1: Once initialised, players are required to pick 3 dice from the bucket by running pick_dice() STEP 2: After they've picked the dice with specific colours, players are required to roll the dice by running roll_dice() STEP 3: Player can pick more dice and re-roll if they choose to - remember footprints are included in the re-pick and re-throw, so keep in mind of the colours STEP 4: Player can keep pick and roll untill the 13 dice are exhausted and the round finished or player can end the round when they feel like they've amounted enough points. Run end_round() to end the round and the next player can continue The first player to reach a total of 13 points wins the game ''' self.player_int = player_int self.pick_results = [] self.footprints = [] self.total_score = [] self.round_score = 0 def pick_dice(self, show_print=True): ''' Run to pick three dice from the bucket of 13 dice A complete bucket consists of the following colours: - 6 green dice - 4 yellow dice - 3 red dice INPUT: optional show_print boolean to include helper text output OUTPUT: three dice colours picked at random ''' picked_results_show = [] footprint_results_show = [] # define the remaining_dice in bucket to pick from (excluding the ones you've already picked) remaining_dice = range(1, 14) remaining_dice = [x for x in remaining_dice if x not in self.pick_results] try: # pick three dice minus the number of footprints dice for dice_pick in range(0, (3 - len(self.footprints))): dice_pick = random.choice(remaining_dice) if dice_pick in [1, 2, 3, 4, 5, 6]: result = dice_pick result_show = 'Green' elif dice_pick in [7, 8, 9, 10]: result = dice_pick result_show = 'Yellow' elif dice_pick in [11, 12, 13]: result = dice_pick result_show = 'Red' self.pick_results.append(result) picked_results_show.append(result_show) except IndexError: print('There are no more dice left in the bucket') picked_results_show = [] # include footprints dice with pick_results for die in self.footprints: self.pick_results.append(die) # if there are footprints dice then append colour and include in picked_results_show if len(self.footprints) > 0: for footprint_die in self.footprints: if footprint_die in [1, 2, 3, 4, 5, 6]: footprint_result_show = 'Green' elif footprint_die in [7, 8, 9, 10]: footprint_result_show = 'Yellow' elif footprint_die in [11, 12, 13]: footprint_result_show = 'Red' footprint_results_show.append(footprint_result_show) # include footprints dice with picked_results_show picked_results_show = picked_results_show + footprint_results_show else: pass if show_print is True: print("You have the following dice to roll:") print('') for die in picked_results_show[-3:]: print(die) print('') if len(self.footprints) > 0: print("The footprints dice from the previous roll is:") for die in footprint_results_show: print(die) else: pass else: pass def roll_dice(self, show_print=True): ''' Run to roll the three dice picked up with pick_dice() Die icons include: - Brains - Shotgun - Footprints INPUT: optional show_print boolean to include helper text output OUTPUT: The colour and 'icon' of each rolled die ''' roll_results_dict = {} die_number = 0 footprints = [] # roll last three dice of picked dice for die in self.pick_results[-3:]: die_number += 1 if die in [1, 2, 3, 4, 5, 6]: die_roll = random.randint(1, 6) roll_result_colour = 'Green' if die_roll in [1, 2, 3]: roll_result = 'Brain' self.round_score += 1 elif die_roll in [4, 5]: roll_result = 'Footprints' footprints.append(die) elif die_roll in [6]: roll_result = 'Shotgun' self.round_score -= 1 roll_results_dict.update({'Die ' + str(die_number) + ': Green' : roll_result}) elif die in [7, 8, 9, 10]: die_roll = random.randint(1, 6) roll_result_colour = 'Yellow' if die_roll in [1, 2]: roll_result = 'Brain' self.round_score += 1 elif die_roll in [3, 4]: roll_result = 'Footprints' footprints.append(die) elif die_roll in [5, 6]: roll_result = 'Shotgun' self.round_score -= 1 roll_results_dict.update({'Die ' + str(die_number) + ': Yellow' : roll_result}) elif die in [11, 12, 13]: die_roll = random.randint(1, 6) roll_result_colour = 'Red' if die_roll in [1]: roll_result = 'Brain' self.round_score += 1 elif die_roll in [2, 3]: roll_result = 'Footprints' footprints.append(die) elif die_roll in [4, 5, 6]: roll_result = 'Shotgun' self.round_score -= 1 roll_results_dict.update({'Die ' + str(die_number) + ': Red' : roll_result}) # only remaining footprints after roll_dice should be included in next pick_dice self.footprints = footprints for key, value in roll_results_dict.items(): print(key, value) if show_print is True: print('') print("You're score this round so far is " + str(self.round_score) + "!") if len(self.footprints) > 0: print("You've rolled " + str(len(self.footprints)) + " footprint(s).") print("Do you wanna pick more dice to re-roll?") print('') print("Remember, you can only pick three dice including one of the footprints.") else: pass else: pass def end_round(self): ''' Run end_round() to end the round and the next player can continue INPUT: None OUTPUT: player's total score - a sum of all rounds played so far ''' # tally round score self.total_score.append(self.round_score) # reset all round variables self.pick_results = [] self.footprints = [] self.round_score = 0 print("You're total score currently is: " + str(sum(self.total_score)))
zombie-dice
/zombie_dice-0.6.tar.gz/zombie_dice-0.6/zombie_dice/zombie_dice.py
zombie_dice.py
# zombie-imp ~~A particularly mischevious act of necromancy. That is,~~ A copy of the `imp` module that was removed in Python 3.12. Don't use this, it'll probably trick and bite you. # Usage Can be summoned by `import zombie_imp`. On Python versions where `imp` was banished, reanimate it using `import imp`. It promises (with a sneer) to be the same as before. Some functionality that was severed from `pkgutil` is interred in `zombie_imp.pkgutil`, ready for reattachment: - `ImpImporter` - `ImpLoader` # Development You want to help it? Think you'll be rewarded? Great! It loves gullible brains. Seriously, **run!** Find a project that needs this and port *that* to `importlib`. ## License The code was snatched from CPython, and is available under CPython's license (SPDX: `Python-2.0.1`).
zombie-imp
/zombie-imp-0.0.2.tar.gz/zombie-imp-0.0.2/README.md
README.md
from pkgutil import * import warnings import importlib def _import_imp(): global imp with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) imp = importlib.import_module('imp') class ImpImporter: """PEP 302 Finder that wraps Python's "classic" import algorithm ImpImporter(dirname) produces a PEP 302 finder that searches that directory. ImpImporter(None) produces a PEP 302 finder that searches the current sys.path, plus any modules that are frozen or built-in. Note that ImpImporter does not currently support being used by placement on sys.meta_path. """ def __init__(self, path=None): global imp warnings.warn("This emulation is deprecated and slated for removal " "in Python 3.12; use 'importlib' instead", DeprecationWarning) _import_imp() self.path = path def find_module(self, fullname, path=None): # Note: we ignore 'path' argument since it is only used via meta_path subname = fullname.split(".")[-1] if subname != fullname and self.path is None: return None if self.path is None: path = None else: path = [os.path.realpath(self.path)] try: file, filename, etc = imp.find_module(subname, path) except ImportError: return None return ImpLoader(fullname, file, filename, etc) def iter_modules(self, prefix=''): if self.path is None or not os.path.isdir(self.path): return yielded = {} import inspect try: filenames = os.listdir(self.path) except OSError: # ignore unreadable directories like import does filenames = [] filenames.sort() # handle packages before same-named modules for fn in filenames: modname = inspect.getmodulename(fn) if modname=='__init__' or modname in yielded: continue path = os.path.join(self.path, fn) ispkg = False if not modname and os.path.isdir(path) and '.' not in fn: modname = fn try: dircontents = os.listdir(path) except OSError: # ignore unreadable directories like import does dircontents = [] for fn in dircontents: subname = inspect.getmodulename(fn) if subname=='__init__': ispkg = True break else: continue # not a package if modname and '.' not in modname: yielded[modname] = 1 yield prefix + modname, ispkg class ImpLoader: """PEP 302 Loader that wraps Python's "classic" import algorithm """ code = source = None def __init__(self, fullname, file, filename, etc): warnings.warn("This emulation is deprecated and slated for removal in " "Python 3.12; use 'importlib' instead", DeprecationWarning) _import_imp() self.file = file self.filename = filename self.fullname = fullname self.etc = etc def load_module(self, fullname): self._reopen() try: mod = imp.load_module(fullname, self.file, self.filename, self.etc) finally: if self.file: self.file.close() # Note: we don't set __loader__ because we want the module to look # normal; i.e. this is just a wrapper for standard import machinery return mod def get_data(self, pathname): with open(pathname, "rb") as file: return file.read() def _reopen(self): if self.file and self.file.closed: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: self.file = open(self.filename, 'r') elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION): self.file = open(self.filename, 'rb') def _fix_name(self, fullname): if fullname is None: fullname = self.fullname elif fullname != self.fullname: raise ImportError("Loader for module %s cannot handle " "module %s" % (self.fullname, fullname)) return fullname def is_package(self, fullname): fullname = self._fix_name(fullname) return self.etc[2]==imp.PKG_DIRECTORY def get_code(self, fullname=None): fullname = self._fix_name(fullname) if self.code is None: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: source = self.get_source(fullname) self.code = compile(source, self.filename, 'exec') elif mod_type==imp.PY_COMPILED: self._reopen() try: self.code = read_code(self.file) finally: self.file.close() elif mod_type==imp.PKG_DIRECTORY: self.code = self._get_delegate().get_code() return self.code def get_source(self, fullname=None): fullname = self._fix_name(fullname) if self.source is None: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: self._reopen() try: self.source = self.file.read() finally: self.file.close() elif mod_type==imp.PY_COMPILED: if os.path.exists(self.filename[:-1]): with open(self.filename[:-1], 'r') as f: self.source = f.read() elif mod_type==imp.PKG_DIRECTORY: self.source = self._get_delegate().get_source() return self.source def _get_delegate(self): finder = ImpImporter(self.filename) spec = _get_spec(finder, '__init__') return spec.loader def get_filename(self, fullname=None): fullname = self._fix_name(fullname) mod_type = self.etc[2] if mod_type==imp.PKG_DIRECTORY: return self._get_delegate().get_filename() elif mod_type in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION): return self.filename return None
zombie-imp
/zombie-imp-0.0.2.tar.gz/zombie-imp-0.0.2/zombie_imp/pkgutil.py
pkgutil.py
from _imp import (lock_held, acquire_lock, release_lock, get_frozen_object, is_frozen_package, init_frozen, is_builtin, is_frozen, _fix_co_filename) try: from _imp import _frozen_module_names except ImportError: pass try: from _imp import create_dynamic except ImportError: # Platform doesn't support dynamic loading. create_dynamic = None from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name from importlib._bootstrap_external import SourcelessFileLoader from importlib import machinery from importlib import util import importlib import os import sys import tokenize import types import warnings warnings.warn("the imp module was removed in favour of importlib. " "Someone brought it back, but it's not a good idea to use it.", DeprecationWarning, stacklevel=2) # DEPRECATED SEARCH_ERROR = 0 PY_SOURCE = 1 PY_COMPILED = 2 C_EXTENSION = 3 PY_RESOURCE = 4 PKG_DIRECTORY = 5 C_BUILTIN = 6 PY_FROZEN = 7 PY_CODERESOURCE = 8 IMP_HOOK = 9 def new_module(name): """**DEPRECATED** Create a new module. The module is not entered into sys.modules. """ return types.ModuleType(name) def get_magic(): """**DEPRECATED** Return the magic number for .pyc files. """ return util.MAGIC_NUMBER def get_tag(): """Return the magic tag for .pyc files.""" return sys.implementation.cache_tag def cache_from_source(path, debug_override=None): """**DEPRECATED** Given the path to a .py file, return the path to its .pyc file. The .py file does not need to exist; this simply returns the path to the .pyc file calculated as if the .py file were imported. If debug_override is not None, then it must be a boolean and is used in place of sys.flags.optimize. If sys.implementation.cache_tag is None then NotImplementedError is raised. """ with warnings.catch_warnings(): warnings.simplefilter('ignore') return util.cache_from_source(path, debug_override) def source_from_cache(path): """**DEPRECATED** Given the path to a .pyc. file, return the path to its .py file. The .pyc file does not need to exist; this simply returns the path to the .py file calculated to correspond to the .pyc file. If path does not conform to PEP 3147 format, ValueError will be raised. If sys.implementation.cache_tag is None then NotImplementedError is raised. """ return util.source_from_cache(path) def get_suffixes(): """**DEPRECATED**""" extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES] source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] return extensions + source + bytecode class NullImporter: """**DEPRECATED** Null import object. """ def __init__(self, path): if path == '': raise ImportError('empty pathname', path='') elif os.path.isdir(path): raise ImportError('existing directory', path=path) def find_module(self, fullname): """Always returns None.""" return None class _HackedGetData: """Compatibility support for 'file' arguments of various load_*() functions.""" def __init__(self, fullname, path, file=None): super().__init__(fullname, path) self.file = file def get_data(self, path): """Gross hack to contort loader to deal w/ load_*()'s bad API.""" if self.file and path == self.path: # The contract of get_data() requires us to return bytes. Reopen the # file in binary mode if needed. if not self.file.closed: file = self.file if 'b' not in file.mode: file.close() if self.file.closed: self.file = file = open(self.path, 'rb') with file: return file.read() else: return super().get_data(path) class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): """Compatibility support for implementing load_source().""" def load_source(name, pathname, file=None): loader = _LoadSourceCompatibility(name, pathname, file) spec = util.spec_from_file_location(name, pathname, loader=loader) if name in sys.modules: module = _exec(spec, sys.modules[name]) else: module = _load(spec) # To allow reloading to potentially work, use a non-hacked loader which # won't rely on a now-closed file object. module.__loader__ = machinery.SourceFileLoader(name, pathname) module.__spec__.loader = module.__loader__ return module class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader): """Compatibility support for implementing load_compiled().""" def load_compiled(name, pathname, file=None): """**DEPRECATED**""" loader = _LoadCompiledCompatibility(name, pathname, file) spec = util.spec_from_file_location(name, pathname, loader=loader) if name in sys.modules: module = _exec(spec, sys.modules[name]) else: module = _load(spec) # To allow reloading to potentially work, use a non-hacked loader which # won't rely on a now-closed file object. module.__loader__ = SourcelessFileLoader(name, pathname) module.__spec__.loader = module.__loader__ return module def load_package(name, path): """**DEPRECATED**""" if os.path.isdir(path): extensions = (machinery.SOURCE_SUFFIXES[:] + machinery.BYTECODE_SUFFIXES[:]) for extension in extensions: init_path = os.path.join(path, '__init__' + extension) if os.path.exists(init_path): path = init_path break else: raise ValueError('{!r} is not a package'.format(path)) spec = util.spec_from_file_location(name, path, submodule_search_locations=[]) if name in sys.modules: return _exec(spec, sys.modules[name]) else: return _load(spec) def load_module(name, file, filename, details): """**DEPRECATED** Load a module, given information returned by find_module(). The module name must include the full package name, if any. """ suffix, mode, type_ = details if mode and (not mode.startswith('r') or '+' in mode): raise ValueError('invalid file open mode {!r}'.format(mode)) elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: msg = 'file object required for import (type code {})'.format(type_) raise ValueError(msg) elif type_ == PY_SOURCE: return load_source(name, filename, file) elif type_ == PY_COMPILED: return load_compiled(name, filename, file) elif type_ == C_EXTENSION and load_dynamic is not None: if file is None: with open(filename, 'rb') as opened_file: return load_dynamic(name, filename, opened_file) else: return load_dynamic(name, filename, file) elif type_ == PKG_DIRECTORY: return load_package(name, filename) elif type_ == C_BUILTIN: return init_builtin(name) elif type_ == PY_FROZEN: return init_frozen(name) else: msg = "Don't know how to import {} (type code {})".format(name, type_) raise ImportError(msg, name=name) def find_module(name, path=None): """**DEPRECATED** Search for a module. If path is omitted or None, search for a built-in, frozen or special module and continue search in sys.path. The module name cannot contain '.'; to search for a submodule of a package, pass the submodule name and the package's __path__. """ if not isinstance(name, str): raise TypeError("'name' must be a str, not {}".format(type(name))) elif not isinstance(path, (type(None), list)): # Backwards-compatibility raise RuntimeError("'path' must be None or a list, " "not {}".format(type(path))) if path is None: if is_builtin(name): return None, None, ('', '', C_BUILTIN) elif is_frozen(name): return None, None, ('', '', PY_FROZEN) else: path = sys.path for entry in path: package_directory = os.path.join(entry, name) for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: package_file_name = '__init__' + suffix file_path = os.path.join(package_directory, package_file_name) if os.path.isfile(file_path): return None, package_directory, ('', '', PKG_DIRECTORY) for suffix, mode, type_ in get_suffixes(): file_name = name + suffix file_path = os.path.join(entry, file_name) if os.path.isfile(file_path): break else: continue break # Break out of outer loop when breaking out of inner loop. else: raise ImportError(_ERR_MSG.format(name), name=name) encoding = None if 'b' not in mode: with open(file_path, 'rb') as file: encoding = tokenize.detect_encoding(file.readline)[0] file = open(file_path, mode, encoding=encoding) return file, file_path, (suffix, mode, type_) def reload(module): """**DEPRECATED** Reload the module and return it. The module must have been successfully imported before. """ return importlib.reload(module) def init_builtin(name): """**DEPRECATED** Load and return a built-in module by name, or None is such module doesn't exist """ try: return _builtin_from_name(name) except ImportError: return None if create_dynamic: def load_dynamic(name, path, file=None): """**DEPRECATED** Load an extension module. """ import importlib.machinery loader = importlib.machinery.ExtensionFileLoader(name, path) # Issue #24748: Skip the sys.modules check in _load_module_shim; # always load new extension spec = importlib.util.spec_from_file_location( name, path, loader=loader) return _load(spec) else: load_dynamic = None
zombie-imp
/zombie-imp-0.0.2.tar.gz/zombie-imp-0.0.2/zombie_imp/imp_3_11.py
imp_3_11.py
from string import maketrans import random import re import hashlib import string ZOMBISH_LETTER_MAPPING = { "a": "Ar", "b": "AA", "c": "Ab", "d": "RA", "e": "bb", "f": "BA", "g": "ll", "h": "bG", "i": "Gn", "j": "GA", "k": "GG", "l": "nh", "m": "hh", "n": "MM", "o": "hr", "p": "hA", "q": "hb", "r": "rr", "s": "hG", "t": "Gg", "u": "GM", "v": "nr", "w": "Mr", "x": "Gl", "y": "nn", "z": "KA", "A": "aR", "B": "aa", "C": "aB", "D": "ra", "E": "BB", "F": "ba", "G": "LL", "H": "Bg", "I": "gN", "J": "ga", "K": "gg", "L": "NH", "M": "HH", "N": "mm", "O": "HR", "P": "Ha", "Q": "HB", "R": "RR", "S": "Hg", "T": "gG", "U": "gm", "V": "NR", "W": "mR", "X": "gL", "Y": "NN", "Z": "ka" } REVERSE_ZOMBISH_LETTER_MAPPING = {k: v for v, k in ZOMBISH_LETTER_MAPPING.iteritems()} VALID_LETTERS = [] for k, v in ZOMBISH_LETTER_MAPPING.iteritems(): for l in v: if not l in VALID_LETTERS: VALID_LETTERS.append(l) BAD_WORD_SHA1S = ['74a4297365735b6c107b85e034347ce013eeae01', 'e0e18955d533e74a5351d5607d2f865d9fbe11e1', '540837e91f91c03c7bbbc24b69cb099d22a841f4', '666789aff6f0018d2e4cf718304c1a19f706cbb9', '8a54cc42562083149d1ed9c6ec99ddf2d8fab91c', '531119893fe30f33435cbae9c4d5444246debd09', '86a5c26f3b38e1d5b1ed15b3b6faf207441e6f53', 'f0bc8cda60f9806593744fc234b222d06fc937f4', '3d0405fe6d96ff4d6eae29fcf54871e38aa9c6cc', '5a6829cf110c007985d094ed7671cdc67ccad1e5', 'b8e3a38c3983b92b50055911c431b85eea88b0af', '4e3193331533ab82fa7d23612dcfadab41116d1d', 'fc224f2c3ac166965e2a45f91a23839b85ede24f', '3285af9eedadfc63a3806e85c8c06187ab4d0fca', 'd5b52124e8163f8afb25272fcd2993fe5f5f2a45', '9d3e79df2dc14212972ae5c556dfaf66cd4878d5', '2e9da8a1da64de4bc5faf7077ac735296b2a780b', 'e5e0c0a87be00fa5b7b5f687da5f7c0881e58f0d', '28e1bb38e3016e807de7ba854d310b536849e4a6', '61a91e2c746c89ee196a8d6405e159d2418f7c60', '97f87c14f8e48e7e226190c77a22c16bf5a88315', '67470f7d5ff1a80bd458d5b5711f3e55406ffdd0', '149f4c39fa2a88da4e00b85a795e1885b8aad4f7', 'cbd7b9d8b84782f43a9efbda03dac651949982e7', '55e0aa148f148ab1d46b633e83134d130fa9a709', 'bc4a26308f29d2e814e3f396a893d579e1f54f02', '2c82b2d5584bbffbc62ab9b7001438a9809beb7f', '7a71feae9f408177ccf61d58387395221811cf4c', 'a747e81cbca2cf2c2546d779e53eba4ec7455040', '2b21eafef31bbfa9b15d0af031dcb86dc9e545b2', 'faf4b101e0b32b1405b00a4036040e0b1a22882d', '9e3d61a6131d891950c51dd06b903679b5c4c9b8', 'd058fac6bba05d32e53ec1e167d81ca2e7665e70', '9942eb698d686a1a9b998c9476c258c9aafe1293', 'd2433614e75096963e0c4c7eef3d977f5d98b495', '9e325ce34b98f9704e8070c6f8687ce054f005c5', '097b6efe50dcd775f5d7dbfa0e8dbe8c8f4c2dc7', '7f503657e909b851d988a015286c3bf10d32aa93', 'c4107c86edd84ecdfca1d9b795fddb11b353008d', '8106bc4e517faad1c2f1f30a029224b3167f83fd', '807acd61b28d763dace0ab53dc1db211a9cb5dd0', '76c54245f3657706eecd6acbe2cdc204650ed092', '6fbf5d5685f1936b3ddd382237478b56a0c4ed0e', '7843f9623df90c487c94abf2521de7f90fc91cdd', 'a56e7b1f5c822a678289aff3bfa7f3ff09dd1af3', '58f7c55efa650924ad8006c424df3c51648ee96b', '26cb1af6f5d38a4defcd7461e64fade8752127e4', '579efa51d770b36547bc5c493c8ca7b750fa2f7d', '1f11f04ca8a528b70a320c4991143fc14ca9ce07', 'ffcd0d4ae5093b26561a8fca6096311d2a7df2dd', '755d3ffeb93ea2549e2bb8c8d49e60bf92b15f8a', '6c745098db2588df94808e4de38bb57bd14ea3d3', '64f74105e8d2f019a8a1aafa478a05eea4f343ea', '32799caae956abd598340df2c7a096dc8ea1e906', 'e1fc850eec208673b766281c093586f24046da62', '810035a11572c3e9dea0947376c35bbd0d6a1429', 'a1c79d345c0eb74679957f8acd04a5d7daf02d81', '62c25b59cd0ffd8a738a97ee052939f90cc9a421', 'e2ebbd7d504c5e4b47f3e130649151dc5cf355ef', '180481b8278b20daa9df98351dc96762dde37761', '04bcf789c82a5b6079de7a15014e261cb0a9825e', '0ebeadec39a44538c1ecca90713971c956227621', 'bc99c4bc648cf6cd9ca1e52fc51e06a5b768fb2c', '3d61943d80528aea50e1199bb20ddd714a2c4b18', 'cae7d64249d61a5417bb2592b389f9f9e7c3cbc8', '13b00fbc9da3818d080e92923cd2a7006830fc02', '7ccf656841628096f935d24149c9501be29b11c0', '41098d044b8668cd4300fa835f306252f39b2325', '26b6814d19965ecfdf01a7d0a21fce3536567120', 'cfbfa04462abbc9e8009057581bb45348a4c3a93', 'f266f5668150fe2ce8b33196b0f96ecf8855be4a', '7baacfff3bced0e0bc2ab16b63049ac1fb18a15a', '1b99738c6a82ea273cc7e7a2e81e88e940f2220f', '2324b408bd50b5e5a540000ce21f319c7d59d0d6', 'a0c678616db2a6128dd55af9842568f51fed64df', 'f8709496ee6002b5174ac0b0bfdc3fb1e3844ebf', 'de56a83bc36ac47b33324164a681294e30dbcf03', 'ec19d1e6ebc5561069d71b3ba2958b0cb1a84723', '06360bb2a813ff952e394286266a108cbd13714f', 'a269e24a0c0e29408b54c935ef6bd4818e61a5a8', '66ff1d22ed26adb6adc15cb2f87b59cb61d2d54f', 'b83faf32eefbd3eac8aa6f02c91fe4628664263a', '6c2c707e0d1f8e86fd9b5d3989201e7c75737950', 'd92d875cc0775b1cc8a9125bead4dbf840999858', '48770dfd3d23f09e02c2c70a37039de833009894', '6b86036bcaa1775b61ffca0406a8beb12e536ead', 'bb2202f38a5d70849a24466e24679dbb400901f0', '9a780aa0bb67eb4a88f5e45d153b78e17e8fcfb7', 'bc8b92e977301d0e35f53fe15d304d10e28ddcf3', '6d2705f87117603eb8396ea0ee6b9673317857f3', '6623a746cbaa591c50682a2ddd708660626609dd', '6be46662fb74a8a8affcaba45eae659bc5f9caa9', 'dc8b0b70574dbe838f27f918970043a7b3efc86a', '7327a89fda77ee4c71a4672281aeb418f76c4b54', 'c0e4c78af86ecbd0526fb47130c718948770699a', 'd6132624d10d5825aaa12d0eb471c2d1660eb860', '174f8037317a5bcd149b3c6b2629a9dd8d664f5f', 'dc4aee52e86c2b5b7d5f1406cd3cd701d55a1115', '8f29949c28fc25662aaab699adca56089de9bf9f', 'ffff3477a373c7d00b0f94dfb85c6df895962348', 'c9721c9e20e0da98f1cc81539b4514f002bec671', 'b467b0eda7936c8c77ae2ae16f1f82785154ca17', '63c3ea5b0e579f7aec8c253d53e9aeadce619f74', 'ecdcb8632194d3dcb87d00686b162a2bafb0fbc3', '8f6d4a3505bbd0ce7af49cff6fdac9bd0777c80e', '69a81c38266326ecb438e58e940bf9e26c7369e0', '581b46bd68fac4aa98a02b2fabfb2f8ed8287088', '61810241b6d720bc9cf28e8a4282f0fdf4099d3b', 'cc5a32eb62a66a887bb8decb697fabbddccadc30', 'a5332254d71129e69ee07fd42f68bfb361d6cf48', '4a1450ad6d7da5e9008d5f81db57594810b0fd83', '5df23f5917c523d7131a331c18009af96be06dc4', '7f133b2b30980a528ae20efc8dbddc2afbd4eef9', 'e96e09c97c160f130aba4b5ae0589861253e0208', '7d580d3f1a124fa8256dae33efda9c00ae68e7e2', '082d4cfdca498d1e49a6466de0dcd3851500e9f7', '1219eae2ebd8608bb4f2ea25b8a1d1ddf8792240', 'b3599b578fcc782af9f312f1f9d2d2ded1e2e714', 'ab8772b95851dc87daba09deba1fadd21527d971', '641b29dccca3839e691df3dd3a12605f32a25e3f', 'bc5a44c95fb0a47e2adc9b973e26ffefccecf9d5', '2f77f3ec2adbfd32a729d01aac988bc1273ea64a', '195028153f175b4519d43658b8dd722c01216878', 'a724b56acebfc52dcec35a8f8e2713f8e877d832', 'eac9159146e38e4424594e52ae418736924605a4', '8c9dc9686879985aa72c6c118143a8031cf9f559', 'b5a06f00909ccf8cdbba574084dff7837698774c', 'eaf42a99834830647e206fa268d816c467bcb345', '0512c8e32850c598343ffdd1ddfba8ab8aa22271', '7c0bdf13e57b6330fb4b8db4e5d1effd4bb10598', '9c1ca9b504a60a6d1e6e88c080955cbd123c76ec', 'b2917257bb11e96bdac4c32d3533cfb82506cd5b', 'bcff6cf4d3a94403b07e46a4f4ca59ddd0e119f5', 'c6f61a3fb02414445505cb6bd4416d9a4045260c', 'dfbba6752465bec0209e94898f6525c53f7e677a', '74f131f6d3afc2c053ec0f48e95e88ebc7799db2', '337c9ad9a08378f54211bb9141808618cdeb0b47', 'd2ca5005532010b8e4f2c0ba8d45046bbaebc9c0', '868ddf608f922e08a3c281c98286c89574898f8f', '4591be1c58b7b954d73630865f9e64ba6445ea47', 'f0cdfcb50aa0bea8e35aabfbb63a4037825e59b3', '46844855499713f4d693dffc053ea785309dd762', 'af94ef294a835b6d162a3752aeff845e7d2d6d60', '450cb84e7e1bd554fa2a318644860dd029ecd163', 'da62423d3acc45800bd5fbea93ee17917a79b298', '876647977fd005f7eab4681817d8ec95d3ddbafc', '82c2ebd0824723a8a7a3da71a41a3c3149380091', 'f44691bd4d3f35674aed19b766653e1476df7463', '7fe1e202ea26389e93483d1f46a90e017a0b06cd', '5838903532d749bd6171c8ca84ea55bdd59838b0', 'c96916c4ebae3cee333b1bfcb1d2e1c6383670db', 'ae95092fa28e19432d8f12f81aec5157faabdbf0', '3a75def94b98208ab18f76670316d77cf584462e', 'b3642f6e5f53fd0bb9e1c9fc163ffbca3d00d989', 'ab0f37ea4ab2633a17248c0165b4eb1e56c2c3c4', '8099e239e901d197b69e1ebff89e179b93fd8902', '27b070a93b65923efb18e5ce4d2c2c79c56220bb', '2554fab316fbb12f093b74852c9ed01c071e7bd0', '5c3b0ace776870484c851e194637f6af2f562032', '2e5304fa9ee7d29f5296356a2070b2dbea64d65e', '6f014e8bc8f386055caa50374287aa1938e1ecdc', '921f5f93f47447369b07442197b298c807ffd73f', 'a968d43478abb3462a238f015442857e9126d19d', '9cdaee6cc41399b86b4c71c5bc82568a396b8a3c', '34e209d8131973758cbea46308bd3610bc66334b', '3d1e4c66bc9e57f30897c66d0e43e7c0ae8a1c73', '27bc0234c37c1ab56aaedc99e7c9cf57ceaa191d', '840ed1f019b16f78650e2587e42d888f48eaa724', '245bd1c0bf855c6c9edbbc1642815d59838802e8', '7127fae89974b1c323c977e2fbf6e0aacdd4f701', '9b4992f9095ca7d60e3e467b84b75259fe76173e', 'fa36cb1c46904477e716f6f490bbca402c6e7808', '5cc44c54c973b898dbc93c2dec3a13e59e02a373', '523514dae9842d80e3e1c0c17353ca96da13f4ce', '447e7ac5a9aef1c2e096e70c969d5024bda6baaa', '1bff016ef7669a9e94cb996e4bd3f1c73189a859', '5c9178150a2e3d14bcce171b296296d3f2d08464', '69d396d266f235b74f988d9c29b32a4301e05827', '9324702348d8f30cf8c99b672286c62805417ce3', '9149f06a521ee3230dc5825909a4df75ead922b5', '510e70573bca51a824e345d5cff7448f740203fb', '9365c2ba9b62db6fec6366a78e534ca97249b4f8', '6dc17b64b544b9fc692f5f6f38bc3254c9d4f0d4', '3fec80d8b65cab10eb4b88323f64c201480190ef', '6f4c4cc83f34b063e5b0ccce151e44f4dcc233e4', '307047711c406ce65fa634f83027a4d25e38484b', '3884a5548634fda8f937f51c3a5397fa2bd1dcc0', 'a98ad99ae5ea1c7493dadee1078b4562e8f5f677', '87635340d332e11e30873341c5a2feeab12a32ae', '84adb93d36cb553c8fd47918dc6a6a0c102482ba', 'c10879a536b888c21b5ae27341acd66b75c2a09d', '324e4785d1302b06fd172ba3347e6162e9bccefe', '8bbfb23d05e4f9a1c20589a7ab77a896c4c21329', '34210979361f7ed821f0d21429965b9ccef00b10', 'dbfd71d987baafa03e32416302f41146aa05fd82', '9bff4fa606e39cad1aa94850e09b8db2cdd386ed', '46e955108e0ea67be7ab4a2faf2463b517e66a34', '7b758cbf4bf58184204b535fc0343ade3bcffaed', '60933ff3da52bd815f27360d3974424de402af90', 'd977078247822fb289ae1dbc03e552dfd902adbc', '9057a25d21e1f676c441019bf0dbd2cb10dfb563', '8facf342691143f5a7dea4e7ef5867bc3bf02110', '98c2f6b3c36e3d414ddc6e82ff868ed7db79910e', '486e42a249d6c7d1c87097d0e671ec7f0ebbb0f2', '272d19f2952781b02319ee0668c3349186d54a7b', 'b67ea5bb22d0083ef38ea611f0ef243084bfb768', 'f839285c92f4984a73ed980cc1e66f08142c045f', '7be42345af70a9a5bf343195f7d1292a64a1d9e8', '7ef34a651ba297fe59831497bf8c06f593e2f7ad', '44dadead9563dadd11d96466c02ff2ddd217fcfa', '252d9e5637dcbd5675aa62602dda7fbaa56d63ef', '1fa86438b81ff9f5c53f98ce2c07bf02f29463e9', 'bb00371f7e5955c5d08528afbe259117e2a1be84', '9ef9db6de61e6979e2af93e5eb61d0b5541cb033', 'ada3f3766a3a9b7dababd207b04ac7b0bedeec2f', 'b2af2c4b99cb997a1a157fccb12b951616b9ad47', '9969905ddfd027de48929288f193ac24258b7486', '436e8b13dd5c390d8904dc98695f22f492f190c8', 'b513aed7b9790904f01a8140b065935de404f3bc', '48db1e01b2e380bc35890bbda4bdf507f68443c1', '8bd88c4c56c56f6775aaccae23edde6a55c3cc34', '83c2613f95db6abab9c96ecc266ba54d72f73e4c', '7ad82de7b8ab8215089975f7c172df81e874f4dd', '4236ed4ffb09a16d92261aeb6dd8c9d90f39cb87', 'ba4e62382274e7bf3dccdbd7493d7ef114efb116', '17ded59b33ab74a04abdd18e82ecd447f2d1f56d', 'a25d3e45132b010b0b8d181bc1132c73b4624095', '8249e8333799081d901af830eca3573540d3ce8f', 'f6fabbf470b171d8af59092ac02a8fa66b79d560', 'af1522fbd00e3e3acc6564bb8af06e8e66f6eb76', '14e6b525316b7d069ff284f6082afc76ad277cf1', 'fe1308e858615956bccb18cbde9422a3b7aedd5e', '48a81b4debee9bbee6acf56e8d220d2aa2466a68', '291156139da450f7706aa3562fa85ca09a1171f2', '5ed236b191579ad08ad06a83df28febce1f9338f', '5ed236b191579ad08ad06a83df28febce1f9338f', 'bdb82ae49323035f0b6943c4e6fec927e6172c81', '2d2d9257e56326b9b61327bb6c45d45549d52abf', '7f64058904746c76208290c70f5b3c6a8234f8d3', 'ec8ac645d4f69c211e26df634dd4f9480ef545db', 'b98dd50a74e2c2be2bff3a3e095cb641c24aed0b', '303087276eea5322943dfca3b677776330c84e19', 'de9cc12b814581504eefd2a52ae7b5819d841c4a', '51cc05eb2731b27879af7bb84f6508b22cfebd31', '6778db7e23dcb2db59cf4c978bd52087983d4d70', '46d7c1a0dc1c803a5bf6482293af2d35774b65dc', '6528427efd3b0d2ff2b44c850c862b65ea0d2a51', 'abcf058aa37827b8bc4631ef427154842236d700', '04808087aebbe99b8ff92441af5a9aec97fc4e93', 'f35c3575d14333d01b0a1851e0cef7d6c7177213', 'f2043be4a04b633f7526956d9449592c66fcccf4', 'cc51e086a43a8566a6a3bab2ae51afc448f2100f', 'dea7d3964897af59b89e23fe7a02629543d68615', 'ec5661e3e7c8adc29680bca712b7fa029cf69107', '286dae502dee8ab1353983e69d2667b7b68e7aac', 'b909a4b05a7dc8b442f7cd65540ffc66b07b6ff7', '260df8bd7b170a245f09426d3c3a7cc201af96c1', 'a54a669720cec76a0af2696c0b53d3708cdb0003', '49ac5ae9620b60a27df7030aeb2f7f860bee2ed8', '5d0d572ec9c419ce3506295b6f0831ae7cc424dd', '88c6cd46c1caa37a9f1ca9ec7add73d5dfb242eb', '0f0a2b9f07d42f7ec58c90f9707e8683c67f7489', 'aa50dca9846d6726d4fc595616ab9ba08b0c619e', 'aa242a02301a19fcc8b1cc12b6934de487e1d397', '03a2c944359fed87420635da4b8b964824bb3eeb', '6d463a70ca07c74c51e49e47340304149d4198a2', '8e8a52afe8258cab4f60f1b6a7ca9e3dc6abd424', '951a9d6343c6c72ca222b80135a379674174e3b6', '5093ef689d06f519daae8269e711e65e88ac69b7', '1d59fd49915f424610f12e57820e1e7a7999d716', '633d4f313d6b1d37dc416e068299954f8d847920', 'fbfe9043751aa6389e65dda3dabccffca0b498b1', 'e46f6e478b8b94f87e048d871dd906929a563ceb', 'ccc21609ed2e31aba89325f8ca738cc771381b6e', '330a37997e6ec643636a18d5563dc786cfe25490', '69121b78d0379c81643d6cc0842c18597d14a668', 'a7f6d9ca01347643cd84d0c16c40d727be8a8967', '1d6694e053e6c1c2b2a66638a24b5f8da766a49b', '44ea6fc98b740e7ad626b920466801820e39ff57', 'cd4a78a1cbd00d2021b4d89c57820d87c6d1f3f4', 'ed873ead115d907b8a5ad079ad75ca35defbf399', '7f674d9e97d92f42cb3e195ffa0d71d6164c411d', 'b29825fbbb37e2c8e0435f9aa38190c029e06688', '82756d8ae7493a4f734cb23e4bfe2050ab460d67', '30a9a58048ab9e0b28be8c36c7d42772929c0de9', '3beb6b85304b166158d7803182a81746687d3e7b', '4f473f0a7352a26d710964ea2bcc1c7ea3b88269', '0b1bc227cbf0d212bacab313d7ef965f653412fc', '9ef0406bd2abbad65245127c0e24f41408f68675', 'bf0e7f84fecbdab4f9e544cbaeb0d0e6004d1b53', '21ab87fc69ae3796abce88faf13c0b3bbe6adedf', '918a4c4105eeb818105424c024b056885b5fa635', 'd9e4662ed4ebc283b5e82af1e0cf60da3d25fd76', 'd1f75551f2beb6f1296706bcb1fcb48f954b0eda', 'f35e2617bf00a361742686a9ffc4a3b2832c7a82', '4f76c7aa8ebd3465d064a98d2a9769c9c1a78dd4', 'c89f8cf174ef19ed42b4dc61f7b6aa153ba83a0a', 'ef0f1d453855fe2a3dd80274a689b5ebfbe7fdef', '0ddd02544cf821431a95839226d4879a22b1640b', '9e5dec4bda33388f48a2c9e4c9321ee38a0d3b36', 'c9c2d50133c0db554256abdbf884203a40091a94', '9e3ee848bcbac689dd438c76433542c1c0cbb33d', '3aaf739d9a15d799c261b206fbb2fccdb60c1966', 'd39dc9d503e0b9fce898b1d9eaad1c680995f065', '7d99bce601b524c0985fa78f52acb6be5965b76a', '51b51e51170a6560deb21afeab19a4192ba95e38', '6a9c1475da5bb76455ec1e186a1d71ccbaa8c609', '0641a9a29b7378aba46df3f3f5fe47099fdef569', 'cc39047cb415b1c27b64ec1fbea0325b9863ed9f', 'be40d3d93776d23e2bc1870765248d7abc12ca38', '5b7e8bcc0ecb01cbb84d2de7637893f4a718986b', '12f2efdd14b14489d4d65a015c56c86a2de96ee1', '88aaa81303df2a5be87b51597834499cab6e7549', 'dcc1518b9ebc889df4174b63dd3fbf9145ac3587', '6865cd9bf4296866e5389d60d2582d50b3d97812', '8e9a4538d28fb432fe8634678adce50492fd8b7f', '3c0c7fa139a7f068a9730ea6a5a9d75201420d79'] BETTER_WORDS = ["GRAANH", "MRRR", "ERRRR", "GRAGH", "MRAAH"] def better_word(): return random.choice(BETTER_WORDS) def to_zombish(phrase, with_profanity_filter=True): if with_profanity_filter: delchars = ''.join(c for c in map(chr, range(256)) if not c.isalpha()) words_split = phrase.split(" ") pattern = re.compile('[\W_]+') for i in range(0, len(words_split)): good_word = "" for w in re.findall(r"[\w\n]+|[^\s\w]", words_split[i]): if hashlib.sha1(pattern.sub('', w).upper()).hexdigest() in BAD_WORD_SHA1S: good_word += better_word() else: good_word += w words_split[i] = good_word phrase = " ".join(words_split) new_str = "" for c in phrase: try: new_str += ZOMBISH_LETTER_MAPPING[c] except KeyError: new_str += c return new_str def from_zombish(phrase): new_str = "" string_pairs = [] first = True pair = "" for s in phrase: if s in VALID_LETTERS: if first: pair = s first = False else: pair += s string_pairs.append(pair) pair = "" first = True else: if pair is not "": string_pairs.append(pair) pair = "" first = True string_pairs.append(s) new_phrase = "" for p in string_pairs: try: new_phrase += REVERSE_ZOMBISH_LETTER_MAPPING[p] except: new_phrase += p return new_phrase
zombie-translator
/zombie-translator-0.1.3.tar.gz/zombie-translator-0.1.3/zombie_translator/__init__.py
__init__.py
A Python driver for `Zombie.js <http://zombie.labnotes.org/>`_, a headless browser powered by `node.js <http://nodejs.org/>`_. :: from zombie import Browser b = Browser() b.visit('http://pypi.python.org/').fill('term', 'Zombie').pressButton('submit') assert "A Python driver for Zombie.js" in b.body.text brew install node curl https://www.npmjs.org/install.sh | sh npm install zombie .. _travis: http://travis-ci.org/ryanpetrello/python-zombie .. |travis| image:: https://secure.travis-ci.org/ryanpetrello/python-zombie.png |travis|_ Installing ========== To install Zombie from PyPI:: $ pip install zombie ...or, for the latest (unstable) tip:: $ git clone https://github.com/ryanpetrello/python-zombie -b next $ cd python-zombie && python setup.py develop Development =========== Source hosted at `GitHub <https://github.com/ryanpetrello/python-zombie>`_. Report issues and feature requests on `GitHub Issues <https://github.com/ryanpetrello/python-zombie/issues>`_. To fix bugs or add features to zombie, a GitHub account is required. The general practice for contributing is to `fork zombie <https://help.github.com/articles/fork-a-repo>`_ and make changes in the ``next`` branch. When you're finished, `send a pull request <https://help.github.com/articles/using-pull-requests>`_ and your patch will be reviewed. Tests require ``tox`` and can be run with ``python setup.py test``. All contributions must: * Include accompanying tests. * Include API documentation if new features or API methods are changed/added. * Be (generally) compliant with PEP8. One exception is that (for consistency, and to demonstrate their analogous nature) API methods on ``zombie.Browser`` should follow the camel case formatting set forth in the zombie.js API (e.g., ``Browser.pressButton``, not ``Browser.press_button``). * Not break the tests or build. Before issuing a pull request, ensure that all tests still pass across multiple versions of Python. * Add your name to the (bottom of the) ``AUTHORS`` file.
zombie
/zombie-0.2.0.tar.gz/zombie-0.2.0/README.rst
README.rst
Zombie Dice Simulator ===================== A simulator for the dice game Zombie Dice that can run bot AI players. Zombie Dice is a quick, fun dice game from Steve Jackson Games. The players are zombies trying to eat as many human brains without getting “shotgunned” by the humans. On their turn, a player will randomly select three dice from a cup of thirteen dice and roll them. The die faces are brains, footsteps, and shotguns. You get one point per brain, but if you roll a cumulative three shotguns, you’ve been shotgunned and get zero points for your turn. You can then decide to re-roll or pass your turn to the next player. If a die came up as “footsteps”, it’s used again if the player decides to re-roll. (The player always uses three dice for each roll.) Zombie Dice has a “push your luck” game mechanic: the more times you choose to re-roll the dice, the more brains you can get but the more likely you’ll collect three shotguns. The game continues until a player reaches 13 brains, and then the rest of the players get one more turn. The dice are colored green (brains are more likely), red (shotguns are more likely), and yellow (brains and shotguns are even). More complete rules for Zombie Dice can be found here: * `PDF of the rules in English <http://www.sjgames.com/dice/zombiedice/img/ZDRules_English.pdf>`_ * `Animated Flash demo of how to play <http://www.sjgames.com/dice/zombiedice/demo.html>`_ * `Instructables article with the rules <https://www.instructables.com/id/How-to-play-Zombie-Dice/>`_ * `YouTube video of someone explaining the rules <https://www.youtube.com/watch?v=xodehimqCVs>`_ This simulator is useful for beginner/intermediate programming lessons or contests. The API for making bots is simple, and it features a web UI for projecting a nifty display of the tournament as it runs. .. image:: screenshot.jpg Quickstart ---------- To install, run the usual ``pip install zombiedice`` (on Windows) or ``pip3 install zombiedice`` (on macOS/Linux). You can view a demo with some pre-made bots by running ``python -m zombiedice`` (on Windows) or ``pip3 install zombiedice`` (on macOS/Linux). Alternatively, you can run ``import zombiedice; zombiedice.demo()`` First, you need to create your own zombie. This is done by creating a class that implements a ``turn()`` method (called when it is your zombie's turn). The ``turn()`` method either calls the ``zombiedice.roll()`` function if you want to roll again, or returns to signal the end of their turn. The ``turn()`` method accepts one argument of the game state (documented later on this page). This class should also have a ``'name'`` attribute that contains a string of the player name. (This is so that the same class can be used for multiple players in a game.) The ``zombiedice.roll()`` function returns a list of dictionaries. The dictionaries represent the dice roll results; it has a ``'color'`` and ``'icon'`` keys, which have possible values of ``'green'``, ``'yellow'``, ``'red'`` and ``'shotgun'``, ``'brains'``, and ``'footsteps'`` respectively. The list will contain three of these dictionaries for the three dice roll results. If the player has reached three shotguns or more, this list will be empty. Here's an example of a zombie that keeps rolling until they've reached two shotguns, then stops. More example zombies can be found in *examples.py* in the *zombiedice* package:: class StopsAt2ShotgunsZombie(object): """This bot keeps rolling until it reaches 2 shotguns.""" def __init__(self, name): self.name = name def turn(self, gameState): shotgunsRolled = 0 while shotgunsRolled < 2: results = roll() if results == []: # Zombie has reached 3 or more shotguns. return for i in results: # Count shotguns in results. if i[ICON] == SHOTGUN: shotguns += 1 Next, you need to run a tournament. Create a file that calls either ``zombiedice.runWebGui()`` (for the nice web GUI) or ``zombiedice.runTournament()`` (for the plain command line interface). A typical file will look like *demo.py* in the `repo <https://github.com/asweigart/zombiedice>`_:: import zombiedice zombies = ( zombiedice.examples.RandomCoinFlipZombie(name='Random'), zombiedice.examples.MonteCarloZombie(name='Monte Carlo', riskiness=40, numExperiments=20), zombiedice.examples.MinNumShotgunsThenStopsZombie(name='Min 2 Shotguns', minShotguns=2) # Add any other zombie players here. ) # Uncomment one of the following lines to run in CLI or Web GUI mode: #zombiedice.runTournament(zombies=zombies, numGames=1000) zombiedice.runWebGui(zombies=zombies, numGames=1000) Example Zombies --------------- There are a few example zombies included with the module: * ``zombiedice.examples.RandomCoinFlipZombie(name)`` - Randomly decides 50/50 whether to continue rolling or quit. * ``zombiedice.examples.MinNumShotgunsThenStopsZombie(name, minShotguns)`` - Keeps rolling until it rolls the minimum number of shotguns specified. * ``zombiedice.examples.MinNumShotgunsThenStopsOneMoreZombie(name, minShotguns)`` - Like MinNumShotgunsThenStopsZombie, except it will roll one more time. * ``zombiedice.examples.HumanPlayerZombie(name)`` - Calls input() to let a human player play against the bots. * ``zombiedice.examples.RollsUntilInTheLeadZombie(name)`` - Keeps rolling until they are in first place. * ``zombiedice.examples.MonteCarloZombie(name, riskiness, numExperiments)`` - Does a number of monte carlo simulation (``numExperiments``) to determine what will happen if they roll again. As long as the percentage of simulations resulting in three shotguns is less than ``riskiness``, it will roll again. TODO ---- More details about how this module works to come.
zombiedice
/zombiedice-0.1.6.tar.gz/zombiedice-0.1.6/README.rst
README.rst
zombies ======== Run brainfuck code. License -------- MIT Installation ------------- .. code-block:: sh $ pip install zombies Python Usage ------------- .. code-block:: py import zombies interpreter = zombies.BF() code = ''' >+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-] >++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++ .------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++. ''' interpreter.run(code) # Hello World! # you can also run a .bf file interpreter.run('helloworld.bf') Command Line Usage ------------------- Run a `.bf` file .. code-block:: sh $ zombies helloworld.bf Use the REPL .. code-block:: sh $ zombies Brainfuck REPL made in Python | zombies 1.0.0a by The Master | License MIT Type "stop" to exit \\\ >>++<<+- Code Formatting ---------------- All code should be formatted with `black`.
zombies
/zombies-1.0.0.tar.gz/zombies-1.0.0/README.rst
README.rst
from .source import CommandResult, RconClient class ZomboidRCON(RconClient): """ Used to interact with Zomboid servers via RCON """ def __init__(self, ip:str='localhost', port:int=27015, password:str='', retries:int=5, logging:int=False ): super().__init__(ip, port, password, retries, logging) """ GENERAL COMMANDS """ def additem(self, user:str, item:str) -> CommandResult: """ Gives the specified player a specified item. /additem “user” “module.item” Items can be found on the PZ wiki: https://pzwiki.net/wiki/Items """ return self.command("additem", user, item) def addvehicle(self, user:str) -> CommandResult: """ Spawns a vehicle. /addvehicle “user” """ return self.command("addvehicle", user) def addxp(self, user:str, perk:str, XP:int) -> CommandResult: """ Gives XP to a player. /addxp “user” “perk=XP” """ return self.command("addxp", user, f"{perk}={str(XP)}") def alarm(self) -> CommandResult: """ Sounds a building alarm at the admin's position. Must be in a room. /alarm """ return self.command("alarm") def changeoption(self, option:str, newOption:str) -> CommandResult: """ Changes a server option. /changeoption option="newOption" """ return self.command("changeoption", f'{option}="{newOption}"') def chopper(self) -> CommandResult: """ Places a helicopter event on a random player. /chopper """ return self.command("chopper") def changepwd(self, pwd:str, newPwd:str) -> CommandResult: """ Changes your password. /changepwd “pwd” “newPwd” """ return self.command("changepwd", pwd, newPwd) def createhorde(self, number:int) -> CommandResult: """ Spawns a horde near a player. /createhorde “number” """ return self.command("createhorde", str(number)) def godmode(self, user:str) -> CommandResult: """ Makes a player invincible. /godmode "user" """ return self.command("godmode", user) def gunshot(self) -> CommandResult: """ Makes a gunshot noise near the player. /gunshot """ return self.command("gunshot") def help(self) -> CommandResult: """ Brings up the help menu. /help Not to be confused with the commands available within zomboid_rcon. For a list of these commands see zomboid_rcon's Github repo: https://github.com/jmwhitworth/zomboid_rcon """ return self.command("help") def invisible(self, user:str) -> CommandResult: """ Makes a player invisible to zombies. /invisible “user” """ return self.command("invisible", user) def noclip(self, user:str) -> CommandResult: """ Allows a player to pass through solid objects. /noclip “user” """ return self.command("noclip", user) def quit(self) -> CommandResult: """ Saves and quits the server. /quit """ return self.command("quit") def releasesafehouse(self) -> CommandResult: """ Releases a safehouse you own. /releasesafehouse """ return self.command("releasesafehouse") def reloadlua(self, filename:str) -> CommandResult: """ Reload a lua script on the server. /reloadlua "filename" """ return self.command("reloadlua", filename) def reloadoptions(self) -> CommandResult: """ Reloads server options. /reloadoptions """ return self.command("reloadoptions") def replay(self, user:str, command:str, filename:str) -> CommandResult: """ Records and plays a replay for a moving player. /replay “user” [-record | -play | -stop] “filename” """ return self.command("replay", user, command, filename) def save(self) -> CommandResult: """ Saves the current world. /save """ return self.command("save") def sendpulse(self) -> CommandResult: """ Toggles sending server performance info to the client. /sendpulse """ return self.command("sendpulse") def showoptions(self) -> CommandResult: """ Shows a list of current server options and values. /showoptions """ return self.command("showoptions") def startrain(self) -> CommandResult: """ Starts rain on the server. /startrain """ return self.command("startrain") def stoprain(self) -> CommandResult: """ Stops rain on the server. /stoprain """ return self.command("stoprain") def teleport(self, user:str, toUser:str) -> CommandResult: """ Teleports to a player. /teleport "toUser" or /teleport "user" "toUser" """ if toUser is not None: return self.command("teleport", user, toUser) return self.command("teleport", user) def teleportto(self, x:int, y:int, z:int) -> CommandResult: """ Teleports to certain coordinates. /teleportto x,y,z """ return self.command("teleportto", f"{str(x)},{str(y)},{str(z)}") """ MODERATION COMMANDS """ def addalltowhitelist(self) ->CommandResult: """ Adds all current users connected with a password to the whitelist. /addalltowhitelist """ return self.command("addalltowhitelist") def adduser(self, user:str, pwd:str) -> CommandResult: """ Adds a new user to the whitelist. /adduser “user” “pwd” """ return self.command("adduser", user, pwd) def addusertowhitelist(self, user:str) -> CommandResult: """ Adds a single user connected with a password to the whitelist. /addusertowhitelist “user” """ return self.command("addusertowhitelist", user) def removeuserfromwhitelist(self, user:str) -> CommandResult: """ Removes a single user connected with a password to the whitelist. /removeuserfromwhitelist “user” """ return self.command("removeuserfromwhitelist", user) def banid(self, SteamID:str) -> CommandResult: """ Bans a Steam ID. /banid “SteamID” """ return self.command("banid", SteamID) def unbanid(self, SteamID:str) -> CommandResult: """ Unbans a Steam ID. /unbanid “SteamID” """ return self.command("unbanid", SteamID) def banuser(self, user:str) -> CommandResult: """ Bans a user. /ban "user" """ return self.command("banuser", user) def unbanuser(self, user:str) -> CommandResult: """ Unbans a user. /unban "user" """ return self.command("unbanuser", user) def checkModsNeedUpdate(self) -> CommandResult: """ Indicates whether a mod has been updated. Writes answer to log file. /checkModsNeedUpdate """ return self.command("checkModsNeedUpdate") def grantadmin(self, user:str) -> CommandResult: """ Gives admin rights to a user. /grantadmin "user" """ return self.command("grantadmin", user) def removeadmin(self, user:str) -> CommandResult: """ Removes admin rights to a user. /removeadmin "user" """ return self.command("removeadmin", user) def kickuser(self, user:str) -> CommandResult: """ Kicks a user from the server. /kickuser “user” """ return self.command("kickuser", user) def players(self) -> CommandResult: """ Lists all connected players. /players """ return self.command("players") def servermsg(self, message:str) -> CommandResult: """ Broadcast a message to all players. /servermsg “message” Spaces are replaced with underscores for compatibility. """ return self.command("servermsg", message.replace(' ', '_').strip()) def setaccesslevel(self, user:str, accesslevel:str) -> CommandResult: """ Set the access/permission level of a player. /setaccesslevel “user” “[admin | moderator | overseer | gm | observer]” """ return self.command("setaccesslevel", user, accesslevel) def voiceban(self, user:str, ban:str) -> CommandResult: """ Ban a user from using the voice feature. /voiceban “user” [-true | -false] """ return self.command("voiceban", user, ban)
zomboid-rcon
/zomboid_rcon-1.0.2-py3-none-any.whl/zomboid_rcon/zomboid_rcon.py
zomboid_rcon.py
class CommandResult: """ A class representing the result of executing a command. """ def __init__(self, command:str, response:str, successful:bool=False, failureMessage:str="Command was unsuccessful" ): """ Args: command (str): The command that was executed. response (str): The response to the command. successful (bool, optional): Whether the command was successful. Defaults to False. failureMessage (str, optional): The message to display if the command was unsuccessful. Defaults to "Command was unsuccessful". """ self.command = command self.response = response self.successful = successful self.failureMessage = failureMessage @property def command(self) -> str: """ Returns command used """ return self._command @command.setter def command(self, command:str) -> None: """ Validates input as string Returns true if set successfully """ if isinstance(command, str): self._command = command.strip() else: raise ValueError("Command used must be a string") @property def failureMessage(self) -> str: """ Returns failure message if command unsuccessful """ return self._failureMessage @failureMessage.setter def failureMessage(self, failureMessage:str) -> None: """ Validates input as string Returns true if set successfully """ if isinstance(failureMessage, str): self._failureMessage = failureMessage.strip() else: raise ValueError("Failure message used must be a string") @property def response(self) -> str: """ Returns the command's response. If command failed, returns failure message. """ if self.successful: return self._response return self.failureMessage @response.setter def response(self, newResponse:str) -> None: """ Validates input as string Returns true if set successfully """ if isinstance(newResponse, str): self._response = newResponse.strip() else: raise ValueError("Command response must be a string") @property def successful(self) -> bool: """ Returns if command was successful """ return self._successful @successful.setter def successful(self, successStatus:bool) -> None: """ Validates input as boolean Returns true if set successfully """ if isinstance(successStatus, bool): self._successful = successStatus else: raise ValueError("Success status must be a boolean")
zomboid-rcon
/zomboid_rcon-1.0.2-py3-none-any.whl/zomboid_rcon/source/CommandResult.py
CommandResult.py
from rcon.source import Client from timeout_decorator import timeout, TimeoutError from .CommandResult import CommandResult class RconClient: """ Parent class for handling RCON core functionality """ def __init__(self, ip:str, port:int, password:str, retries:int=5, logging:bool=False ): """ Args: ip (str): The IP Address of the server. port (int): The RCON port of the server. password (str): The RCON password of the server. retries (int): Number of times to retry on request timeout. logging (bool): Print processes in terminal while running, used in debugging. """ self._ip = ip self._port = port self._password = password self._retries = retries self.logging = logging def createClient(self) -> Client: """ Returns an rcon.source.Client object for requests """ return Client(self._ip, self._port, passwd=self._password) def command(self, command:str, *args) -> CommandResult: """ Attempts to execute a given command. Upon TimeoutError it will retry according to self._retries """ tries = 0 while tries < self._retries: try: result = self._command(command, *args) return CommandResult( command = command, successful = True, response = result ) except TimeoutError: if self.logging: print(f"({tries+1}/{self._retries}) Request timed out, retrying...") tries += 1 return CommandResult( command = command, successful = False, response = f"Session timed out (after {self._retries} attempt(s))" ) @timeout(10) def _command(self, command:str, *args) -> str: """ Private method to handle timeouts """ try: with self.createClient() as client: return client.run(command, *args) except ConnectionRefusedError: return "Connection refused" def getInfo(self) -> dict: """ Returns dict of current object's information """ return { "ip": self._ip, "port": self._port, "password": self._password, "retries": self._retries }
zomboid-rcon
/zomboid_rcon-1.0.2-py3-none-any.whl/zomboid_rcon/source/RconClient.py
RconClient.py
import os class __EnvArgParser(object): """ Works a lot like ArgParse but ONLY for environment variables. Based on this idea: https://pypi.python.org/pypi/ConfigArgParse but hand rolled because ConfigArgParse's documentation was sparse and we only need to read in Environment variables """ def __init__(self): self.args = [] self.OPTIONS = _Options() self.initialized = False def add_argument(self, **kwargs): """ Each add argument call is in the form: add_argument(env_var='SOMEVARNAME', required=True, help='This variable does whatever', type=str, validation=lambda x: somethingsomething) :param env_var: The environment variable is fetched from the environment and placed into the resulting object as an instance WITH THAT SAME NAME. (i.e PROMETHEUS_CLIENT the environment variable will become OPTIONS.PROMETHEUS_CLIENT) :param required: can be true or false, if required=False a default must be provided :param default: The default value. Must be set if required=False, cannot be set if required=True :param validation: Optional, a function should be provided that takes a single value, and should return True, False (or an Exception). False or an exception will prevent the program from launching :param help: This message is displayed if an argument doesnt exist or fails validation. It should explain to the user what the argument is for to assist them in defining it. :param type: Optional, if the value needs to be something other than a string, specify what it should be converted to. """ # Check to see if our required function arguments are defined if 'env_var' not in kwargs or 'required' not in kwargs or "help" not in kwargs: raise Exception("'env_var', 'required' and 'help' are mandatory for each add argument call") # If required is false but a default is not defined, that's a problem if not kwargs['required'] and 'default' not in kwargs: raise Exception("If 'required' is false then a 'default' must be provided") # Otherwise, if required is TRUE, then we cannot have a default elif kwargs['required'] and 'default' in kwargs: raise Exception("'Default' cannot be provided if required=True") self.args.append(kwargs) def parse_args(self): self.initialized = True for a in self.args: a = _Struct(**a) if a.env_var not in os.environ: # We don't have an environment value set if a.required: self._log_and_throw(f"Environment variable {a.env_var} is required " f"but was not found on the system. Help: {a.help}") else: self.OPTIONS.set_attribute(a.env_var, self._convert_if_necessary(a, a.default)) else: env_value = os.environ[a.env_var] # We do have an environment value set if hasattr(a, 'validation'): # If we have a validation method defined for this argument, lets run it try: validated = a.validation(env_value) except Exception: validated = False if not validated: self._log_and_throw(f"Environment variable {a.env_var} did not pass validation. " f"Its value was set to {env_value}. Help: {a.help}") # If we're still here, we either passed # validation or didn't have any to begin # with. Either way, set the option and move on. self.OPTIONS.set_attribute(a.env_var, self._convert_if_necessary(a, env_value)) def get_options(self): if not self.initialized: self.parse_args() return self.OPTIONS def initialize(self): if not self.initialized: self.parse_args() def _convert_if_necessary(self, a, val): """ Helper method to convert a given argument to a different type. :param a: argument :return: The converted val """ if hasattr(a, 'type'): if a.type is bool: val = val.lower() in ("yes", "true", "t", "1", "y", "yeah") else: try: val = a.type(val) except Exception as e: self._log_and_throw(f"An exception occurred when converting {a.env_var}. " f"Tried to convert {val} to {a.type}. Exception: {e}") return val @staticmethod def _log_and_throw(message): """ A little convenience method to log an error and raise is as an Exception """ print(message) raise Exception(message) class _Struct: """ Silly hack to get dictionaries to behave like objects (where each entry is an attribute) Its silly there isn't a more "official" way to do this in python since its cleaner to read, if someone knows a better way please use it, I stole this from https://stackoverflow.com/questions/1305532/convert-python-dict-to-object """ def __init__(self, **entries): self.__dict__.update(entries) class _Options(object): """ This object has attributes set on it depending on what options are passed in. """ def __init__(self): pass def set_attribute(self, name, value): setattr(self, name, value) def __str__(self): option_strings = [] for attr, value in self.__dict__.items(): option_strings.append(str(attr) + " = " + str(value)) return "\n".join(option_strings) # This is what's meant to be imported so we only have a single instance of __EnvArgParser env_arg_parser = __EnvArgParser()
zonar-ds-env-arg-parser
/zonar_ds_env_arg_parser-1.0.1-py3-none-any.whl/zonar_ds_env_arg_parser/env_arg_parser.py
env_arg_parser.py
zonar_ds_logger ====== Overview ------ A logger class that initializes a logger and logs in json when specified. It also redirects flask logs so it doesn’t always show up as ERROR Usage ------ ```python from zonar_ds_logger.logger import logger logger.initialize("evan-test", "info", False) log = logger.get_logger() log.debug("debug") log.info("info") log.warning("warning") log.error("error") ``` Arguments ------ Parameters that can be passed into logger.initialize are as follows: - name (str): Name of the logger - log_level (str): Lowest log level to log. Default is "debug". Options are "debug", "info", "warning", "error" - json_logging (bool): Whether to log in json or not. Options that evaluate to true are ("true", "t", "1", "y", "yes") Default converts value in JSON_LOGGING env var to bool if set else True
zonar-ds-logger
/zonar_ds_logger-1.0.0.tar.gz/zonar_ds_logger-1.0.0/README.md
README.md
import logging import sys import socket import os from pythonjsonlogger import jsonlogger _LOG_LEVEL_CONVERSION = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, } class __Logger(object): """ Helper class to initialize loggers and output in json format when specified. It also redirects flask logs so it doesn't log as ERROR all the time. """ def __init__(self): self.logger = None def get_logger(self): """ Get the logger instance :return: logger :raises: Exception if logger hasn't been initialized """ if self.logger is None: raise Exception("Logger has not been initialized") return self.logger def initialize(self, name, log_level="debug", json_logging=(os.getenv('JSON_LOGGING').lower() in ("true", "t", "1", "y", "yes") if os.getenv('JSON_LOGGING') is not None else True)): """ Initializes logger with given parameters :param name: Name of the logger :type name: str :param log_level: Lowest log level to log. Default is "debug". Options are "debug", "info", "warning", "error" :type log_level: str :param json_logging: Whether to log in json or not. Options that evaluate to true are ("true", "t", "1", "y", "yes") Default converts value in JSON_LOGGING env var to bool if set else True :type json_logging: bool :return: None :raises: Exception if logger has not been initialized or log_level/json_logging is invalid """ if self.logger is not None: raise Exception("Logger has already been initialized") if log_level not in _LOG_LEVEL_CONVERSION: raise Exception(f"Log level {log_level} is unknown. " f"Valid options include 'debug'', 'info'', 'warning'', 'error'") log_level = _LOG_LEVEL_CONVERSION[log_level] logger = logging.getLogger(name) logger.setLevel(log_level) if json_logging: formatter = _StackdriverJsonFormatter(timestamp=True) else: hostname = str(socket.getfqdn()) formatter = logging.Formatter(hostname + ' - %(asctime)-15s %(name)-5s %(levelname)-8s - %(message)s') # STDOUT stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) stdout_handler.addFilter(lambda record: record.levelno <= logging.WARNING) logger.addHandler(stdout_handler) stdout_handler.setFormatter(formatter) # STDERR stderr_handler = logging.StreamHandler(sys.stderr) stderr_handler.setLevel(logging.ERROR) logger.addHandler(stderr_handler) stderr_handler.setFormatter(formatter) # Redirect flask/werkzeug logging so it doesn't go to STDERR all the time. flask_logger = logging.getLogger('werkzeug') flask_logger.setLevel(logging.ERROR) flask_logger.addHandler(stdout_handler) flask_logger.addHandler(stderr_handler) self.logger = logger # Taken from https://medium.com/retailmenot-engineering/formatting-python-logs-for-stackdriver-5a5ddd80761c # and modified to have stack traces in the 'message' field class _StackdriverJsonFormatter(jsonlogger.JsonFormatter, object): def __init__(self, fmt="%(levelname) %(message) %(stacktrace)", style='%', *args, **kwargs): jsonlogger.JsonFormatter.__init__(self, fmt=fmt, *args, **kwargs) def process_log_record(self, log_record): log_record['severity'] = log_record['levelname'] del log_record['levelname'] if 'exc_info' in log_record: log_record['message'] += '\n' + log_record['exc_info'] del log_record['exc_info'] return super(_StackdriverJsonFormatter, self).process_log_record(log_record) # This is meant to be imported logger = __Logger()
zonar-ds-logger
/zonar_ds_logger-1.0.0.tar.gz/zonar_ds_logger-1.0.0/zonar_ds_logger/logger.py
logger.py
====================================== New shiny Sphinx Theme for ZEIT ONLINE ====================================== Usage ----- Install the package .. code-block:: text $ pip install zondocs_theme Then set ``html_theme = 'zondocs_theme'`` in your Sphinx ``conf.py``. Features -------- * Automatically uses the ZON logo. * Adds an "edit this page" link to the sidebar. To customize how this link is created, you can set the following:: html_theme_options = { 'editme_link': ( 'https://github.com/zeitonline/{project}/edit/master/{page}') } (This is the default value, it supports two variables, ``project`` is taken directly from ``conf.py``, and ``page`` evaluates to ``path/to/current/page.suffix``) Release process --------------- `pipenv` is needed to run the release process. To release the package run .. code-block:: text $ bin/release
zondocs-theme
/zondocs_theme-1.0.7.tar.gz/zondocs_theme-1.0.7/README.rst
README.rst
# Zone API - an alternative approach to writing rules In OpenHab, items are defined in a flat manner in the *.items* files under the */etc/openhab/items folder*. They are typically linked to a channel exposed by the underlying hardware. This flat structure has an impact on how rules (whether in Xtend or Jython) are organized. As there is no higher level abstraction, rules tend to listen to changes from the specific devices. When the rules need to interact with multiple devices of the same type, they can utilize the [group concept](https://www.openhab.org/docs/configuration/items.html#groups). An example of good usage of group is to turn off all lights. By linking all smart lights to a group switch, turning off all the lights can be done by changing the state of the group switch to OFF. What is more tricky is when rules need to interact with different devices within the same area. The typical solution is to group unrelated items that belong to the same zone either by using a naming pattern, or by dedicated groups. For example, the light switch and motion sensor in the Foyer area can be named like this: "FF_Foyer_Light", and "FF_Foyer_MotionSensor". When a sensor is triggered, the zone can be derived from the name of the triggering item, and other devices/sensors can be retrieved using that naming convention. This works but as there is not sufficient abstraction, the rules are highly coupled to the naming pattern. The [Zone API](https://github.com/yfaway/zone-apis) provides another approach. It is a layer above the devices / sensors. Each [ZoneManager](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/immutable_zone_manager.py) (i.e. a house) contains multiple [zones](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/zone.py) (i.e. rooms), and each zone contains multiple [devices](https://github.com/yfaway/zone-apis/tree/master/src/zone_api/core/devices). Each zone is associated with a set of [actions](https://github.com/yfaway/zone-apis/tree/master/src/zone_api/core/actions) that are triggered by certain [events](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/zone_event.py). The usual OpenHab events are routed in this manner: ``` OpenHab events --> ZoneManager --> Zones --> Actions ``` The actions operate on the abstract devices and do not concern about the naming of the items or the underlying hardware. They replace the traditional OpenHab rules. Actions can be unit-tested with various levels of mocking. **Most importantly, it enables reusing of action logics.** There is no need to reinvent the wheels for common rules such as turning on/off the lights. All ones need to do is to populate the zones and devices / sensors, and the applicable actions will be added and processed automatically. ZoneApi comes with a set of built-in [actions](https://github.com/yfaway/zone-apis/tree/master/src/zone_api/core/actions). There is no need to determine what action to add to a system. Instead, they are added automatically based on the zones structure and based on the type of devices available in each zone. Here is a sample info log that illustrate the structure of the managed objects. ```text Zone: Kitchen, floor: FIRST_FLOOR, internal, displayIcon: kitchen, displayOrder: 3, 7 devices AstroSensor: VT_Time_Of_Day HumiditySensor: FF_Kitchen_Humidity IlluminanceSensor: FF_Kitchen_LightSwitch_Illuminance Light: FF_Kitchen_LightSwitch, duration: 5 mins, illuminance: 8 MotionSensor: FF_Kitchen_SecurityMotionSensor, battery powered MotionSensor: FF_Kitchen_LightSwitch_PantryMotionSensor, battery powered TemperatureSensor: FF_Kitchen_Temperature Action: HUMIDITY_CHANGED -> AlertOnHumidityOutOfRange Action: MOTION -> TurnOnSwitch Action: MOTION -> AnnounceMorningWeatherAndPlayMusic Action: MOTION -> PlayMusicAtDinnerTime Action: SWITCH_TURNED_ON -> TurnOffAdjacentZones Action: TEMPERATURE_CHANGED -> AlertOnTemperatureOutOfRange Action: TIMER -> TellKidsToGoToBed Neighbor: FF_Foyer, OPEN_SPACE Neighbor: FF_GreatRoom, OPEN_SPACE_MASTER Zone: Foyer, floor: FIRST_FLOOR, internal, displayIcon: groundfloor, displayOrder: 4, 6 devices AlarmPartition: FF_Foyer_AlarmPartition, armMode: ARM_STAY AstroSensor: VT_Time_Of_Day Door: FF_Foyer_Door Light: FF_Foyer_LightSwitch, duration: 5 mins, illuminance: 8, no premature turn-off time range: 0-23:59 MotionSensor: FF_Foyer_LightSwitch_ClosetMotionSensor, battery powered MotionSensor: FF_Foyer_LightSwitch_MotionSensor, battery powered Action: MOTION -> TurnOnSwitch Action: MOTION -> DisarmOnInternalMotion Action: MOTION -> ManagePlugs Action: PARTITION_ARMED_AWAY -> ChangeThermostatBasedOnSecurityArmMode Action: PARTITION_ARMED_AWAY -> ManagePlugs Action: PARTITION_ARMED_AWAY -> TurnOffDevicesOnAlarmModeChange Action: PARTITION_DISARMED_FROM_AWAY -> ChangeThermostatBasedOnSecurityArmMode Action: PARTITION_DISARMED_FROM_AWAY -> ManagePlugs Action: PARTITION_DISARMED_FROM_AWAY -> TurnOffDevicesOnAlarmModeChange Action: SWITCH_TURNED_ON -> TurnOffAdjacentZones Action: TIMER -> ArmStayIfNoMovement Action: TIMER -> ArmStayInTheNight Action: TIMER -> ManagePlugs Neighbor: SF_Lobby, OPEN_SPACE Neighbor: FF_Office, OPEN_SPACE_MASTER ``` **Running on top of HABApp but with minimal dependency:** > [The original Zone API modules](https://github.com/yfaway/openhab-rules/tree/master/legacy-jython-code) > were written in Jython. It was recently migrated over to the [HABApp](https://habapp.readthedocs.io/en/latest/installation.html) > framework with minimal changes needed to the core code. See [here](https://community.openhab.org/t/habapp-vs-jsr223-jython/112914) > for the comparison between HABApp and JSR223 Jython. > > There are 3 peripheral modules that are tightly coupled to the HABApp API. The rest of the modules > is framework neutral. It is possible to migrate Zone API to another framework running on top of GravVM when > it is available. Zone API is now written in Python 3 and thus is not compatible with Jython > (equivalent to Python 2.8). # Set up your home automation system with zone_api ## 1. Name the OpenHab items using the default naming convention ```Zone_api``` comes with a default parser that builds the zone manager using a pre-defined naming convention. See the ZoneParser section at the end of this page for details. Here are a few sample .items files. Note that the file organization doesn't matter; all items can be defined in a single file if desired. **zones.items**: defines two zones and their relationship. ```csv String Zone_Office { level="FF", displayIcon="office", displayOrder="2", openSpaceSlaveNeighbors="FF_Foyer" } String Zone_Foyer { level="FF", displayIcon="groundfloor", displayOrder="4", openSpaceMasterNeighbors="FF_Office", openSpaceNeighbors="SF_Lobby" } ``` **foyer.items**: defines the items in the Foyer zone. ```csv Switch FF_Foyer_LightSwitch "Foyer Light" (gWallSwitch, gLightSwitch, gFirstFloorLightSwitch) { channel="zwave:device:9e4ce05e:node2:switch_binary", disableMotionTriggeringIfOtherLightIsOn="FF_Office_LightSwitch", durationInMinutes="5"} Switch FF_Foyer_LightSwitch_ClosetMotionSensor "Foyer Closet Motion Sensor" (gWallSwitchMotionSensor) { channel="mqtt:topic:myBroker:xiaomiMotionSensors:FoyerMotionSensor"} ``` **office.items**: defines the items in the Office zone. ```csv Switch FF_Office_LightSwitch "Office Light" (gWallSwitch, gLightSwitch, gFirstFloorLightSwitch) [shared-motion-sensor] { channel="zwave:device:9e4ce05e:node8:switch_binary", durationInMinutes="15" } Switch FF_Office_LightSwitch_MotionSensor "Office Motion Sensor" (gWallSwitchMotionSensor, gFirstFloorMotionSensors) { channel="mqtt:topic:myBroker:xiaomiMotionSensors:OfficeMotionSensor"} ``` That's it. Once the system is fully set up, ZoneApi's default actions will be registered automatically depending on the available devices. In the example above, the two zones have light switches and motion sensor. Thus the light rule is applicable and will automatically turn on the light when a motion sensor is triggered, and turn it off if there is no activity for the pre-defined duration. It will also turn off lights in the dependent zones. ## 2. Clone this repository ```git clone [email protected]:yfaway/zone-apis.git``` ## 3. Install, configure, and run HABapp Refer to the instructions on the [official HABApp website](https://habapp.readthedocs.io/en/latest/installation.html). The instruction below is specifically for the zone_api. ```bash sudo apt-get install python3-venv # to install python3-venv library cd zone_api # the cloned project in the section above python3 -m venv . source bin/activate # to get into our virtual environment python3 -m pip install --upgrade pip # to upgrade the pip library. python3 -m pip install habapp request schedule # request and schedule are required by zone_api ``` To manually run HABApp, execute this command within the ```zone_api``` folder: ```bash ./bin/habapp --config ./habapp/config.yml ``` The ```./habapp/rules``` folder contains the bootstrap [rule](https://github.com/yfaway/zone-apis/blob/master/habapp/rules/configure_zone_manager.py) to initialize the ```zone_api``` framework. The rule is pretty simple with its entire content below. ```python import HABApp from zone_api import zone_parser as zp from zone_api.core.devices.activity_times import ActivityType, ActivityTimes class ConfigureZoneManagerRule(HABApp.Rule): def __init__(self): super().__init__() self.run_soon(self.configure_zone_manager) # noinspection PyMethodMayBeStatic def configure_zone_manager(self): time_map = { ActivityType.WAKE_UP: '6 - 9', ActivityType.LUNCH: '12:00 - 13:30', ActivityType.QUIET: '14:00 - 16:00, 20:00 - 22:59', ActivityType.DINNER: '17:50 - 20:00', ActivityType.SLEEP: '23:00 - 7:00', ActivityType.AUTO_ARM_STAY: '20:00 - 2:00', ActivityType.TURN_OFF_PLUGS: '23:00 - 2:00', } zone_manager = zp.parse(ActivityTimes(time_map)) ConfigureZoneManagerRule() ``` The code above defines an ActivityTimes object with various activity time periods and pass it over to the [zone_parser](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/zone_parser.py) module. The zone_parser parses the OpenHab items following a specific naming pattern, and construct the zones and the devices / sensors. It then registers the handlers for the events associated with the devices / sensors. Finally, it loads all the actions and add them to the zones based on the pre-declared execution rules associated with each action (more on this later). That's it; from this point forward, events generated by the devices / sensors will trigger the associated actions. It is important to note that the zone_parser is just a default mechanism to build the ZoneManager. A custom module can be used to parse from a different naming pattern for the OpenHab items, or the ZoneManager can be constructed manually. The role of the parser is no longer needed once the ZoneManager has been built. # ZoneManager Contains a set of zones and is responsible for dispatching the events to the zones. # Zone Contains a set of devices, actions, and is responsible for dispatching the events to the actions. A zone is aware of its neighbors. Certain rules such as the [turning on/off of the lights](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/actions/turn_on_switch.py) is highly dependent on the layout of the zones. The following [neighbor](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/neighbor.py) types are available. 1. ```CLOSED_SPACE``` 2. ```OPEN_SPACE``` 3. ```OPEN_SPACE_MASTER``` 4. ```OPEN_SPACE_SLAVE``` # Devices The [devices](https://github.com/yfaway/zone-apis/tree/master/src/zone_api/core/devices) contains one or more underlying OpenHab items. Rather than operating on a SwitchItem or on a NumberItem, the device represents meaningful concrete things such as a [MotionSensor](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/devices/motion_sensor.py), or a [Light](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/devices/switch.py). Devices contain both attributes (e.g. 'is the door open') and behaviors (e.g. 'arm the security system'). # Events Similar to the abstraction for the devices, the events are also more concrete. Zone API maps the OpenHab items events to the event enums in [ZoneEvent](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/zone_event.py) such as ```ZoneEvent.HUMIDITY_CHANGED``` or ```ZoneEvent.PARTITION_ARMED_AWAY```. There is also the special event ```ZoneEvent.TIMER``` that represents triggering from a scheduler. The event is dispatched to the appropriate zones which then invokes the actions registered for that event. See [EventInfo](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/event_info.py) for more info. # Actions All the [actions](https://github.com/yfaway/zone-apis/tree/master/src/zone_api/core/actions) implement the [Action](https://github.com/yfaway/zone-apis/blob/master/src/zone_api/core/action.py) interface. The action's life cycle is represented by the three functions: 1. ```on_startup()``` - invoked after the ZoneManager has been fully populated, via the event ```ZoneEvent.STARTUP```. 2. ```on_action()``` - invoked where the device generates an event or when a timer event is triggered (via ```ZoneEvent.TIMER```). 3. ```on_destroy()``` - currently not invoked. The ```@action``` decorator provides execution rules for the action as well as basic validation. If the condition (based on the execution rules) does not match, the action won't be executed. Below are the currently supported decorator parameters: 1. *devices* - the list of devices the zone must have in order to invoke the action. 2. *events* - the list of events for which the action will response to. 3. *internal* - if set, this action is only applicable for internal zone 4. *external* - if set, this action is only applicable for external zone 5. *levels* - the zone levels that this action is applicable to. the empty list default value indicates that the action is applicable to all zone levels. 6. *unique_instance* - if set, do not share the same action instance across zones. This is the case when the action is stateful. 7. *zone_name_pattern* - if set, the zone name regular expression that is applicable to this action. 8. *external_events* - the list of events from other zones that this action processes. These events won't be filtered using the same mechanism as the internal events as they come from other zones. 9. *priority* - the action priority with respect to other actions within the same zone. Actions with lower priority values are executed first. These parameters are also available to the action and can be used as a filtering mechanism to make sure that the action is only added to the applicable zones. Here is a simple action to disarm the security system when a motion sensor is triggered: ```python from zone_api import security_manager as sm from zone_api.core.devices.activity_times import ActivityTimes from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.devices.alarm_partition import AlarmPartition @action(events=[ZoneEvent.MOTION], devices=[AlarmPartition, MotionSensor]) class DisarmOnInternalMotion: """ Automatically disarm the security system when the motion sensor in the zone containing the security panel is triggered and the current time is not in the auto-arm-stay or sleep time periods. """ def on_action(self, event_info): events = event_info.get_event_dispatcher() zone_manager = event_info.get_zone_manager() if not sm.is_armed_stay(zone_manager): return False activity = zone_manager.get_first_device_by_type(ActivityTimes) if activity is None: self.log_warning("Missing activities time; can't determine wake-up time.") return False if activity.is_auto_arm_stay_time() or (activity.is_sleep_time() and not activity.is_wakeup_time()): return False sm.disarm(zone_manager, events) return True ``` The decorator for the action above indicates that it is triggered by the motion event, and should only be added to a zone that contains both the AlarmPartition and the Motion devices. # ZoneParser The default parser uses this naming pattern for the OpenHab items. 1. The zones are defined as a String item with this pattern Zone_{name}: String Zone_GreatRoom { level="FF", displayIcon="player", displayOrder="1", openSpaceSlaveNeighbors="FF_Kitchen" } - The levels are the reversed mapping of the enums in Zone::Level. - Here are the list of supported attributes: level, external, openSpaceNeighbors, openSpaceMasterNeighbors, openSpaceSlaveNeighbors, displayIcon, displayOrder. 2. The individual OpenHab items are named after this convention: ```{zone_id}_{device_type}_{device_name}```. Here's an example: Switch FF_Office_LightSwitch "Office Light" (gWallSwitch, gLightSwitch, gFirstFloorLightSwitch) [shared-motion-sensor] { channel="zwave:device:9e4ce05e:node8:switch_binary", durationInMinutes="15" } See here for a [sample .items](https://github.com/yfaway/openhab-rules/blob/master/items/switch-and-plug.items) file that is parsable by ZoneParser.
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/README.md
README.md
from typing import Union from zone_api.core.devices.alarm_partition import AlarmPartition, AlarmState from zone_api.core.immutable_zone_manager import ImmutableZoneManager """ Provide quick access to the alarm partition of the zones. """ def has_security_system(zm: ImmutableZoneManager): """ Returns True if the house has a security system. """ return _get_partition(zm) is not None def is_armed_away(zm: ImmutableZoneManager): """ :return: True if at least one zone is armed-away """ partition = _get_partition(zm) if partition is not None: return AlarmState.ARM_AWAY == partition.get_arm_mode() return False def is_armed_stay(zm: ImmutableZoneManager): """ :return: True if at least one zone is armed-stay """ partition = _get_partition(zm) if partition is not None: return AlarmState.ARM_STAY == partition.get_arm_mode() return False def is_unarmed(zm: ImmutableZoneManager): """ :return: True if at least one zone is unarmed. """ partition = _get_partition(zm) if partition is not None: return AlarmState.UNARMED == partition.get_arm_mode() return False def arm_away(zm: ImmutableZoneManager, events): """ Arms the security system in 'away' mode. """ partition = _get_partition(zm) if partition is None: raise ValueError('Missing security partition.') partition.arm_away(events) def arm_stay(zm: ImmutableZoneManager, events): """ Arms the security system in 'stay' mode. """ partition = _get_partition(zm) if partition is None: raise ValueError('Missing security partition.') partition.arm_stay(events) def disarm(zm: ImmutableZoneManager, events): """ Disarms the security system. """ partition = _get_partition(zm) if partition is None: raise ValueError('Missing security partition.') partition.disarm(events) def _get_partition(zm: ImmutableZoneManager) -> Union[AlarmPartition, None]: security_partitions = zm.get_devices_by_type(AlarmPartition) if len(security_partitions) > 0: return security_partitions[0] else: return None
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/security_manager.py
security_manager.py
import time def is_in_time_range(time_ranges_string, epoch_seconds=None): """ Determines if the current time is in the timeRange string. :param str time_ranges_string: one or multiple time range in 24-hour format.\ Example: '10-12', or '6-9, 7-7, 8:30 - 14:45', or '19 - 8' (wrap around) :param int epoch_seconds: seconds since epoch, optional :rtype: boolean :raise: ValueError if the time range string is invalid """ if time_ranges_string is None or 0 == len(time_ranges_string): raise ValueError('Must have at least one time range.') time_struct = time.localtime(epoch_seconds) hour = time_struct[3] minute = time_struct[4] for time_range in string_to_time_range_lists(time_ranges_string): start_hour, start_minute, end_hour, end_minute = time_range if start_hour <= end_hour: if hour < start_hour: continue else: # wrap around scenario pass if hour == start_hour and minute < start_minute: continue if end_minute == 0: if start_hour <= end_hour: if hour >= end_hour: continue else: # wrap around if (hour < start_hour or hour > 23) and (hour < 0 or hour > end_hour): continue else: # minutes are > 0 if hour > end_hour or minute > end_minute: continue return True return False def string_to_time_range_lists(time_ranges_string): """ Return a list of time ranges. Each list item is itself a list of 4 elements: startTime, startMinute, endTime, endMinute. :rtype: list :raise: ValueError if the time range string is invalid """ if time_ranges_string is None or 0 == len(time_ranges_string): raise ValueError('Must have at least one time range.') time_ranges = [] pairs = time_ranges_string.split(',') for pair in pairs: times = pair.split('-') if 1 == len(times): hour = int(times[0]) if hour < 0 or hour > 23: raise ValueError('Hour must be between 0 and 23 inclusive.') time_ranges.append([int(hour), 0, int(hour), 59]) elif 2 == len(times): this_range = [] def parse_hour_and_minute(time_string): hour_minute = time_string.split(':') inner_hour = int(hour_minute[0]) if inner_hour < 0 or inner_hour > 23: raise ValueError('Hour must be between 0 and 23 inclusive.') if 1 == len(hour_minute): return [int(inner_hour), 0] # 0 minute elif 2 == len(hour_minute): minute = int(hour_minute[1]) if minute < 0 or minute > 59: raise ValueError('Minute must be between 0 and 59 inclusive.') return [inner_hour, minute] else: raise ValueError('Must be in format "HH" or "HH:MM".') this_range += parse_hour_and_minute(times[0]) this_range += parse_hour_and_minute(times[1]) time_ranges.append(this_range) else: raise ValueError('Must have either one or two time values.') return time_ranges
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/time_utilities.py
time_utilities.py
import time from typing import List from zone_api.alert import Alert from zone_api import platform_encapsulator as pe from zone_api.core.devices.activity_times import ActivityTimes from zone_api.core.devices.chromecast_audio_sink import ChromeCastAudioSink _ADMIN_EMAIL_KEY = 'admin-email-address' _OWNER_EMAIL_KEY = 'owner-email-address' class AlertManager: """ Process an alert. The current implementation will send out an email. If the alert is at critical level, a TTS message will also be sent to all audio sinks. """ def __init__(self, properties_file='/etc/openhab/transform/owner-email-addresses.map'): self._properties_file = properties_file # If set, the TTS message won't be sent to the chrome casts. self._testMode = False # Used in unit testing to make sure that the email alert function was invoked, # without having to sent any actual email. self._lastEmailedSubject = None # Tracks the timestamp of the last alert in a module. self._moduleTimestamps = {} def process_alert(self, alert: Alert, zone_manager=None): """ Processes the provided alert. If the alert's level is WARNING or CRITICAL, the TTS subject will be played on the ChromeCasts. :param Alert alert: the alert to be processed :param ImmutableZoneManager zone_manager: used to retrieve the ActivityTimes :return: True if alert was processed; False otherwise. :raise: ValueError if alert is None """ if alert is None: raise ValueError('Invalid alert.') pe.log_info(f"Processing alert\n{str(alert)}") if self._is_throttled(alert): return False if not alert.is_audio_alert_only(): self._email_alert(alert, _get_owner_email_addresses(self._properties_file)) # Play an audio message if the alert is warning or critical. # Determine the volume based on the current zone activity. volume = 0 if alert.is_critical_level(): volume = 60 elif alert.is_warning_level(): if zone_manager is None: volume = 60 else: activities = zone_manager.get_devices_by_type(ActivityTimes) if len(activities) > 0: activity = activities[0] if activity.is_sleep_time(): volume = 0 elif activity.is_quiet_time(): volume = 40 else: volume = 60 else: volume = 50 if volume > 0: casts: List[ChromeCastAudioSink] = zone_manager.get_devices_by_type(ChromeCastAudioSink) for cast in casts: cast.play_message(alert.get_subject(), volume) return True def process_admin_alert(self, alert): """ Processes the provided alert by sending an email to the administrator. :param Alert alert: the alert to be processed :return: True if alert was processed; False otherwise. :raise: ValueError if alert is None """ if alert is None: raise ValueError('Invalid alert.') pe.log_info(f"Processing admin alert\n{str(alert)}") if self._is_throttled(alert): return False self._email_alert(alert, _get_admin_email_addresses(self._properties_file)) return True def reset(self): """ Reset the internal states of this class. """ self._lastEmailedSubject = None self._moduleTimestamps = {} def _is_throttled(self, alert): if alert.get_module() is not None: interval_in_seconds = alert.get_interval_between_alerts_in_minutes() * 60 if alert.get_module() in self._moduleTimestamps: previous_time = self._moduleTimestamps[alert.get_module()] if (time.time() - previous_time) < interval_in_seconds: return True self._moduleTimestamps[alert.get_module()] = time.time() return False def _email_alert(self, alert, default_email_addresses): email_addresses = alert.get_email_addresses() if not email_addresses: email_addresses = default_email_addresses if email_addresses is None or len(email_addresses) == 0: raise ValueError('Missing email addresses.') if not self._testMode: body = '' if alert.get_body() is None else alert.get_body() pe.send_email(email_addresses, alert.get_subject(), body, alert.get_attachment_urls()) self._lastEmailedSubject = alert.get_subject() self._lastEmailedBody = alert.get_body() def _set_test_mode(self, mode): """ Switches on/off the test mode. @param mode boolean """ self._testMode = mode def _load_properties(filepath, sep='=', comment_char='#'): """ Read the file passed as parameter as a properties file. @see https://stackoverflow.com/a/31852401 """ props = {} with open(filepath, "rt") as f: for line in f: line = line.strip() if line and not line.startswith(comment_char): key_value = line.split(sep) key = key_value[0].strip() value = sep.join(key_value[1:]).strip().strip('"') props[key] = value return props def _get_owner_email_addresses(file_name: str): """ :return: list of user email addresses """ props = _load_properties(file_name) emails = props[_OWNER_EMAIL_KEY].split(';') return emails def _get_admin_email_addresses(file_name: str): """ :return: list of administrator email addresses """ props = _load_properties(file_name) emails = props[_ADMIN_EMAIL_KEY].split(';') return emails
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/alert_manager.py
alert_manager.py
from HABApp.openhab.errors import ItemNotFoundError try: import HABApp except ImportError: from org.slf4j import Logger, LoggerFactory from org.eclipse.smarthome.core.types import UnDefType from org.eclipse.smarthome.core.library.types import DecimalType from org.eclipse.smarthome.core.library.items import StringItem from org.eclipse.smarthome.core.library.types import OnOffType from org.eclipse.smarthome.core.library.types import OpenClosedType from core.jsr223 import scope from core.testing import run_test logger = LoggerFactory.getLogger("org.eclipse.smarthome.model.script.Rules") _in_hab_app = False else: import logging from typing import Tuple, List, Union, Dict, Any from HABApp.core import Items from HABApp.core.items import Item from HABApp.openhab.items import ContactItem, DimmerItem, NumberItem, StringItem, SwitchItem, PlayerItem, \ OpenhabItem from HABApp.openhab.definitions import OnOffValue from HABApp.core.events import ValueChangeEvent _in_hab_app = True logger = logging.getLogger('ZoneApis') ACTION_AUDIO_SINK_ITEM_NAME = 'AudioVoiceSinkName' ACTION_TEXT_TO_SPEECH_MESSAGE_ITEM_NAME = 'TextToSpeechMessage' ACTION_AUDIO_LOCAL_FILE_LOCATION_ITEM_NAME = 'AudioFileLocation' ACTION_AUDIO_STREAM_URL_ITEM_NAME = 'AudioStreamUrl' """ The previous 4 items are used to play TTS message and audio file/URL. The corresponding script to process these actions are in JSR223 side, within OpenHab. """ ZONE_MANAGER_ITEM_NAME = "zone-manager" _in_unit_tests = False def is_in_hab_app() -> bool: return _in_hab_app def register_test_item(item: Item) -> None: """ Register the given item with the runtime. """ if is_in_hab_app(): HABApp.core.Items.add_item(item) else: scope.itemRegistry.remove(item.getName()) scope.itemRegistry.add(item) def unregister_test_item(item) -> None: """ Unregister the given item with the runtime. """ HABApp.core.Items.pop_item(item.name) def add_zone_manager_to_context(zm): """ Adds the zone manager instance to the context. :param ImmutableZoneManager zm: """ if is_in_hab_app(): if Items.item_exists(ZONE_MANAGER_ITEM_NAME): HABApp.core.Items.pop_item(ZONE_MANAGER_ITEM_NAME) item = OpenhabItem(ZONE_MANAGER_ITEM_NAME, zm) HABApp.core.Items.add_item(item) else: raise ValueError("Unsupported type op: add_zone_manager_to_context") def get_zone_manager_from_context(): """ Gets the zone manager from the context. :rtype ImmutableZoneManager: """ if is_in_hab_app(): item = OpenhabItem.get_item(ZONE_MANAGER_ITEM_NAME) return item.get_value() else: raise ValueError("Unsupported type op: add_zone_manager_to_context") def is_in_on_state(item: SwitchItem): """ :param SwitchItem item: :return: True if the state is ON. """ if isinstance(item, SwitchItem): return item.is_on() return False def is_in_open_state(item: ContactItem): """ :param SwitchItem item: :return: True if the state is OPEN. """ if isinstance(item, ContactItem): return item.is_open() return False def create_number_item(name: str) -> NumberItem: return NumberItem(name) def create_player_item(name: str) -> PlayerItem: return PlayerItem(name) def create_dimmer_item(name: str, percentage: int = 0) -> DimmerItem: """ :param name: the item name :param int percentage: 0 (OFF) to 100 (full brightness) :return: DimmerItem """ return DimmerItem(name, percentage) def create_switch_item(name: str, on=False) -> SwitchItem: """ :param name: the item name :param on: if True, the state is ON, else the state is OFF :return: SwitchItem """ return SwitchItem(name, OnOffValue.ON if on else OnOffValue.OFF) def create_string_item(name: str) -> StringItem: return StringItem(name) def set_switch_state(item_or_item_name: Union[SwitchItem, str], on: bool): """ Set the switch state for the given item or item name. """ if isinstance(item_or_item_name, str): item_or_item_name = SwitchItem.get_item(item_or_item_name) if is_in_unit_tests(): item_or_item_name.set_value(OnOffValue.ON if on else OnOffValue.OFF) else: if on: item_or_item_name.on() else: item_or_item_name.off() def set_dimmer_value(item: DimmerItem, percentage: int): if is_in_unit_tests(): item.post_value(percentage) else: item.percent(percentage) def get_dimmer_percentage(item: DimmerItem) -> int: return item.get_value(0) def set_number_value(item: NumberItem, value: float): if is_in_unit_tests(): item.post_value(value) else: item.oh_send_command(str(value)) def get_number_value(item_or_item_name: Union[NumberItem, DimmerItem, str]) -> float: if isinstance(item_or_item_name, str): item_or_item_name = NumberItem.get_item(item_or_item_name) return int(item_or_item_name.get_value(0)) def set_string_value(item: StringItem, value: str): if is_in_unit_tests(): item.post_value(value) else: item.oh_send_command(value) def get_string_value(item_or_item_name: Union[StringItem, str]) -> str: if isinstance(item_or_item_name, str): item_or_item_name = StringItem.get_item(item_or_item_name) return item_or_item_name.get_value() def change_player_state_to_pause(item: PlayerItem): if is_in_unit_tests(): item.set_value("PAUSE") else: item.oh_send_command("PAUSE") def change_player_state_to_play(item: PlayerItem): if is_in_unit_tests(): item.set_value("PLAY") else: item.oh_send_command("PLAY") def is_player_playing(item: PlayerItem): return item.get_value() == "PLAY" def has_item(item_name: str): """ Returns true if the item name is present in the back store. """ return Items.item_exists(item_name) def get_item_name(item): return item.name def register_value_change_event(item: Item, handler): item.listen_event(handler, ValueChangeEvent) def log_debug(message: str): """ Log a debug message. """ logger.debug(message) def log_info(message: str): """ Log an info message. """ logger.info(message) def log_error(message: str): """ Log an error message. """ logger.error(message) def log_warning(message: str): """ Log an warning message. """ logger.warning(message) def get_channel(item) -> str: """ Returns the OpenHab channel string linked with the item. :rtype: str the channel string or None if the item is not linked to a channel """ if _in_hab_app: if is_in_unit_tests(): return None else: try: item_def = HABApp.openhab.interface.get_item(item.name, "channel") metadata = item_def.metadata value = metadata.get("channel") return value['value'] if value is not None else None except ItemNotFoundError: return None else: from core import osgi from org.eclipse.smarthome.core.items import MetadataKey meta_registry = osgi.get_service("org.eclipse.smarthome.core.items.MetadataRegistry") channel_meta = meta_registry.get( MetadataKey('channel', item.getName())) if channel_meta is not None: return channel_meta.value else: return None def get_event_dispatcher(): if not is_in_unit_tests(): class EventDispatcher: # noinspection PyMethodMayBeStatic def send_command(self, item_name: str, command: Any): HABApp.openhab.interface.send_command(item_name, command) return EventDispatcher() else: class TestEventDispatcher: # noinspection PyMethodMayBeStatic def send_command(self, item_name: str, command: Any): item = Items.get_item(item_name) if isinstance(item, SwitchItem): item = SwitchItem.get_item(item_name) if command == "ON": item.post_value(OnOffValue.ON) elif command == "OFF": item.post_value(OnOffValue.OFF) elif isinstance(item, DimmerItem): item.post_value(int(command)) elif isinstance(item, NumberItem): item.post_value(command) else: log_error("type: {}".format(type(item))) raise ValueError("Unsupported type for item '{}'".format(item_name)) return TestEventDispatcher() def set_in_unit_tests(value: bool): global _in_unit_tests _in_unit_tests = value def is_in_unit_tests(): return _in_unit_tests def play_local_audio_file(sink_name: str, file_location: str): """ Plays a local audio file on the given audio sink. """ StringItem.get_item(ACTION_AUDIO_SINK_ITEM_NAME).oh_post_update(sink_name) StringItem.get_item(ACTION_AUDIO_LOCAL_FILE_LOCATION_ITEM_NAME).oh_post_update(file_location) def play_stream_url(sink_name: str, url: str): """ Plays a stream URL on the given audio sink. """ StringItem.get_item(ACTION_AUDIO_SINK_ITEM_NAME).oh_post_update(sink_name) StringItem.get_item(ACTION_AUDIO_STREAM_URL_ITEM_NAME).oh_post_update(url) def play_text_to_speech_message(sink_name: str, tts: str): """ Plays a text to speech message on the given audio sink. """ StringItem.get_item(ACTION_AUDIO_SINK_ITEM_NAME).oh_post_update(sink_name) StringItem.get_item(ACTION_TEXT_TO_SPEECH_MESSAGE_ITEM_NAME).oh_post_update(tts) def send_email(email_addresses: List[str], subject: str, body: str = '', attachment_urls: List[str] = None): """ Send an email using the OpenHab email action. """ if attachment_urls is None: attachment_urls = [] if body is None: body = '' StringItem.get_item('EmailSubject').oh_post_update(subject) StringItem.get_item('EmailBody').oh_post_update(body) StringItem.get_item('EmailAttachmentUrls').oh_post_update(', '.join(attachment_urls)) StringItem.get_item('EmailAddresses').oh_post_update(', '.join(email_addresses)) def change_ecobee_thermostat_hold_mode(mode: str): """ Change Ecobee thermostat to the specified mode via the Ecobee action in OpenHab. """ StringItem.get_item('EcobeeThermostatHoldMode').oh_post_update(mode) def resume_ecobee_thermostat_program(): """ Resume the Ecobee thermostat via the Ecobee action in OpenHab. """ SwitchItem.get_item('EcobeeThermostatResume').on()
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/platform_encapsulator.py
platform_encapsulator.py
from enum import Enum, unique import json @unique class AlertLevel(Enum): """ The alert levels. """ INFO = 1 """ INFO """ WARNING = 2 """ WARNING """ CRITICAL = 3 """ CRITICAL """ class Alert: """ Contains information about the alert. """ @classmethod def create_info_alert(cls, subject, body=None, attachment_urls=None, module=None, interval_between_alerts_in_minutes=-1): """ Creates an INFO alert. :param body: :param string subject: :param list(str) attachment_urls: list of URL attachment strings: :param string module: (optional) :param int interval_between_alerts_in_minutes: (optional) """ if attachment_urls is None: attachment_urls = [] return cls(AlertLevel.INFO, subject, body, attachment_urls, module, interval_between_alerts_in_minutes) @classmethod def create_warning_alert(cls, subject, body=None, attachment_urls=None, module=None, interval_between_alerts_in_minutes=-1): """ Creates a WARNING alert. :param body: :param string subject: :param list(str) attachment_urls: list of URL attachment strings: :param string module: (optional) :param int interval_between_alerts_in_minutes: (optional) """ if attachment_urls is None: attachment_urls = [] return cls(AlertLevel.WARNING, subject, body, attachment_urls, module, interval_between_alerts_in_minutes) @classmethod def create_audio_warning_alert(cls, subject, body=None, attachment_urls=None, module=None, interval_between_alerts_in_minutes=-1): """ Creates an audio-only WARNING alert. :param body: :param string subject: :param list(str) attachment_urls: list of URL attachment strings: :param string module: (optional) :param int interval_between_alerts_in_minutes: (optional) """ if attachment_urls is None: attachment_urls = [] return cls(AlertLevel.WARNING, subject, body, attachment_urls, module, interval_between_alerts_in_minutes, [], True) @classmethod def create_critical_alert(cls, subject, body=None, attachment_urls=None, module=None, interval_between_alerts_in_minutes=-1): """ Creates a CRITICAL alert. :param body: :param string subject: :param list(str) attachment_urls: list of URL attachment strings: :param string module: (optional) :param int interval_between_alerts_in_minutes: (optional) """ if attachment_urls is None: attachment_urls = [] return cls(AlertLevel.CRITICAL, subject, body, attachment_urls, module, interval_between_alerts_in_minutes) @classmethod def from_json(cls, json_string): """ Creates a new object from information in the json string. This method is used for alerts coming in from outside the jsr223 framework; they will be in JSON format. Accepted keys: subject, body, level ('info', 'warning', or 'critical'). :param str json_string: :raise: ValueError if jsonString contains invalid values """ # set strict to false to allow control characters in the json string obj = json.loads(json_string, strict=False) subject = obj.get('subject', None) if subject is None or '' == subject: raise ValueError('Missing subject value.') body = obj.get('body', None) level_mappings = { 'info': AlertLevel.INFO, 'warning': AlertLevel.WARNING, 'critical': AlertLevel.CRITICAL } level = AlertLevel.INFO if 'level' in obj: level = level_mappings.get(obj['level'], None) if level is None: raise ValueError('Invalid alert level.') module = obj.get('module', None) if '' == module: module = None interval_between_alerts_in_minutes = obj.get( 'intervalBetweenAlertsInMinutes', -1) if module is not None and interval_between_alerts_in_minutes <= 0: raise ValueError(f'Invalid interval_between_alerts_in_minutes value: {interval_between_alerts_in_minutes}') attachment_urls = [] email_addresses = obj.get('emailAddresses', None) return cls(level, subject, body, attachment_urls, module, interval_between_alerts_in_minutes, email_addresses) def __init__(self, level, subject, body=None, attachment_urls=None, module=None, interval_between_alerts_in_minutes=-1, email_addresses=None, audio_alert_only=False): if attachment_urls is None: attachment_urls = [] self.level = level self.subject = subject self.body = body self.attachment_urls = attachment_urls self.module = module self.interval_between_alerts_in_minutes = interval_between_alerts_in_minutes self.emailAddresses = email_addresses self.audioAlertOnly = audio_alert_only def get_subject(self): """ :rtype: str """ return self.subject def get_body(self): """ :rtype: str """ return self.body def get_attachment_urls(self): """ :rtype: list(str) """ return self.attachment_urls def get_module(self): """ Returns the alert module :rtype: str """ return self.module def get_email_addresses(self): """ Returns the overriding email addresses to be used instead of the default email addresses. :return: a list of email addresses; empty list if not specified :rtype: list(str) """ return [] if self.emailAddresses is None else self.emailAddresses.split(';') def get_interval_between_alerts_in_minutes(self): """ :rtype: int """ return self.interval_between_alerts_in_minutes def is_info_level(self): """ :rtype: bool """ return AlertLevel.INFO == self.level def is_warning_level(self): """ :rtype: bool """ return AlertLevel.WARNING == self.level def is_critical_level(self): """ :rtype: bool """ return AlertLevel.CRITICAL == self.level def is_audio_alert_only(self): """ :rtype: bool """ return self.audioAlertOnly def __str__(self): """ :return: a user readable string containing this object's info. """ return f'[{self.level.name}] {self.get_subject()}\n{self.get_body()}\n{str(self.get_attachment_urls())}'
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/alert.py
alert.py
import re import time from typing import Union, Tuple import requests class Forecast(object): """ Represent the weather forecast. """ def __init__(self, forecast_time: int, temperature: int, condition: str, precipitation_probability: str, wind: str): self._forecastTime = forecast_time self._temperature = temperature self._condition = condition self._precipitation_probability = precipitation_probability self._wind = wind def get_forecast_time(self): """ Return the hour in 24-hour format. :rtype: int """ return self._forecastTime def get_user_friendly_forecast_time(self): """ Returns the forecast hour in user friendly format (1AM, 2PM,...) :rtype: str """ hour = self._forecastTime if hour == 0: return 'Midnight' elif hour < 12: return str(hour) + ' AM' elif hour == 12: return 'Noon' else: return str(hour - 12) + ' PM' def get_temperature(self): """ Return the temperature in Celsius. :rtype: int """ return self._temperature def get_condition(self): """ Return the weather condition. :rtype: str """ return self._condition def get_precipitation_probability(self): """ Return the precipitation probability. Possible values: High (70%+), Medium (60% - 70%), Low (< 40%), or Nil (0%). :rtype: str """ return self._precipitation_probability def get_wind(self): """ Return the wind info such as "15 NW". :rtype: str """ return self._wind def __str__(self): """ :rtype: str """ value = u"{:5}: {:7} {:25} {:6} {:6}".format(self.get_forecast_time(), self.get_temperature(), self.get_condition(), self.get_precipitation_probability(), self.get_wind()) return value class EnvCanada(object): """ Utility class to retrieve the hourly forecast. """ CITY_FORECAST_MAPPING = {'ottawa': 'on-118'} """ Mapping from lowercase city name to the env canada identifier. """ CITY_ALERT_MAPPING = {'ottawa': 'on41'} @staticmethod def retrieve_hourly_forecast(city_or_url, hour_count=12): """ Retrieves the hourly forecast for the given city. :param str city_or_url: the city name or the Environment Canada website\ 'https://www.weather.gc.ca/forecast/hourly/on-118_metric_e.html' :param int hour_count: the # of forecast hour to get, starting from \ the next hour relative to the current time. :rtype: list(Forecast) :raise: ValueError if cityOrUrl points to an invalid city, or if \ hourCount is more than 24 and less than 1. """ if hour_count > 24 or hour_count < 1: raise ValueError("hourCount must be between 1 and 24.") if city_or_url[0:6].lower() != 'https:': normalized_city = city_or_url.lower() if normalized_city not in EnvCanada.CITY_FORECAST_MAPPING: raise ValueError( "Can't map city name to URL for {}".format(city_or_url)) url = 'https://www.weather.gc.ca/forecast/hourly/{}_metric_e.html'.format( EnvCanada.CITY_FORECAST_MAPPING[normalized_city]) else: url = city_or_url data = requests.get(url).text time_struct = time.localtime() hour_of_day = time_struct[3] pattern = r"""header2.*?\>(-?\d+)< # temp .*?<p>(.*?)</p> # condition .*?header4.*?>(.+?)< # precipitation probability .*?abbr.*?>(.+?)</abbr> (.*?)< # wind direction and speed """ forecasts = [] index = 0 for increment in range(1, hour_count + 1): hour = (hour_of_day + increment) % 24 hour_string = ("0" + str(hour)) if hour < 10 else str(hour) hour_string += ":00" search_string = '<td headers="header1" class="text-center">{}</td>'.format(hour_string) index = data.find(search_string, index) subdata = data[index:] match = re.search(pattern, subdata, re.MULTILINE | re.DOTALL | re.VERBOSE) if not match: raise ValueError("Invalid pattern.") temperature = int(match.group(1)) condition = match.group(2) precipitation_probability = match.group(3) wind = u'' + match.group(5) + ' ' + match.group(4) forecasts.append(Forecast(hour, temperature, condition, precipitation_probability, wind)) return forecasts @staticmethod def retrieve_alert(city_or_url: str) -> Union[Tuple[str, str, str], Tuple[None, str, str]]: """ Retrieves the weather alert for the given region. :return: a tuple containing the alert string (or None if there is no alert), the URL that was used to retrieve the data, and the raw data returned by the server. """ if city_or_url[0:6].lower() != 'https:': normalized_city = city_or_url.lower() if normalized_city not in EnvCanada.CITY_FORECAST_MAPPING: raise ValueError( "Can't map city name to URL for {}".format(city_or_url)) city_code = EnvCanada.CITY_ALERT_MAPPING[normalized_city] url = f'https://www.weather.gc.ca/warnings/report_e.html?{city_code}' else: url = city_or_url raw_data: str = requests.get(url).text data = raw_data start_keyword = "<div class=\"col-xs-12\">" start_idx = data.index(start_keyword) end_idx = data.index("<section class=\"followus hidden-print\">") data = data[start_idx + len(start_keyword): end_idx] data = data.replace("<br/>", "\n") data = data.replace("<br />", "\n") data = data.replace("<p>", "\n\n") data = re.sub("(?s)<[^>]*>(\\s*<[^>]*>)*", " ", data) data = data.strip() if 'No Alerts in effect.' in data: return None, url, raw_data else: return data, url, raw_data
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/environment_canada.py
environment_canada.py
import re from typing import Union, Dict, Any import HABApp from HABApp.core import Items from HABApp.core.events import ValueChangeEvent, ValueUpdateEvent from HABApp.core.items.base_item import BaseItem from HABApp.openhab.events import ItemCommandEvent from HABApp.openhab.events import ItemStateEvent from HABApp.openhab.items import ColorItem, DimmerItem, NumberItem, SwitchItem, StringItem from zone_api import platform_encapsulator as pe from zone_api.core.device import Device from zone_api.core.devices.alarm_partition import AlarmPartition, AlarmState from zone_api.core.devices.astro_sensor import AstroSensor from zone_api.core.devices.camera import Camera from zone_api.core.devices.chromecast_audio_sink import ChromeCastAudioSink from zone_api.core.devices.computer import Computer from zone_api.core.devices.contact import Door, GarageDoor, Window from zone_api.core.devices.dimmer import Dimmer from zone_api.core.devices.gas_sensor import GasSensor from zone_api.core.devices.humidity_sensor import HumiditySensor from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.devices.network_presence import NetworkPresence from zone_api.core.devices.plug import Plug from zone_api.core.devices.switch import Light, Fan from zone_api.core.devices.temperature_sensor import TemperatureSensor from zone_api.core.devices.thermostat import EcobeeThermostat from zone_api.core.devices.tv import Tv from zone_api.core.devices.water_leak_sensor import WaterLeakSensor from zone_api.core.devices.weather import Weather from zone_api.core.devices.wled import Wled from zone_api.core.immutable_zone_manager import ImmutableZoneManager from zone_api.core.zone_event import ZoneEvent """ This module contains a set of utility functions to create devices and their associated event handler. They are independent from the OpenHab naming convention but they are HABApp specific. """ def create_switches(zm: ImmutableZoneManager, item: Union[ColorItem, DimmerItem, NumberItem, SwitchItem]) \ -> Union[None, Dimmer, Light, Fan, Wled]: """ Parses and creates Dimmer, Fan or Light device. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem :return: Union[None, Dimmer, Light, Fan] """ device_name_pattern = '([^_]+)_([^_]+)_(.+)' # level_location_deviceName item_name = item.name illuminance_threshold_in_lux = 8 match = re.search(device_name_pattern, item_name) if not match: return None device_name = match.group(3) dimmable_key = 'dimmable' duration_in_minutes_key = 'durationInMinutes' disable_triggering_key = "disableTriggeringFromMotionSensor" item_def = HABApp.openhab.interface.get_item( item.name, f"noPrematureTurnOffTimeRange, {duration_in_minutes_key}, {dimmable_key}, {disable_triggering_key}") metadata = item_def.metadata if 'LightSwitch' == device_name or 'FanSwitch' == device_name or 'Wled_MasterControls' in device_name: duration_in_minutes = int(get_meta_value(metadata, duration_in_minutes_key, -1)) if duration_in_minutes == -1: raise ValueError(f"Missing durationInMinutes value for {item_name}'") else: duration_in_minutes = None device = None if 'LightSwitch' == device_name: no_premature_turn_off_time_range = get_meta_value(metadata, "noPrematureTurnOffTimeRange", None) if dimmable_key in metadata: config = metadata.get(dimmable_key).get('config') level = int(config.get('level')) time_ranges = config.get('timeRanges') device = Dimmer(item, duration_in_minutes, level, time_ranges, illuminance_threshold_in_lux, no_premature_turn_off_time_range) else: device = Light(item, duration_in_minutes, illuminance_threshold_in_lux, no_premature_turn_off_time_range) elif 'FanSwitch' == device_name: device = Fan(item, duration_in_minutes) elif 'Wled_MasterControls' in device_name: effect_item = Items.get_item(item.name.replace('MasterControls', 'FX')) primary_color_item = Items.get_item(item.name.replace('MasterControls', 'Primary')) secondary_color_item = Items.get_item(item.name.replace('MasterControls', 'Secondary')) device = Wled(item, effect_item, primary_color_item, secondary_color_item, duration_in_minutes) if device is not None: device = _configure_device(device, zm) def handler(event: ValueChangeEvent): is_on = False is_off = False if isinstance(item, SwitchItem): is_on = pe.is_in_on_state(item) is_off = not is_on elif isinstance(item, DimmerItem): is_off = pe.get_number_value(item) == 0 is_on = not is_off and event.old_value == 0 elif isinstance(item, ColorItem): was_on = (event.old_value[2] > 0) # index 2 for brightness was_off = int(event.old_value[2]) == 0 is_on = was_off and event.value[2] > 0 is_off = was_on and int(event.value[2]) == 0 if is_on: if not zm.on_switch_turned_on(pe.get_event_dispatcher(), device, item): pe.log_debug(f'Switch on event for {item.name} is not processed.') elif is_off: if not zm.on_switch_turned_off(pe.get_event_dispatcher(), device, item): pe.log_debug(f'Switch off event for {item.name} is not processed.') item.listen_event(handler, ValueChangeEvent) return device def create_alarm_partition(zm: ImmutableZoneManager, item: SwitchItem) -> AlarmPartition: """ Creates an alarm partition. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem :return: AlarmPartition """ arm_mode_item = Items.get_item(item.name + '_ArmMode') device = _configure_device(AlarmPartition(item, arm_mode_item), zm) def arm_mode_value_changed(event: ValueChangeEvent): if AlarmState.ARM_AWAY == AlarmState(int(event.value)): dispatch_event(zm, ZoneEvent.PARTITION_ARMED_AWAY, device, item) elif AlarmState.UNARMED == AlarmState(int(event.value)) \ and AlarmState.ARM_AWAY == AlarmState(int(event.old_value)): dispatch_event(zm, ZoneEvent.PARTITION_DISARMED_FROM_AWAY, device, item) def arm_mode_value_received(event: ItemCommandEvent): if AlarmState.ARM_AWAY == AlarmState(int(event.value)): dispatch_event(zm, ZoneEvent.PARTITION_RECEIVE_ARM_AWAY, device, arm_mode_item) elif AlarmState.ARM_STAY == AlarmState(int(event.value)): dispatch_event(zm, ZoneEvent.PARTITION_RECEIVE_ARM_STAY, device, arm_mode_item) # noinspection PyUnusedLocal def state_change_handler(event: ValueChangeEvent): dispatch_event(zm, ZoneEvent.PARTITION_IN_ALARM_STATE_CHANGED, device, item) arm_mode_item.listen_event(arm_mode_value_changed, ValueChangeEvent) arm_mode_item.listen_event(arm_mode_value_received, ValueUpdateEvent) item.listen_event(state_change_handler, ValueChangeEvent) # noinspection PyTypeChecker return device def create_chrome_cast(zm: ImmutableZoneManager, item: StringItem) -> ChromeCastAudioSink: item_def = HABApp.openhab.interface.get_item(item.name, "sinkName") metadata = item_def.metadata sink_name = get_meta_value(metadata, "sinkName", None) player_item = Items.get_item(item.name + "Player") volume_item = Items.get_item(item.name + "Volume") title_item = Items.get_item(item.name + "Title") idling_item = Items.get_item(item.name + "Idling") stream_title_name = item.name + "StreamTitle" stream_title_item = None if pe.has_item(stream_title_name): stream_title_item = Items.get_item(stream_title_name) device = _configure_device(ChromeCastAudioSink( sink_name, player_item, volume_item, title_item, idling_item, stream_title_item), zm) def player_command_event(event): event_map = {'NEXT': ZoneEvent.PLAYER_NEXT, 'PREVIOUS': ZoneEvent.PLAYER_PREVIOUS} if event.value in event_map.keys(): event = event_map[event.value] dispatch_event(zm, event, device, player_item) player_item.listen_event(player_command_event, ItemCommandEvent) # noinspection PyTypeChecker return device def get_meta_value(metadata: Dict[str, Any], key, default_value=None) -> str: """ Helper method to get the metadata value. """ value = metadata.get(key) if value is None: return default_value else: return value['value'] def get_zone_id_from_item_name(item_name: str) -> Union[str, None]: """ Extract and return the zone id from the the item name. """ pattern = '([^_]+)_([^_]+)_(.+)' match = re.search(pattern, item_name) if not match: return None level_string = match.group(1) location = match.group(2) return level_string + '_' + location def create_camera(zm: ImmutableZoneManager, item: StringItem) -> Camera: """ Creates a Camera. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem """ zone_name = get_zone_id_from_item_name(item.name) # noinspection PyTypeChecker return _configure_device(Camera(item, zone_name), zm) def create_motion_sensor(zm: ImmutableZoneManager, item) -> MotionSensor: """ Creates a MotionSensor and register for change event. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem :return: MotionSensor """ key_disable_triggering_switches = "disableTriggeringSwitches" item_def = HABApp.openhab.interface.get_item(item.name, f"{key_disable_triggering_switches}") metadata = item_def.metadata can_trigger_switches = False if "true" == get_meta_value(metadata, key_disable_triggering_switches) else True sensor = _configure_device(MotionSensor(item, True, can_trigger_switches), zm) # noinspection PyUnusedLocal def handler(event: ValueChangeEvent): if pe.is_in_on_state(item): dispatch_event(zm, ZoneEvent.MOTION, sensor, item) item.listen_event(handler, ValueChangeEvent) # noinspection PyTypeChecker return sensor def create_humidity_sensor(zm: ImmutableZoneManager, item) -> HumiditySensor: """ Creates a MotionSensor and register for change event. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem """ sensor = _configure_device(HumiditySensor(item), zm) # noinspection PyUnusedLocal def handler(event: ValueChangeEvent): dispatch_event(zm, ZoneEvent.HUMIDITY_CHANGED, sensor, item) item.listen_event(handler, ValueChangeEvent) # noinspection PyTypeChecker return sensor def create_network_presence_device(zm: ImmutableZoneManager, item) -> NetworkPresence: """ Creates a MotionSensor and register for change event. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem """ sensor = _configure_device(NetworkPresence(item), zm) # noinspection PyUnusedLocal def handler(event: ValueChangeEvent): if pe.is_in_on_state(item): zm.on_network_device_connected(pe.get_event_dispatcher(), sensor, item) item.listen_event(handler, ValueChangeEvent) # noinspection PyTypeChecker return sensor def create_temperature_sensor(zm: ImmutableZoneManager, item) -> TemperatureSensor: """ Creates a MotionSensor and register for change event. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem """ sensor = _configure_device(TemperatureSensor(item), zm) item.listen_event(lambda event: dispatch_event(zm, ZoneEvent.TEMPERATURE_CHANGED, sensor, item), ValueChangeEvent) # noinspection PyTypeChecker return sensor def create_plug(zm: ImmutableZoneManager, item) -> Plug: """ Creates a smart plug. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem :return: Plug """ power_item_name = item.name + '_Power' if Items.item_exists(power_item_name): power_item = Items.get_item(power_item_name) else: power_item = None item_def = HABApp.openhab.interface.get_item(item.name, "alwaysOn") metadata = item_def.metadata always_on = True if "true" == get_meta_value(metadata, "alwaysOn") else False # noinspection PyTypeChecker return _configure_device(Plug(item, power_item, always_on), zm) def create_gas_sensor(cls): """ :return: a function that create the specific gas sensor type. """ def inner_fcn(zm: ImmutableZoneManager, item) -> GasSensor: state_item = Items.get_item(item.name + 'State') sensor = _configure_device(cls(item, state_item), zm) # noinspection PyUnusedLocal def state_change_handler(event: ValueChangeEvent): dispatch_event(zm, ZoneEvent.GAS_TRIGGER_STATE_CHANGED, sensor, state_item) # noinspection PyUnusedLocal def value_change_handler(event: ValueChangeEvent): dispatch_event(zm, ZoneEvent.GAS_VALUE_CHANGED, sensor, item) item.listen_event(value_change_handler, ValueChangeEvent) state_item.listen_event(state_change_handler, ValueChangeEvent) # noinspection PyTypeChecker return sensor return inner_fcn def create_door(zm: ImmutableZoneManager, item) -> Door: if 'garage' in pe.get_item_name(item).lower(): sensor = GarageDoor(item) else: sensor = Door(item) sensor = _configure_device(sensor, zm) # noinspection PyUnusedLocal def handler(event: ValueChangeEvent): if pe.is_in_on_state(item) or pe.is_in_open_state(item): dispatch_event(zm, ZoneEvent.DOOR_OPEN, sensor, item) else: dispatch_event(zm, ZoneEvent.DOOR_CLOSED, sensor, item) item.listen_event(handler, ValueChangeEvent) # noinspection PyTypeChecker return sensor def create_window(zm: ImmutableZoneManager, item) -> Window: sensor = _configure_device(Window(item), zm) # noinspection PyUnusedLocal def handler(event: ValueChangeEvent): if pe.is_in_on_state(item) or pe.is_in_open_state(item): dispatch_event(zm, ZoneEvent.WINDOW_OPEN, sensor, item) else: dispatch_event(zm, ZoneEvent.WINDOW_CLOSED, sensor, item) item.listen_event(handler, ValueChangeEvent) # noinspection PyTypeChecker return sensor def create_water_leak_sensor(zm: ImmutableZoneManager, item) -> WaterLeakSensor: """ Creates a water leak sensor and register for change event. :param zm: the zone manager instance to dispatch the event. :param item: SwitchItem :return: WaterLeakSensor """ sensor = _configure_device(WaterLeakSensor(item), zm) item.listen_event(lambda event: dispatch_event(zm, ZoneEvent.WATER_LEAK_STATE_CHANGED, sensor, item), ValueChangeEvent) # noinspection PyTypeChecker return sensor def create_illuminance_sensor(zm: ImmutableZoneManager, item) -> IlluminanceSensor: """ Create an illuminance sensor. """ # noinspection PyTypeChecker return _configure_device(IlluminanceSensor(item), zm) def create_ecobee_thermostat(zm: ImmutableZoneManager, item) -> IlluminanceSensor: """ Create an Ecobee thermostat and set up the event listener to trap the vacation setting via the Ecobee application. If the OH switch item 'Out_Vacation' is present, set its value to the vacation mode setting. """ event_item_name = item.name.replace("EcobeeName", "FirstEvent_Type") event_item = Items.get_item(event_item_name) # noinspection PyTypeChecker device: EcobeeThermostat = _configure_device(EcobeeThermostat(item, event_item), zm) def handler(event: ValueChangeEvent): display_item_name = 'Out_Vacation' if device.is_in_vacation(): dispatch_event(zm, ZoneEvent.VACATION_MODE_ON, device, event_item) if pe.has_item(display_item_name): pe.set_switch_state(display_item_name, True) elif event.old_value == EcobeeThermostat.VACATION_EVENT_TYPE: dispatch_event(zm, ZoneEvent.VACATION_MODE_OFF, device, event_item) if pe.has_item(display_item_name): pe.set_switch_state(display_item_name, False) event_item.listen_event(handler, ValueChangeEvent) # noinspection PyTypeChecker return device def create_astro_sensor(zm: ImmutableZoneManager, item) -> AstroSensor: # noinspection PyTypeChecker device: AstroSensor = _configure_device(AstroSensor(item), zm) def handler(event: ValueChangeEvent): was_light_on_time = device.is_light_on_time(event.old_value) is_light_on_time = device.is_light_on_time(event.value) if was_light_on_time != is_light_on_time: if is_light_on_time: dispatch_event(zm, ZoneEvent.ASTRO_LIGHT_ON, device, item) else: dispatch_event(zm, ZoneEvent.ASTRO_LIGHT_OFF, device, item) if device.is_bed_time(event.value): dispatch_event(zm, ZoneEvent.ASTRO_BED_TIME, device, item) item.listen_event(handler, ValueChangeEvent) # noinspection PyTypeChecker return device def create_television_device(zm: ImmutableZoneManager, item) -> Tv: """ Create an television device. """ # noinspection PyTypeChecker return _configure_device(Tv(item), zm) def create_computer(zm: ImmutableZoneManager, item) -> Computer: """ Create an computer device. """ item_def = HABApp.openhab.interface.get_item(item.name, "name, alwaysOn") metadata = item_def.metadata name = get_meta_value(metadata, "name", None) always_on = True if get_meta_value(metadata, "alwaysOn", None) == "true" else False tmp_item_name = item.name + "_CpuTemperature" cpu_temperature_item = Items.get_item(tmp_item_name) if pe.has_item(tmp_item_name) else None tmp_item_name = item.name + "_GpuTemperature" gpu_temperature_item = Items.get_item(tmp_item_name) if pe.has_item(tmp_item_name) else None tmp_item_name = item.name + "_GpuFanSpeed" gpu_fan_speed_item = Items.get_item(tmp_item_name) if pe.has_item(tmp_item_name) else None device = _configure_device(Computer( name, cpu_temperature_item, gpu_temperature_item, gpu_fan_speed_item, always_on), zm) if cpu_temperature_item is not None: cpu_temperature_item.listen_event( lambda event: dispatch_event(zm, ZoneEvent.COMPUTER_CPU_TEMPERATURE_CHANGED, device, cpu_temperature_item), ValueChangeEvent) if gpu_temperature_item is not None: gpu_temperature_item.listen_event( lambda event: dispatch_event(zm, ZoneEvent.COMPUTER_GPU_TEMPERATURE_CHANGED, device, gpu_temperature_item), ValueChangeEvent) if gpu_fan_speed_item is not None: gpu_fan_speed_item.listen_event( lambda event: dispatch_event(zm, ZoneEvent.COMPUTER_GPU_FAN_SPEED_CHANGED, device, gpu_fan_speed_item), ValueChangeEvent) # noinspection PyTypeChecker return device def create_weather(zm: ImmutableZoneManager, temperature_item: NumberItem) -> Union[None, Weather]: """ Creates a weather device. :param zm: the zone manager instance to dispatch the event. :param temperature_item: the temperature weather item. """ device_name_pattern = '(.*)_Temperature' match = re.search(device_name_pattern, temperature_item.name) if not match: return None device_name = match.group(1) humidity_item = Items.get_item(f"{device_name}_Humidity") condition_item = Items.get_item(f"{device_name}_Condition") item_name = f"{device_name}_Alert_Title" alert_item = Items.get_item(item_name) if pe.has_item(item_name) else None item_name = f"{device_name}_ForecastTempMin" forecast_min_temp_item = Items.get_item(item_name) if pe.has_item(item_name) else None item_name = f"{device_name}_ForecastTempMax" forecast_max_temp_item = Items.get_item(item_name) if pe.has_item(item_name) else None device = Weather(temperature_item, humidity_item, condition_item, alert_item, forecast_min_temp_item, forecast_max_temp_item) device = _configure_device(device, zm) temperature_item.listen_event( lambda event: dispatch_event( zm, ZoneEvent.WEATHER_TEMPERATURE_CHANGED, device, temperature_item), ValueChangeEvent) humidity_item.listen_event( lambda event: dispatch_event( zm, ZoneEvent.WEATHER_HUMIDITY_CHANGED, device, humidity_item), ValueChangeEvent) condition_item.listen_event( lambda event: dispatch_event( zm, ZoneEvent.WEATHER_CONDITION_CHANGED, device, condition_item), ValueChangeEvent) alert_item.listen_event( lambda event: dispatch_event( zm, ZoneEvent.WEATHER_ALERT_CHANGED, device, alert_item), ValueChangeEvent) # noinspection PyTypeChecker return device def dispatch_event(zm: ImmutableZoneManager, zone_event: ZoneEvent, device: Device, item: BaseItem): """ Dispatches an event to the ZoneManager. If the event is not processed, create a debug log. """ # pe.log_info(f"Dispatching event {zone_event.name} for {item.name}") if not zm.dispatch_event(zone_event, pe.get_event_dispatcher(), device, item): pe.log_debug(f'Event {zone_event} for item {item.name} is not processed.') def _configure_device(device: Device, zm: ImmutableZoneManager) -> Device: """ - Set a few properties on the device. Note that each setter returns a new device instance, and as such, this method should be called before configuring the event handler. - Also register the item state event for each item in the device to update the last activated timestamp. """ device = device.set_channel(pe.get_channel(device.get_item())) device = device.set_zone_manager(zm) # Can't rely on item changed even to determine last activated time, as sometimes the device may send the same value # and that wouldn't trigger the item changed event. # However, we need to exclude a few sensor types that would falsely flag occupancy (occupancy determination is # based on the ON state in the last number of minutes). if not isinstance(device, MotionSensor) and not isinstance(device, NetworkPresence): for item in device.get_all_items(): item.listen_event(lambda event: device.update_last_activated_timestamp(), ItemStateEvent) return device
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/device_factory.py
device_factory.py
import re from typing import List, Dict, Type import pkgutil import inspect import importlib import HABApp from HABApp.core import Items from HABApp.core.items.base_item import BaseItem import zone_api.core.actions as actions from zone_api import platform_encapsulator as pe from zone_api import device_factory as df from zone_api.alert_manager import AlertManager from zone_api.core.action import Action from zone_api.core.devices.activity_times import ActivityTimes from zone_api.core.devices.gas_sensor import NaturalGasSensor, SmokeSensor, Co2GasSensor from zone_api.core.immutable_zone_manager import ImmutableZoneManager from zone_api.core.zone import Zone, Level from zone_api.core.zone_manager import ZoneManager from zone_api.core.neighbor import NeighborType, Neighbor """ This module contains functions to construct an ImmutableZoneManager using the following convention for the OpenHab items. 1. The zones are defined as a String item with this pattern Zone_{name}: String Zone_GreatRoom { level="FF", displayIcon="player", displayOrder="1", openSpaceSlaveNeighbors="FF_Kitchen" } - The levels are the reversed mapping of the enums in Zone::Level. - Here are the list of supported attributes: level, external, openSpaceNeighbors, openSpaceMasterNeighbors, openSpaceSlaveNeighbors, displayIcon, displayOrder. 2. The individual OpenHab items are named after this convention: {zone_id}_{device_type}_{device_name}. Here's an example: Switch FF_Office_LightSwitch "Office Light" (gWallSwitch, gLightSwitch, gFirstFloorLightSwitch) [shared-motion-sensor] { channel="zwave:device:9e4ce05e:node8:switch_binary", durationInMinutes="15" } """ def parse(activity_times: ActivityTimes, actions_package: str = "zone_api.core.actions", actions_path: List[str] = actions.__path__) -> ImmutableZoneManager: """ - Parses the zones and devices from the remote OpenHab items (via the REST API). - Adds devices to the zones. - Adds default actions to the zones. - For each action, invoke Action::on_startup method. - Start the scheduler service. :return: """ mappings = { '.*AlarmPartition$': df.create_alarm_partition, '.*_ChromeCast$': df.create_chrome_cast, '.*Door$': df.create_door, '[^g].*_Window$': df.create_window, '.*_Camera$': df.create_camera, '[^g].*MotionSensor$': df.create_motion_sensor, '[^g].*LightSwitch.*': df.create_switches, '.*FanSwitch.*': df.create_switches, '.*Wled_MasterControls.*': df.create_switches, '[^g].*_Illuminance.*': df.create_illuminance_sensor, '[^g](?!.*Weather).*Humidity$': df.create_humidity_sensor, '[^g].*_NetworkPresence.*': df.create_network_presence_device, '[^g].*_Plug$': df.create_plug, '[^g].*_Co2$': df.create_gas_sensor(Co2GasSensor), '[^g].*_NaturalGas$': df.create_gas_sensor(NaturalGasSensor), '[^g].*_Smoke$': df.create_gas_sensor(SmokeSensor), '.*_Tv$': df.create_television_device, '.*_Thermostat_EcobeeName$': df.create_ecobee_thermostat, # not matching "FF_Office_Computer_Dell_GpuTemperature" '[^g](?!.*Computer)(?!.*Weather).*Temperature$': df.create_temperature_sensor, '[^g].*WaterLeakState$': df.create_water_leak_sensor, '[^g].*_TimeOfDay$': df.create_astro_sensor, '.*_Computer_[^_]+$': df.create_computer, '.*_Weather_Temperature$': df.create_weather, } zm: ZoneManager = ZoneManager() immutable_zm = zm.get_immutable_instance() immutable_zm = immutable_zm.set_alert_manager(AlertManager()) zone_mappings = {} for zone in _parse_zones(): zone_mappings[zone.get_id()] = zone items: List[BaseItem] = Items.get_all_items() for item in items: for pattern in mappings.keys(): device = None if re.match(pattern, item.name) is not None: device = mappings[pattern](immutable_zm, item) if device is not None: zone_id = df.get_zone_id_from_item_name(item.name) if zone_id is None: pe.log_warning("Can't get zone id from item name '{}'".format(item.name)) continue if zone_id not in zone_mappings.keys(): pe.log_warning("Invalid zone id '{}'".format(zone_id)) continue zone = zone_mappings[zone_id].add_device(device) zone_mappings[zone_id] = zone # Add specific devices to the Virtual Zone zone = next((z for z in zone_mappings.values() if z.get_name() == 'Virtual'), None) if zone is not None: zone = zone.add_device(activity_times) zone_mappings[zone.get_id()] = zone action_classes = get_action_classes(actions_package, actions_path) zone_mappings = add_actions(zone_mappings, action_classes) for z in zone_mappings.values(): zm.add_zone(z) immutable_zm.start() return immutable_zm def _parse_zones() -> List[Zone]: """ Parses items with the zone pattern in the name and constructs the associated Zone objects. :return: List[Zone] """ pattern = 'Zone_([^_]+)' zones: List[Zone] = [] items = Items.get_all_items() for item in items: match = re.search(pattern, item.name) if not match: continue zone_name = match.group(1) item_def = HABApp.openhab.interface.get_item( item.name, "level, external, openSpaceNeighbors, openSpaceMasterNeighbors, openSpaceSlaveNeighbors, displayIcon, " "displayOrder") metadata = item_def.metadata level = Level(df.get_meta_value(metadata, "level")) external = df.get_meta_value(metadata, "external", False) display_icon = df.get_meta_value(metadata, "displayIcon", '') display_order = int(df.get_meta_value(metadata, "displayOrder", 9999)) zone = Zone(zone_name, [], level, [], {}, external, display_icon, display_order) neighbor_type_mappings = { 'closeSpaceNeighbors': NeighborType.CLOSED_SPACE, 'openSpaceNeighbors': NeighborType.OPEN_SPACE, 'openSpaceMasterNeighbors': NeighborType.OPEN_SPACE_MASTER, 'openSpaceSlaveNeighbors': NeighborType.OPEN_SPACE_SLAVE, } for neighbor_type_str in neighbor_type_mappings.keys(): neighbor_str = df.get_meta_value(metadata, neighbor_type_str) if neighbor_str is not None: for neighbor_id in neighbor_str.split(','): neighbor_id = neighbor_id.strip() neighbor = Neighbor(neighbor_id, neighbor_type_mappings[neighbor_type_str]) zone = zone.add_neighbor(neighbor) zones.append(zone) return zones def add_actions(zone_mappings: Dict, action_classes: List[Type]) -> Dict: """ Create action instances from action_classes and add them to the zones. A set of filters are applied to ensure that only the application actions are added to each zone. As the Zone class is immutable, a new Zone instance is created after adding an action. As such, a zone_mappings dictionary must be provided. :param str zone_mappings: mappings from zone_id string to a Zone instance. :param str action_classes: the list of action types. """ for clazz in action_classes: action: Action = clazz() for zone in zone_mappings.values(): if not _can_add_action_to_zone(zone, action): continue if action.must_be_unique_instance(): zone = zone.add_action(clazz()) else: zone = zone.add_action(action) zone_mappings[zone.get_id()] = zone return zone_mappings def _can_add_action_to_zone(zone: Zone, action: Action) -> bool: satisfied = True # must have all devices for device_type in action.get_required_devices(): if len(zone.get_devices_by_type(device_type)) == 0: satisfied = False break if not satisfied: return False if zone.is_internal() and not action.is_applicable_to_internal_zone(): return False if zone.is_external() and not action.is_applicable_to_external_zone(): return False if len(action.get_applicable_levels()) > 0 and (zone.get_level() not in action.get_applicable_levels()): return False zone_name_pattern = action.get_applicable_zone_name_pattern() if zone_name_pattern is not None: match = re.search(zone_name_pattern, zone.get_name()) if not match: return False return True def get_action_classes(actions_package: str = "zone_api.core.actions", actions_path: List[str] = actions.__path__) -> List[Type]: """ Retrieve a list of action class types defined in the actions_path with the given actions_package. To avoid loading the non-action classes (the package might contain helper modules), the following restrictions are used: 1. The normalized action name must be the same as the normalized module name. e.g. action 'ManagePlugs' is defined in the file 'manage_plugs.py'. 2. The class defined in the module must be an instance of 'Action'. :param str actions_package: the package of the action classes. :param str actions_path: the absolute path to the action classes. """ classes = [] for importer, module_name, is_pkg in pkgutil.iter_modules(actions_path): module = importlib.import_module(f"{actions_package}.{module_name}") for (name, value) in inspect.getmembers(module, lambda member: inspect.isclass(member)): normalized_module_name = module_name.replace('_', '').lower() if name.lower() == normalized_module_name: try: clazz = getattr(module, name) obj = clazz() if isinstance(obj, Action): classes.append(clazz) except AttributeError: pass except TypeError: pass return classes
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/zone_parser.py
zone_parser.py
import re from typing import Any from zone_api import platform_encapsulator as pe from zone_api.core.event_info import EventInfo from zone_api.core.zone_event import ZoneEvent class Action(object): """ The base class for all zone actions. An action is invoked when an event is triggered (e.g. when a motion sensor is turned on). An action may rely on the states of one or more sensors in the zone. Here is the action life cycle: 1. Object creation. 2. Action::on_startup is invoked with ZoneEvent::STARTUP. 3. Action::on_action is invoked when the specified event is triggered. 4. Action::on_destroy is invoked with ZoneEvent::DESTROY. """ def __init__(self): self._triggering_events = None self._external_events = None self._devices = None self._internal = None self._external = None self._levels = None self._unique_instance = False self._zone_name_pattern = None self._filtering_disabled = False self._priority = 10 # noinspection PyUnusedLocal,PyMethodMayBeStatic def on_action(self, event_info: EventInfo) -> bool: """ Invoked when an event is triggered. Subclass must override this method with its own handling. :param EventInfo event_info: :return: True if the event is processed; False otherwise. """ return True def on_startup(self, event_info: EventInfo): """ Invoked when the system has been fully initialized, and the action is ready to accept event. Action should perform any initialization actions such as starting the timer here. """ pass def on_destroy(self, event_info: EventInfo): """ Invoked when the system is about to be shutdown. Action should perform any necessary destruction such as cancelling the timer here. """ pass def get_containing_zone(self, zm): """ :param ImmutableZoneManager zm: :return: the first zone containing this action or None. :rtype: Zone """ for z in zm.get_zones(): if z.has_action(self): return z return None def create_timer_event_info(self, event_info: EventInfo, custom_parameter: Any = None): """ Helper method to return the TIMER event info. """ return EventInfo(ZoneEvent.TIMER, self.get_containing_zone(event_info.get_zone_manager()), event_info.get_zone(), event_info.get_zone_manager(), event_info.get_event_dispatcher(), None, None, custom_parameter) def get_required_devices(self): """ :return: list of devices that would generate the events :rtype: list(Device) """ return self._devices def get_required_events(self): """ :return: list of triggering events this action processes. External events aren't filtered through the normal mechanism as they come from different zones. :rtype: list(ZoneEvent) """ return self._triggering_events def get_external_events(self): """ :return: list of external events that this action processes. """ return self._external_events def is_applicable_to_internal_zone(self): """ :return: true if the action can be invoked on an internal zone. :rtype: bool """ return self._internal def is_applicable_to_external_zone(self): """ :return: true if the action can be invoked on an external zone. :rtype: bool """ return self._external def get_applicable_levels(self): """ :return: list of applicable zone levels :rtype: list(int) """ return self._levels def get_applicable_zone_name_pattern(self): """ :return: the zone name pattern that is applicable for this action. :rtype: str """ return self._zone_name_pattern def must_be_unique_instance(self): """ Returns true if the action must be an unique instance for each zone. This must be the case when the action is stateful. """ return self._unique_instance def is_filtering_disabled(self): """ Returns true if no filtering shall be performed before the action is invoked. """ return self._filtering_disabled def get_priority(self) -> int: """ Returns the specified priority order. Actions with lower order value is executed first. """ return self._priority def disable_filtering(self): self._filtering_disabled = True return self def log_info(self, message: str): """ Log an info message with the action name prefix. """ pe.log_info(f"{self.__class__.__name__}: {message}") def log_warning(self, message: str): """ Log a warning with the action name prefix. """ pe.log_warning(f"{self.__class__.__name__}: {message}") def log_error(self, message: str): """ Log an error message with the action name prefix. """ pe.log_error(f"{self.__class__.__name__}: {message}") def action(devices=None, events=None, internal=True, external=False, levels=None, unique_instance=False, zone_name_pattern: str = None, external_events=None, priority: int = 10): """ A decorator that accepts an action class and do the followings: - Create a subclass that extends the decorated class and Action. - Wrap the Action::on_action to perform various validations before invoking on_action. :param list(Device) devices: the list of devices the zone must have in order to invoke the action. :param list(ZoneEvent) events: the list of events for which the action will response to. :param boolean internal: if set, this action is only applicable for internal zone :param boolean external: if set, this action is only applicable for external zone :param list(int) levels: the zone levels that this action is applicable to. the empty list default value indicates that the action is applicable to all zone levels. :param boolean unique_instance: if set, do not share the same action instance across zones. This is the case when the action is stateful. :param str zone_name_pattern: if set, the zone name regular expression that is applicable to this action. :param list(ZoneEvent) external_events: the list of events from other zones that this action processes. These events won't be filtered using the same mechanism as the internal events as they come from other zones. :param int priority: the action priority with respect to other actions within the same zone. Actions with lower priority values are executed first. """ if levels is None: levels = [] if events is None: events = [] if external_events is None: external_events = [] if devices is None: devices = [] def action_decorator(clazz): def init(self, *args, **kwargs): clazz.__init__(self, *args, **kwargs) self._triggering_events = events self._devices = devices self._internal = internal self._external = external self._levels = levels self._unique_instance = unique_instance self._zone_name_pattern = zone_name_pattern self._external_events = external_events self._filtering_disabled = False self._priority = priority subclass = type(clazz.__name__, (clazz, Action), dict(__init__=init)) subclass.on_action = validate(clazz.on_action) return subclass return action_decorator def validate(function): """ Returns a function that validates the followings: - The generated event matched the action's applicable events. - The zone contains the expected device. - The zone's internal or external attributes matches the action's specification. - The zone's level matches the action's specification. """ def wrapper(*args, **kwargs): obj = args[0] event_info = args[1] zone = event_info.get_zone() if obj.is_filtering_disabled() or event_info.get_event_type() == ZoneEvent.TIMER: return function(*args, **kwargs) if zone.contains_open_hab_item(event_info.get_item()): if len(obj.get_required_events()) > 0 \ and not any(e == event_info.get_event_type() for e in obj.get_required_events()): return False elif len(obj.get_required_devices()) > 0 \ and not any(len(zone.get_devices_by_type(cls)) > 0 for cls in obj.get_required_devices()): return False elif zone.is_internal() and not obj.is_applicable_to_internal_zone(): return False elif zone.is_external() and not obj.is_applicable_to_external_zone(): return False elif len(obj.get_applicable_levels()) > 0 \ and not any(zone.get_level() == level for level in obj.get_applicable_levels()): return False elif obj.get_applicable_zone_name_pattern() is not None: pattern = obj.get_applicable_zone_name_pattern() match = re.search(pattern, zone.get_name()) if not match: return False else: # event from other zones if event_info.get_event_type() not in obj.get_external_events(): return False return function(*args, **kwargs) return wrapper
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/action.py
action.py
from enum import unique, Enum @unique class ZoneEvent(Enum): """ An enum of triggering zone events. """ UNDEFINED = -1 # Undefined MOTION = 1 # A motion triggered event SWITCH_TURNED_ON = 2 # A switch turned-on event SWITCH_TURNED_OFF = 3 # A switch turned-on event CONTACT_OPEN = 4 # A contact (doors/windows) is open CONTACT_CLOSED = 5 # A contact (doors/windows) is close DOOR_OPEN = 6 # A door is open DOOR_CLOSED = 7 # A door is close WINDOW_OPEN = 8 # A window is open WINDOW_CLOSED = 9 # A window is close PARTITION_ARMED_AWAY = 10 # Changed to armed away PARTITION_ARMED_STAY = 11 # Changed to armed stay PARTITION_RECEIVE_ARM_AWAY = 12 # Changed to armed away PARTITION_RECEIVE_ARM_STAY = 13 # Changed to armed stay PARTITION_DISARMED_FROM_AWAY = 14 # Changed from armed away to disarm PARTITION_DISARMED_FROM_STAY = 15 # Changed from armed stay to disarm PARTITION_IN_ALARM_STATE_CHANGED = 16 # The partition is either in alarm or no longer in alarm. HUMIDITY_CHANGED = 17 # The humidity percentage changed TEMPERATURE_CHANGED = 18 # The temperature changed GAS_TRIGGER_STATE_CHANGED = 19 # The gas sensor triggering boolean changed GAS_VALUE_CHANGED = 20 # The gas sensor value changed WATER_LEAK_STATE_CHANGED = 21 # The water leak sensor state changed PLAYER_PAUSE = 40 PLAYER_PLAY = 41 PLAYER_NEXT = 42 PLAYER_PREVIOUS = 43 COMPUTER_CPU_TEMPERATURE_CHANGED = 45 COMPUTER_GPU_TEMPERATURE_CHANGED = 46 COMPUTER_GPU_FAN_SPEED_CHANGED = 47 WEATHER_TEMPERATURE_CHANGED = 50 WEATHER_HUMIDITY_CHANGED = 51 WEATHER_CONDITION_CHANGED = 52 WEATHER_ALERT_CHANGED = 53 ASTRO_LIGHT_ON = 80 # Indicates that it is getting dark and the light should be turn on. ASTRO_LIGHT_OFF = 81 # Indicates that the time period transitions to day time. ASTRO_BED_TIME = 82 # Indicates that the time period transitions to bed time. VACATION_MODE_ON = 83 VACATION_MODE_OFF = 84 TIMER = 98 # A timer event is triggered. STARTUP = 99 # action startup event DESTROY = 100 # action destroy event
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/zone_event.py
zone_event.py
import threading import time from typing import Type, List from schedule import Scheduler from zone_api import platform_encapsulator as pe from zone_api.alert_manager import AlertManager from zone_api.core.devices.astro_sensor import AstroSensor from zone_api.core.devices.vacation import Vacation from zone_api.core.zone import Zone from zone_api.core.zone_event import ZoneEvent from zone_api.core.device import Device class ImmutableZoneManager: """ Similar to ZoneManager, but this class contains read-only methods. Instances of this class is passed to the method Action#on_action. Provide the follow common services: - Alert processing. - Scheduler. Instance of this class has life cycle: - start() should be called first to indicate that the zones have been fully populated (outside the scope of the class). - stop() should be called when the object is no longer used. """ def __init__(self, get_zones_fcn, get_zone_by_id_fcn, get_devices_by_type_fcn, alert_manager: AlertManager = None): self.get_zones_fcn = get_zones_fcn self.get_zone_by_id_fcn = get_zone_by_id_fcn self.get_devices_by_type_fcn = get_devices_by_type_fcn self.alert_manager = alert_manager self.scheduler = Scheduler() # noinspection PyTypeChecker self.cease_continuous_run: threading.Event = None # map from primary item name to zone for quick look-up. self.item_name_to_zone = {} self.fully_initialized = False def start(self): """ Indicates that the zones are fully populated. The following actions will take place: 1. Map device item name to zone. 2. Start scheduler (if not in a unit test). 3. Send event ZoneEvent.STARTUP to each action. """ for z in self.get_zones(): for d in z.get_devices(): self.item_name_to_zone[d.get_item_name()] = z if not pe.is_in_unit_tests(): self._start_scheduler() self.fully_initialized = True for z in self.get_zones(): z.dispatch_event(ZoneEvent.STARTUP, pe.get_event_dispatcher(), None, None, self) def stop(self): """ Indicates that this object is no longer being used. """ self._cancel_scheduler() self.fully_initialized = False def set_alert_manager(self, alert_manager: AlertManager): """ Sets the alert manager and returns a new instance of this class. """ params = {'get_zones_fcn': self.get_zones_fcn, 'get_zone_by_id_fcn': self.get_zone_by_id_fcn, 'get_devices_by_type_fcn': self.get_devices_by_type_fcn, 'alert_manager': alert_manager} return ImmutableZoneManager(**params) def get_alert_manager(self) -> AlertManager: return self.alert_manager def get_scheduler(self) -> Scheduler: """ Returns the Scheduler instance """ return self.scheduler def _start_scheduler(self, interval_in_seconds=1) -> threading.Event: """ Runs the scheduler in a separate thread. """ class ScheduleThread(threading.Thread): @classmethod def run(cls): while not self.cease_continuous_run.is_set(): self.scheduler.run_pending() time.sleep(interval_in_seconds) pe.log_info("Cancelled the scheduler service.") if self.cease_continuous_run is None: self.cease_continuous_run = threading.Event() continuous_thread = ScheduleThread() continuous_thread.start() pe.log_info("Started the scheduler service.") return self.cease_continuous_run def _cancel_scheduler(self): """ Cancel the scheduler thread if it was started. """ if self.cease_continuous_run is not None: self.cease_continuous_run.set() def get_containing_zone(self, device): """ Returns the first zone containing the device or None if the device does not belong to a zone. :param Device device: the device :rtype: Zone or None """ if device is None: raise ValueError('device must not be None') for zone in self.get_zones(): if zone.has_device(device): return zone return None def get_zones(self) -> List[Zone]: """ Returns a new list contains all zone. :rtype: list(Zone) """ return self.get_zones_fcn() def get_zone_by_id(self, zone_id): """ Returns the zone associated with the given zone_id. :param string zone_id: the value returned by Zone::get_id() :return: the associated zone or None if the zone_id is not found :rtype: Zone """ return self.get_zone_by_id_fcn(zone_id) def get_zone_by_item_name(self, item_name): """ Returns the zone associated with the given item_name. :param str item_name: :return: the associated zone or None if the item_name is not found :rtype: Zone """ return self.item_name_to_zone[item_name] if item_name in self.item_name_to_zone.keys() else None def get_devices_by_type(self, cls: Type): """ Returns a list of devices in all zones matching the given type. :param Device cls: the device type :rtype: list(Device) """ return self.get_devices_by_type_fcn(cls) def is_in_vacation(self): """ Returns true if at least one device indicates that the house is in vacation mode, vie Vacation class. """ for z in self.get_zones(): for d in z.get_devices_by_type(Vacation): if d.is_in_vacation(): return True return False def is_light_on_time(self): """ Returns True if it is light-on time; returns false if it is no. Returns None if there is no AstroSensor to determine the time. :rtype: bool or None """ has_astro_sensors = False for z in self.get_zones(): astro_sensors = z.get_devices_by_type(AstroSensor) if len(astro_sensors) > 0: has_astro_sensors = True value = any(s.is_light_on_time() for s in astro_sensors) if value: return True if not has_astro_sensors: return None else: return False def get_first_device_by_type(self, cls: type): """ Returns the first device matching the given type, or None if there is no device. :param type cls: the device type """ devices = self.get_devices_by_type(cls) return devices[0] if len(devices) > 0 else None def dispatch_event(self, zone_event: ZoneEvent, open_hab_events, device: Device, item): """ Dispatches the event to the zones. :param Device device: the device containing the triggered item; a device may contain multiple items. :param Any item: the triggered item. :param ZoneEvent zone_event: :param events open_hab_events: """ # noinspection PyProtectedMember device.update_last_activated_timestamp() return_values = [] # Small optimization: dispatch directly to the applicable zone first if we can determine # the zone id from the item name. owning_zone: Zone = self.get_zone_by_item_name(pe.get_item_name(item)) if owning_zone is not None: value = owning_zone.dispatch_event(zone_event, open_hab_events, device, item, self, owning_zone) return_values.append(value) # Then continue to dispatch to other zones even if a priority zone has been dispatched to. # This allows action to process events from other zones. for z in self.get_zones(): if z is not owning_zone: value = z.dispatch_event(zone_event, open_hab_events, device, item, self, owning_zone) return_values.append(value) return any(return_values) # noinspection PyUnusedLocal,PyMethodMayBeStatic def on_network_device_connected(self, events, device, item): """ Dispatches the network device connected (to local network) to each zone. :return: True if at least one zone processed the event; False otherwise :rtype: bool """ # noinspection PyProtectedMember device.update_last_activated_timestamp() return True def on_switch_turned_on(self, events, device, item): """ Dispatches the switch turned on event to each zone. :return: True if at least one zone processed the event; False otherwise :rtype: bool """ # noinspection PyProtectedMember device.update_last_activated_timestamp() return_values = [z.on_switch_turned_on(events, item, self) for z in self.get_zones()] return any(return_values) # noinspection PyUnusedLocal def on_switch_turned_off(self, events, device, item): """ Dispatches the switch turned off event to each zone. :return: True if at least one zone processed the event; False otherwise :rtype: bool """ return_values = [] for z in self.get_zones(): return_values.append(z.on_switch_turned_off(events, item, self)) return any(return_values) def __str__(self): value = u"" for z in self.get_zones(): value = f"{value}\n{str(z)}" return value
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/immutable_zone_manager.py
immutable_zone_manager.py
import datetime from copy import copy import time from zone_api import platform_encapsulator as pe class Device(object): """ The base class that all other sensors and switches derive from. """ def __init__(self, openhab_item, additional_items=None, battery_powered=False, wifi=False, auto_report=False): """ Ctor :param Item openhab_item: :param bool battery_powered: indicates if the device is powered by battery. :param bool wifi: indicates if the device communicates by WiFi. :param bool auto_report: indicates if the device periodically reports its value. :raise ValueError: if any parameter is invalid """ if additional_items is None: additional_items = [] if openhab_item is None: raise ValueError('openhabItem must not be None') self.item = openhab_item self.battery_powered = battery_powered self.wifi = wifi self.auto_report = auto_report self.last_activated_timestamp = None self.zone_manager = None self.channel = None self._additional_items = [i for i in additional_items if i is not None] def contains_item(self, item): """ Returns true if this device contains the specified item. """ their_name = pe.get_item_name(item) for item in self.get_all_items(): if pe.get_item_name(item) == their_name: return True return False def get_item(self): """ Returns the backed OpenHab item. :rtype: Item """ return self.item def get_item_name(self): """ Returns the backed OpenHab item name. :rtype: str """ return pe.get_item_name(self.item) def get_all_items(self): """ Return a list of all items in this device. """ return [self.item] + self._additional_items def set_channel(self, channel: str): """ Set the OpenHab channel string (configured in the item metadata). :return: A NEW object with the additional newly set channel. """ new_obj = copy(self) new_obj.channel = channel return new_obj def get_channel(self) -> str: """ Returns the OpenHab channel string linked with the item. :rtype: str the channel string or None if the item is not linked to a channel """ return self.channel def set_battery_powered(self, bool_value): """ :return: A NEW object with the batteryPowered attribute set to the specified value """ new_obj = copy(self) new_obj.battery_powered = bool_value return new_obj def is_battery_powered(self): """ Returns True if the device is powered by a batter; False otherwise. :rtype: Boolean """ return self.battery_powered def set_use_wifi(self, bool_value): """ :return: A NEW object with the wifi attribute set to the specified value """ new_obj = copy(self) new_obj.wifi = bool_value return new_obj def use_wifi(self): """ Returns True if the device communicates using WiFi. :rtype: Boolean """ return self.wifi def set_auto_report(self, bool_value): """ :return: A NEW object with the autoReport attribute set to the specified value. """ new_obj = copy(self) new_obj.auto_report = bool_value return new_obj def is_auto_report(self): """ Returns True if the device periodically sends its value. :rtype: Boolean """ return self.auto_report def set_zone_manager(self, zone_manager): """ :return: A NEW object with the zoneManager attribute set to the specified value. """ new_obj = copy(self) new_obj.zone_manager = zone_manager return new_obj def get_zone_manager(self): """ Returns the zone the device belong to or None if the device does not belong to any zone. :rtype: Zone """ return self.zone_manager def is_occupied(self, seconds_from_last_event=5 * 60): """ Returns boolean indicating if the present state of the device might indicate that the zone is occupied. :rtype: bool """ return False def get_last_activated_timestamp(self): """ Returns the timestamp in epoch seconds of the last event generated by the device. :rtype: int the last activated epoch second or None if not no event has been generated. """ return self.last_activated_timestamp def reset_value_states(self): """ Reset the underlying OpenHab item state. This method can be used when the physical device mal-functions and no longer sends the value update. A watch dog process can determine that the device is offline and invoke this method to reset the states. Devices that have more than one underlying OpenHab values must override this method. """ pass def was_recently_activated(self, seconds) -> bool: """ :param int seconds: the past duration (from the current time) to determine if the device was activated. :rtype: bool True if the device was activated during the specified seconds; False otherwise. """ prev_timestamp = self.get_last_activated_timestamp() if prev_timestamp is None: return False else: return (time.time() - prev_timestamp) <= seconds def update_last_activated_timestamp(self): """ Set the lastActivatedTimestamp field to the current epoch second. """ self.last_activated_timestamp = time.time() def __str__(self): value = u"{}: {}".format(self.__class__.__name__, self.get_item_name()) if self.is_battery_powered(): value += ", battery powered" if self.use_wifi(): value += ", wifi" if self.is_auto_report(): value += ", auto report" if self.last_activated_timestamp is not None: diff_in_seconds = time.time() - self.last_activated_timestamp value += ", last activated: {} ({})".format(self.last_activated_timestamp, str(datetime.timedelta(seconds=diff_in_seconds))) return value
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/device.py
device.py
from enum import Enum, unique from typing import List, Union from zone_api.core.action import Action from zone_api.core.event_info import EventInfo from zone_api.core.device import Device from zone_api.core.devices.illuminance_sensor import IlluminanceSensor from zone_api.core.devices.switch import Light, Switch from zone_api.core.neighbor import Neighbor from zone_api import platform_encapsulator as pe from zone_api.core.zone_event import ZoneEvent @unique class Level(Enum): """ An enum of the vertical levels.""" UNDEFINED = "UD" #: Undefined BASEMENT = "BM" #: The basement FIRST_FLOOR = "FF" #: The first floor SECOND_FLOOR = "SF" #: The second floor THIRD_FLOOR = "TF" #: The third floor VIRTUAL = "VT" #: The third floor class Zone: """ Represent a zone such as a room, foyer, porch, or lobby. Each zone holds a number of devices/sensors such as switches, motion sensors, or temperature sensors. A zone might have zero, one or multiple adjacent zones. The adjacent zones can be further classified into closed space (i.e. a wall exists between the two zones, open space, open space slave (the neighbor is a less important zone), and open space master. This layout-like structure is useful for certain scenario such as light control. Each zone instance is IMMUTABLE. The various add/remove methods return a new Zone object. Note however that the OpenHab item underlying each device/sensor is not (the state changes). See :meth:`add_device`, :meth:`remove_device`, :meth:`add_neighbor()` The zone itself doesn't know how to operate a device/sensor. The sensors themselves (all sensors derive from Device class) exposes the possible operations. Generally, the zone needs not know about the exact types of sensors it contains. However, controlling the light is a very common case for home automation; thus it does references to several virtual/physical sensors to determine the astro time, the illuminance, and the motion sensor. See :meth:`get_devices()`, :meth:`get_devices_by_type()`. There are two sets of operation on each zone: 1. Active operations such as turn on a light/fan in a zone. These are\ represented by common functions such as #turnOnLights(),\ #turnOffLights(); and 2. Passive operations triggered by events such onTimerExpired(),\ onSwitchTurnedOn(), and so on. The passive triggering is needed because the interaction with the devices or sensors might happen outside the interface exposed by this class. It could be a manually action on the switch by the user, or a direct send command through the OpenHab event bus. All the onXxx methods accept two parameters: the core.jsr223.scope.events object and the string itemName. The zone will perform appropriate actions for each of these events. For example, a motion event will turn on the light if it is dark or if it is evening time; a timer expiry event will turn off the associated light if it is currently on. @Immutable (the Zone object only) """ @classmethod def create_second_floor_zone(cls, name): """ Creates an internal second floor zone with the given name. :rtype: Zone """ params = {'name': name, 'level': Level.SECOND_FLOOR} return Zone(**params) @classmethod def create_first_floor_zone(cls, name): """ Creates an internal first floor zone with the given name. :rtype: Zone """ params = {'name': name, 'level': Level.FIRST_FLOOR} return Zone(**params) @classmethod def create_external_zone(cls, name, level=Level.FIRST_FLOOR): """ Creates an external zone with the given name. :rtype: Zone """ params = {'name': name, 'level': level, 'external': True} return Zone(**params) def __init__(self, name, devices: List[Device] = None, level=Level.UNDEFINED, neighbors: List[Neighbor] = None, actions=None, external=False, display_icon=None, display_order=9999): """ Creates a new zone. :param str name: the zone name :param list(Device) devices: the list of Device objects :param zone.Level level: the zone's physical level :param list(Neighbor) neighbors: the list of optional neighbor zones. :param dict(ZoneEvent -> list(Action)) actions: the optional \ dictionary from :class:`.ZoneEvent` to :class:`.Action` :param Bool external: indicates if the zone is external :param str display_icon: the icon associated with the zone, useful for displaying in sitemap. :param int display_order: the order with respective to the other zones, useful for arranging in sitemap. """ if actions is None: actions = {} if devices is None: devices = [] if neighbors is None: neighbors = [] self.name = name self.level = level self.devices = [d for d in devices] self.neighbors = list(neighbors) # type : List[Neighbor] self.actions = dict(actions) # shallow copy self.external = external self.displayIcon = display_icon self.displayOrder = display_order def add_device(self, device): """ Creates a new zone that is an exact copy of this one, but has the additional device. :return: A NEW object. :rtype: Zone :raise ValueError: if device is None or is not a subclass of :class:`.Device` """ if device is None: raise ValueError('device must not be None') if not isinstance(device, Device): raise ValueError('device must be an instance of Device') new_devices = list(self.devices) new_devices.append(device) params = self._create_ctor_param_dictionary('devices', new_devices) return Zone(**params) def remove_device(self, device): """ Creates a new zone that is an exact copy of this one less the given device :return: A NEW object. :rtype: Zone :raise ValueError: if device is None or is not a subclass of :class:`.Device` """ if device is None: raise ValueError('device must not be None') if not isinstance(device, Device): raise ValueError('device must be an instance of Device') new_devices = list(self.devices) new_devices.remove(device) params = self._create_ctor_param_dictionary('devices', new_devices) return Zone(**params) def has_device(self, device): """ Determine if the zone contains the specified device. :rtype: Boolean """ return device in self.devices def get_devices(self): """ Returns a copy of the list of devices. :rtype: list(Device) """ return [d for d in self.devices] def get_devices_by_type(self, cls: type): """ Returns a list of devices matching the given type. :param type cls: the device type :rtype: list(Device) """ if cls is None: raise ValueError('cls must not be None') return [d for d in self.devices if isinstance(d, cls)] def get_first_device_by_type(self, cls: type): """ Returns the first device matching the given type, or None if there is no device. :param type cls: the device type :rtype: Device or None """ devices = self.get_devices_by_type(cls) return devices[0] if len(devices) > 0 else None def get_device_by_event(self, event_info): """ Returns the device that generates the provided event. :param EventInfo event_info: :rtype: Device """ if event_info is None: raise ValueError('eventInfo must not be None') return next((d for d in self.devices if d.contains_item(event_info.get_item())), None) def add_neighbor(self, neighbor): """ Creates a new zone that is an exact copy of this one, but has the additional neighbor. :return: A NEW object. :rtype: Zone """ if neighbor is None: raise ValueError('neighbor must not be None') new_neighbors = list(self.neighbors) new_neighbors.append(neighbor) params = self._create_ctor_param_dictionary('neighbors', new_neighbors) return Zone(**params) def add_action(self, action): """ Creates a new zone that is an exact copy of this one, but has the additional action mapping. The actions are sorted by its priority in ascending order. :param Any action: :return: A NEW object. :rtype: Zone """ if len(action.get_required_events()) == 0: raise ValueError('Action must define at least one triggering event') new_actions = dict(self.actions) events = set(action.get_required_events() + action.get_external_events()) for zone_event in events: if zone_event in new_actions: new_actions[zone_event].append(action) new_actions[zone_event].sort(key=lambda a: a.get_priority()) else: new_actions[zone_event] = [action] params = self._create_ctor_param_dictionary('actions', new_actions) return Zone(**params) def get_actions(self, zone_event): """ :return: the list of actions for the provided zoneEvent :rtype: list(Action) """ if zone_event in self.actions: return self.actions[zone_event] else: return [] def has_action(self, action: Action): """ Determine if the zone contains the specified action. :rtype: Boolean """ for action_list in self.actions.values(): if action in action_list: return True return False def get_id(self): """ :rtype: str """ return self.get_level().value + '_' + self.get_name() def get_name(self): """ :rtype: str """ return self.name def is_internal(self): """ :return: True if the this is an internal zone :rtype: bool """ return not self.is_external() def is_external(self): """ :return: True if the this is an external zone :rtype: bool """ return self.external def get_level(self): """ :rtype: zone.Level""" return self.level def get_display_icon(self): """ :rtype: str or None if not available""" return self.displayIcon def get_display_order(self): """ :rtype: int""" return self.displayOrder def get_neighbors(self): """ :return: a copy of the list of neighboring zones. :rtype: list(Neighbor) """ return list(self.neighbors) def get_neighbor_zones(self, zone_manager, neighbor_types=None): """ :param zone_manager: :param list(NeighborType) neighbor_types: optional :return: a list of neighboring zones for the provided neighbor type (optional). :rtype: list(Zone) """ if neighbor_types is None: neighbor_types = [] if zone_manager is None: raise ValueError('zoneManager must not be None') if neighbor_types is None or len(neighbor_types) == 0: zones = [zone_manager.get_zone_by_id(n.get_zone_id()) for n in self.neighbors] else: zones = [zone_manager.get_zone_by_id(n.get_zone_id()) for n in self.neighbors if any(n.get_type() == t for t in neighbor_types)] return zones def contains_open_hab_item(self, item, sensor_type: type = None): """ Returns True if this zone contains the given item; returns False otherwise. :param Item item: :param Device sensor_type: an optional sub-class of Device. If specified,\ will search for itemName for those device types only. Otherwise,\ search for all devices/sensors. :rtype: bool """ sensors = self.get_devices() if sensor_type is None \ else self.get_devices_by_type(sensor_type) return any(s.contains_item(item) for s in sensors) def get_illuminance_level(self): """ Retrieves the maximum illuminance level from one or more IlluminanceSensor. If no sensor is available, return -1. :rtype: int """ illuminances = [s.get_illuminance_level() for s in self.get_devices_by_type( IlluminanceSensor)] zone_illuminance = -1 if len(illuminances) > 0: zone_illuminance = max(illuminances) return zone_illuminance def is_occupied(self, ignored_device_types=None, seconds_from_last_event=5 * 60): """ Returns a list of two value. The first value is True if at least one device's is_occupied() method returns true (i.e. at least one device was triggered within the provided # of seconds); otherwise it is False. If the first list item is True, then the second value is the Device that indicates occupancy; otherwise it i None. :param seconds_from_last_event: :param list(Device) ignored_device_types: the devices not to be considered for the occupancy check. :rtype: list(bool, Device) """ if ignored_device_types is None: ignored_device_types = [] for device in self.get_devices(): if not any(isinstance(device, deviceType) for deviceType in ignored_device_types): if device.is_occupied(seconds_from_last_event): return True, device return False, None def is_light_on(self): """ Returns True if at least one light is on; returns False otherwise. :rtype: bool """ return any(light.is_on() for light in self.get_devices_by_type(Light)) def share_sensor_with(self, zone, sensor_type): """ Returns True if this zone shares at least one sensor of the given sensor_type with the provider zone. Two sensors are considered the same if they link to the same channel. See :meth:`.Device.getChannel` :rtype: bool """ our_sensor_channels = [s.get_channel() for s in self.get_devices_by_type(sensor_type) if s.get_channel() is not None] their_sensor_channels = [s.get_channel() for s in zone.get_devices_by_type(sensor_type) if s.get_channel() is not None] intersection = set(our_sensor_channels).intersection(their_sensor_channels) return len(intersection) > 0 def turn_off_lights(self, events): """ Turn off all the lights in the zone. :param scope.events events: """ for light in self.get_devices_by_type(Light): if light.is_on(): light.turn_off(events) def on_switch_turned_on(self, events, item, immutable_zone_manager): """ If item belongs to this zone, dispatches the event to the associated Switch object, execute the associated actions, and returns True. Otherwise return False. See :meth:`.Switch.onSwitchTurnedOn` :param item: :param events: :param ImmutableZoneManager immutable_zone_manager: a function that \ returns a Zone object given a zone id string :rtype: boolean """ is_processed = False actions = self.get_actions(ZoneEvent.SWITCH_TURNED_ON) event_info = EventInfo(ZoneEvent.SWITCH_TURNED_ON, item, self, immutable_zone_manager, events) switches = self.get_devices_by_type(Switch) for switch in switches: if switch.on_switch_turned_on(events, pe.get_item_name(item)): for a in actions: a.on_action(event_info) is_processed = True return is_processed def on_switch_turned_off(self, events, item, immutable_zone_manager): """ If item belongs to this zone, dispatches the event to the associated Switch object, execute the associated actions, and returns True. Otherwise return False. See :meth:`.Switch.onSwitchTurnedOff` :rtype: boolean """ event_info = EventInfo(ZoneEvent.SWITCH_TURNED_OFF, item, self, immutable_zone_manager, events) is_processed = False actions = self.get_actions(ZoneEvent.SWITCH_TURNED_OFF) switches = self.get_devices_by_type(Switch) for switch in switches: if switch.on_switch_turned_off(events, pe.get_item_name(item)): for a in actions: a.on_action(event_info) is_processed = True return is_processed def dispatch_event(self, zone_event, event_dispatcher, device: Union[Device, None], item, immutable_zone_manager, owning_zone=None): """ :param Device device: the device containing the item that received the event. :param Any item: the OpenHab item that received the event :param ZoneEvent zone_event: :param events event_dispatcher: :param ImmutableZoneManager immutable_zone_manager: :param Any owning_zone: the zone that contains the item; None if the current zone contains the item. :rtype: boolean """ processed = False event_info = EventInfo(zone_event, item, self, immutable_zone_manager, event_dispatcher, owning_zone, device) if zone_event == ZoneEvent.STARTUP: for action_list in self.actions.values(): for action in action_list: action.on_startup(event_info) processed = True elif zone_event == ZoneEvent.DESTROY: for action_list in self.actions.values(): for action in action_list: action.on_destroy(event_info) processed = True else: for a in self.get_actions(zone_event): if a.on_action(event_info): processed = True return processed def __str__(self): value = u"Zone: {}, floor: {}, {}, displayIcon: {}, displayOrder: {}, {} devices".format( self.name, self.level.name, ('external' if self.is_external() else 'internal'), self.displayIcon, self.displayOrder, len(self.devices)) for d in sorted(self.devices, key=lambda item: item.__class__.__name__): value += u"\n {}".format(str(d)) if len(self.actions) > 0: value += u"\n" for key in sorted(self.actions.keys(), key=lambda item: item.name): action_list = self.actions[key] for action in action_list: value += u"\n Action: {} -> {}".format(key.name, type(action).__name__) if len(self.neighbors) > 0: value += u"\n" for n in self.neighbors: value += u"\n Neighbor: {}, {}".format( n.get_zone_id(), n.get_type().name) return value def _create_ctor_param_dictionary(self, key_to_replace: str, new_value): """ A helper method to return a list of ctor parameters. :param str key_to_replace: the key to override :param any new_value: the new value to replace :rtype: dict """ params = {'name': self.name, 'devices': self.devices, 'level': self.level, 'neighbors': self.neighbors, 'actions': self.actions, 'external': self.external, 'display_icon': self.displayIcon, 'display_order': self.displayOrder, key_to_replace: new_value} return params
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/zone.py
zone.py
from threading import Timer from typing import List, Union, Type from zone_api import platform_encapsulator as pe from zone_api.core.immutable_zone_manager import ImmutableZoneManager from zone_api.core.zone import Zone class ZoneManager: """ Contains a set of Zone instances. """ def __init__(self): self.zones = {} # map from string zoneId to Zone self.auto_report_watch_dog_timer = None def add_zone(self, zone: Zone): """ Adds a zone. :param Zone zone: a Zone instance """ if zone is None: raise ValueError('zone must not be None') self.zones[zone.get_id()] = zone return self def remove_zone(self, zone: Zone): """ Removes a zone. :param Zone zone: a Zone instance """ if zone is None: raise ValueError('zone must not be None') self.zones.pop(zone.get_id()) return self def remove_all_zones(self): """ Removes all zone. """ self.zones.clear() return self def get_zones(self) -> List[Zone]: """ Returns a new list contains all zone. :rtype: list(Zone) """ zones = [z for z in self.zones.values()] zones.sort(key=lambda z: z.get_display_order()) return zones def get_zone_by_id(self, zone_id: str) -> Union[None, Zone]: """ Returns the zone associated with the given zoneId. :param string zone_id: the value returned by Zone::get_id() :return: the associated zone or None if the zoneId is not found :rtype: Zone """ zone = self.zones[zone_id] if zone_id in self.zones else None return zone def get_devices_by_type(self, cls: Type): """ Returns a list of devices in all zones matching the given type. :param Type cls: the device type :rtype: list(Device) """ if cls is None: raise ValueError('cls must not be None') devices = [] for zone in self.zones.values(): devices = devices + zone.get_devices_by_type(cls) return devices def start_auto_report_watch_dog(self, timer_interval_in_seconds=10 * 60, inactive_interval_in_seconds=10 * 60): """ Starts a timer that run every timerIntervalInSeconds. When the timer is triggered, it will scan auto-report devices (Devices::isAutoReport), and if any of them hasn't been triggered in the last inactiveIntervalInSeconds, it will reset the item value. This method is safe to call multiple times (a new timer will be started and any old timer is cancelled). :param int timer_interval_in_seconds: the timer duration :param int inactive_interval_in_seconds: the inactive duration after which the device's value will be reset. :rtype: None """ def reset_failed_auto_report_devices(): devices = [] for z in self.get_zones(): [devices.append(d) for d in z.get_devices() if d.is_auto_report() and not d.was_recently_activated(inactive_interval_in_seconds)] if len(devices) > 0: item_names = [] for d in devices: item_names.append(d.get_item_name()) d.reset_value_states() pe.log_warning( "AutoReport Watchdog: {} failed auto-report devices: {}".format( len(devices), item_names)) else: pe.log_debug("AutoReport Watchdog: no failed auto-report devices") # restart the timer self.auto_report_watch_dog_timer = Timer( timer_interval_in_seconds, reset_failed_auto_report_devices) self.auto_report_watch_dog_timer.start() self.stop_auto_report_watch_dog() self.auto_report_watch_dog_timer = Timer( timer_interval_in_seconds, reset_failed_auto_report_devices) self.auto_report_watch_dog_timer.start() pe.log_info("Started auto-report watchdog timer.") def stop_auto_report_watch_dog(self): if self.auto_report_watch_dog_timer is not None \ and self.auto_report_watch_dog_timer.is_alive(): self.auto_report_watch_dog_timer.cancel() self.auto_report_watch_dog_timer = None def get_immutable_instance(self) -> ImmutableZoneManager: """ Return an immutable zone manager instance that contains the same data as in this object. :rtype: ImmutableZoneManager """ return ImmutableZoneManager(self.get_zones, self.get_zone_by_id, self.get_devices_by_type)
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/zone_manager.py
zone_manager.py
import typing from typing import Any from zone_api.core.zone_event import ZoneEvent if typing.TYPE_CHECKING: from zone_api.core.device import Device from zone_api.core.zone import Zone from zone_api.core.immutable_zone_manager import ImmutableZoneManager class EventInfo(object): """ Represent an event such as switch turned on, switch turned off, or motion triggered. """ def __init__(self, event_type: ZoneEvent, item, zone: 'Zone', zone_manager: 'ImmutableZoneManager', events, owning_zone: 'Zone' = None, device: 'Device' = None, custom_parameter: Any = None): """ Creates a new EventInfo object. :param ZoneEvent event_type: the type of the event :param Item item: the OpenHab Item :param Zone zone: the zone where the event was triggered :param ImmutableZoneManager zone_manager: :param Any events: the OpenHab events object to dispatch actions :param Zone owning_zone: the zone that contains the item; None if it is the same at the dispatched zone. :param Device device: the device containing the item triggered the event. """ if event_type is None: raise ValueError('eventType must not be None') # The item field isn't available for several event types. if event_type not in [ZoneEvent.STARTUP, ZoneEvent.DESTROY, ZoneEvent.TIMER]: if item is None: raise ValueError('item must not be None') if zone is None: raise ValueError('zone must not be None') if events is None: raise ValueError('events must not be None') self.eventType = event_type self.device = device self.item = item self.zone = zone self.zoneManager = zone_manager self.events = events self._owning_zone = owning_zone self._custom_parameter = custom_parameter def get_event_type(self) -> 'ZoneEvent': """ :rtype: ZoneEvent""" return self.eventType def get_device(self) -> 'Device': """ :rtype: Device""" return self.device def get_item(self): """ :rtype: Item""" return self.item def get_zone(self) -> 'Zone': """ :rtype: Zone""" return self.zone def get_zone_manager(self) -> 'ImmutableZoneManager': """ :rtype: ImmutableZoneManager""" return self.zoneManager def get_event_dispatcher(self): """ :rtype: Event""" return self.events def get_owning_zone(self) -> 'Zone': """ Returns the zone that contains the item; returns None if it is the same at the dispatched zone.""" return self._owning_zone def get_custom_parameter(self): """ :rtype: Any""" return self._custom_parameter
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/event_info.py
event_info.py
import random from threading import Timer from typing import Dict from zone_api import platform_encapsulator as pe from zone_api.core.devices.switch import Light class Wled(Light): """ Represents a WLED strip. @see https://github.com/Skinah/wled @see https://github.com/Aircoookie/WLED """ def __init__(self, master_control_item, effect_item, primary_color_item, secondary_color_item, duration_in_minutes): """ Constructs a new object. :raise ValueError: if any parameter is invalid """ Light.__init__(self, master_control_item, duration_in_minutes, 0, True) self.effect_item = effect_item self.primary_color_item = primary_color_item self.secondary_color_item = secondary_color_item self.effect_timer = None def on_switch_turned_on(self, events, item_name): """ @override to turn on the effect timer """ if super(Wled, self).on_switch_turned_on(events, item_name): self._start_effect_timer(events) def on_switch_turned_off(self, events, item_name): """ @override to turn off the effect timer """ if super(Wled, self).on_switch_turned_off(events, item_name): self._cancel_effect_timer() def _start_effect_timer(self, events): """ Creates and returns the timer to change to a random effect """ def change_effect(): # Randomize the primary and secondary HSB colours # Focus on bright colours (randomize over all Hue range, with # Saturation between 50 and 100%, and full Brightness. primary_color = "{},{},100".format( random.choice(range(0, 360)), random.choice(range(50, 100))) events.send_command(pe.get_item_name(self.primary_color_item), primary_color) secondary_color = "{},{},100".format( random.choice(range(0, 360)), random.choice(range(50, 100))) events.send_command(pe.get_item_name(self.secondary_color_item), secondary_color) # now randomize the effect # noinspection PyTypeChecker effect_id = random.choice(list(get_effects().keys())) events.send_command(pe.get_item_name(self.effect_item), str(effect_id)) # start the next timer next_duration_in_minute = random.choice(range(2, 7)) self.effect_timer = Timer(next_duration_in_minute * 60, change_effect) self.effect_timer.start() self._cancel_timer() # cancel the previous timer, if any. self.effect_timer = Timer(3, change_effect) # start timer in 3 secs self.effect_timer.start() def _cancel_effect_timer(self): """ Cancel the random effect switch timer. """ if self.effect_timer is not None and self.effect_timer.is_alive(): self.effect_timer.cancel() self.effect_timer = None def __str__(self): """ @override """ return u"{}, effectItem: {}, primaryColorItem: {}, secondaryColorItem: {}".format( super(Wled, self).__str__(), pe.get_item_name(self.effect_item), pe.get_item_name(self.primary_color_item), pe.get_item_name(self.secondary_color_item)) def get_effects() -> Dict: return {0: 'Solid', 102: 'Candle Multi', 52: 'Circus', 34: 'Colorful', 8: 'Colorloop', 74: 'Colortwinkle', 7: 'Dynamic', 69: 'Fill Noise', 45: 'Fire Flicker', 89: 'Fireworks Starbust', 110: 'Flow', 87: 'Glitter', 53: 'Halloween', 75: 'Lake', 44: 'Merry Christmas', 107: 'Noise Pal', 105: 'Phased', 11: 'Rainbow', 5: 'Random Colors', 79: 'Ripple', 99: 'Ripple Rainbow', 15: 'Running', 108: 'Sine', 39: 'Stream', 13: 'Theater' }
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/wled.py
wled.py
from zone_api import platform_encapsulator as pe from zone_api.core.device import Device class Computer(Device): """ Represents a computer. Track states such as cpu temperature, GPU temperature & fan speed, always on, last update time stamp. """ def __init__(self, name: str, cpu_temperature_item=None, gpu_temperature_item=None, gpu_fan_speed_item=None, always_on=False): """ Ctor :param str name: the computer name. :param NumberItem cpu_temperature_item: :param NumberItem gpu_temperature_item: :param NumberItem gpu_fan_speed_item: fan speed in percentage. :param Bool always_on: True if the computer is always on; this value is equivalent to the Device's auto_report value. :raise ValueError: if any parameter is invalid """ Device.__init__(self, pe.create_string_item(f'Computer: {name}'), [cpu_temperature_item, gpu_temperature_item, gpu_fan_speed_item], False, False, always_on) self._name = name self._cpu_temperature_item = cpu_temperature_item self._gpu_temperature_item = gpu_temperature_item self._gpu_fan_speed_item = gpu_fan_speed_item def is_always_on(self): return self.is_auto_report() def has_cpu_temperature(self): return self._cpu_temperature_item is not None def get_cpu_temperature(self) -> float: if self._cpu_temperature_item is None: raise ValueError("CPU temperature not available.") return pe.get_number_value(self._cpu_temperature_item) def has_gpu_temperature(self): return self._gpu_temperature_item is not None def get_gpu_temperature(self) -> float: if self._gpu_temperature_item is None: raise ValueError("GPU temperature not available.") return pe.get_number_value(self._gpu_temperature_item) def has_gpu_fan_speed(self): return self._gpu_fan_speed_item is not None def get_gpu_fan_speed(self) -> float: if self._gpu_fan_speed_item is None: raise ValueError("GPU Fan Speed not available.") return pe.get_number_value(self._gpu_fan_speed_item) def __str__(self): """ @override """ return u"{}{}{}{}".format( super(Computer, self).__str__(), f", CPU Temp.: {self.get_cpu_temperature()} °C" if self.has_cpu_temperature() else "", f", GPU Temp.: {self.get_gpu_temperature()} °C" if self.has_gpu_temperature() else "", f", GPU Fan Speed: {self.get_gpu_fan_speed()} %" if self.has_gpu_fan_speed() else "")
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/computer.py
computer.py
from enum import Enum, unique from zone_api import platform_encapsulator as pe from zone_api.core.device import Device @unique class AlarmState(Enum): """ An enum of possible alarm states.""" UNARMED = 0 """ The value for the unarmed state. """ ARM_AWAY = 1 """ The value for the arm away state. """ ARM_STAY = 2 """ The value for the arm stay state. """ class AlarmPartition(Device): """ Represents a security control. Exposes methods to arm the security system, and provide the alarm status. The current implementation is for DSC Alarm system. """ def __init__(self, alarm_status_item, arm_mode_item): """ Ctor :param SwitchItem alarm_status_item: the item to indicate if the system is in alarm :param NumberItem arm_mode_item: the item to set the arming/disarming mode :raise ValueError: if any parameter is invalid """ Device.__init__(self, alarm_status_item, [arm_mode_item]) if arm_mode_item is None: raise ValueError('armModeItem must not be None') self.arm_mode_item = arm_mode_item def is_in_alarm(self): """ :return: True if the partition is in alarm; False otherwise :rtype: bool """ return pe.is_in_on_state(self.get_item()) def get_arm_mode(self) -> AlarmState: """ :return: one of STATE_UNARMED, STATE_ARM_AWAY, STATE_ARM_STAY :rtype: int """ return AlarmState(pe.get_number_value(self.arm_mode_item)) def is_armed_away(self): """ :rtype: boolean """ return AlarmState.ARM_AWAY == self.get_arm_mode() def is_armed_stay(self): """ :rtype: boolean """ return AlarmState.ARM_STAY == self.get_arm_mode() def is_unarmed(self): """ :rtype: boolean """ return AlarmState.UNARMED == self.get_arm_mode() def arm_away(self, events): """ Arm-away the partition. :param events: """ events.send_command(pe.get_item_name(self.arm_mode_item), str(AlarmState.ARM_AWAY.value)) def arm_stay(self, events): """ Arm-stay the partition. :param events: """ events.send_command(pe.get_item_name(self.arm_mode_item), str(AlarmState.ARM_STAY.value)) def disarm(self, events): """ Disarm the partition. :param events: """ events.send_command(pe.get_item_name(self.arm_mode_item), str(AlarmState.UNARMED.value)) def get_arm_mode_item(self): return self.arm_mode_item def __str__(self): """ @override """ return u"{}, armMode: {}".format( super(AlarmPartition, self).__str__(), self.get_arm_mode().name)
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/alarm_partition.py
alarm_partition.py
from zone_api import platform_encapsulator as pe from zone_api.core.device import Device class Weather(Device): """ Represents the outdoor weather condition. The minimum items required are the temperature, humidity, and condition. All other parameters are optional. """ def __init__(self, temperature_item, humidity_item, condition_item, alert_item=None, forecast_min_temperature_item=None, forecast_max_temperature_item=None): """ Ctor :param NumberItem temperature_item: :param NumberItem humidity_item: :param StringItem condition_item: :param StringItem alert_item: :param NumberItem forecast_min_temperature_item: :param NumberItem forecast_max_temperature_item: :raise ValueError: if any parameter is invalid """ Device.__init__(self, temperature_item, [humidity_item, condition_item, alert_item, forecast_min_temperature_item, forecast_max_temperature_item]) self._temperature_item = temperature_item self._humidity_item = humidity_item self._condition_item = condition_item self._alert_item = alert_item self._forecast_min_temperature_item = forecast_min_temperature_item self._forecast_max_temperature_item = forecast_max_temperature_item def get_temperature(self) -> float: return pe.get_number_value(self._temperature_item) def get_humidity(self) -> float: return pe.get_number_value(self._humidity_item) def get_condition(self) -> str: return pe.get_string_value(self._condition_item) def support_alert(self): """ Returns true if the alert information is available. """ return self._alert_item is not None def get_alert(self) -> str: if not self.support_alert(): raise ValueError("alert is not available.") return pe.get_string_value(self._alert_item) def support_forecast_min_temperature(self): return self._forecast_min_temperature_item is not None def get_forecast_min_temperature(self) -> float: if not self.support_forecast_min_temperature(): raise ValueError("forecast_min_temperature is not available.") return pe.get_number_value(self._forecast_min_temperature_item) def support_forecast_max_temperature(self): return self._forecast_max_temperature_item is not None def get_forecast_max_temperature(self) -> float: if not self.support_forecast_max_temperature(): raise ValueError("forecast_max_temperature is not available.") return pe.get_number_value(self._forecast_max_temperature_item) def __str__(self): """ @override """ return u"{}{}{}{}{}{}{}".format( super(Weather, self).__str__(), f", Temp.: {self.get_temperature()}°C", f", Humidity: {self.get_humidity()}%", f", Condition: {self.get_condition()}", f", Alert: {self.get_alert()}" if ( self.support_alert() and self.get_alert() is not None and self.get_alert() != '') else "", f", Min. Temp.: {self.get_forecast_min_temperature()}°C" if self.support_forecast_min_temperature() else "", f", Max. Temp.: {self.get_forecast_max_temperature()}°C" if self.support_forecast_max_temperature() else "")
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/weather.py
weather.py
import time from typing import Union from zone_api import platform_encapsulator as pe from zone_api.core.device import Device from zone_api.music_streams import MusicStream MAX_SAY_WAIT_TIME_IN_SECONDS = 20 class ChromeCastAudioSink(Device): """ Represents a ChromeCast audio sink. """ def __init__(self, sink_name, player_item, volume_item, title_item, idling_item, out_current_stream_item=None): """ Ctor :param str sink_name: the sink name for voice and audio play. The sink name can be retrieved by running "openhab-cli console" and then "smarthome:audio sinks". :param PlayerItem player_item: :param NumberItem volume_item: :param StringItem title_item: :param SwitchItemItem idling_item: :param StringItem out_current_stream_item: the optional item to display the current music stream name :raise ValueError: if any parameter is invalid """ Device.__init__(self, pe.create_string_item(f'Chromecast-{sink_name}'), [player_item, volume_item, title_item, idling_item]) self._sink_name = sink_name self._volume_item = volume_item self._title_item = title_item self._player_item = player_item self._idling_item = idling_item self._out_current_stream_item = out_current_stream_item self.streamUrl = None self.lastTtsMessage = None self._testMode = False self._testLastCommand = None self._lastCommandTimestamp = time.time() self._lastCommand = None def play_message(self, message, volume=50): """ Play the given message on one or more ChromeCast and wait till it finishes (up to MAX_SAY_WAIT_TIME_IN_SECONDS seconds). Afterward, pause the player. After this call, cast.isActive() will return False. If self._testMode is True, no message will be sent to the cast. :param str message: the message to tts :param int volume: the volume value, 0 to 100 inclusive :return: boolean True if success; False if stream name is invalid. :raise: ValueError if volume is not in the 0 - 100 inclusive range, or if\ message is None or empty. """ if volume < 0 or volume > 100: raise ValueError('volume must be between 0 and 100') if message is None or '' == message: raise ValueError('message must not be null or empty') was_active = self.is_active() previous_volume = pe.get_number_value(self._volume_item) pe.set_number_value(self._volume_item, volume) if not self._testMode: pe.play_text_to_speech_message(self.get_sink_name(), message) else: self._testLastCommand = 'playMessage' self.lastTtsMessage = message if not self._testMode: # Wait until the cast is available again or a specific number of seconds # has passed. This is a workaround for the limitation that the OpenHab # 'say' method is non-blocking. seconds = 2 time.sleep(seconds) while seconds <= MAX_SAY_WAIT_TIME_IN_SECONDS: if self._has_title(): # this means the announcement is still happening. time.sleep(1) seconds += 1 else: # announcement is finished. seconds = MAX_SAY_WAIT_TIME_IN_SECONDS + 1 self.pause() if was_active: pe.set_number_value(self._volume_item, previous_volume) self.resume() return True def play_sound_file(self, local_file, duration_in_secs, volume=None): """ Plays the provided local sound file. See '/etc/openhab/sound'. :param volume: :param str local_file: a sound file located in '/etc/openhab/sound' :param int duration_in_secs: the duration of the sound file in seconds :rtype: boolean """ self._lastCommandTimestamp = time.time() self._lastCommand = local_file if self._testMode: self._testLastCommand = 'playSoundFile' return True was_active = self.is_active() previous_volume = pe.get_number_value(self._volume_item) if volume is not None: pe.set_number_value(self._volume_item, volume) pe.play_local_audio_file(self.get_sink_name(), local_file) if was_active: time.sleep(duration_in_secs + 1) pe.set_number_value(self._volume_item, previous_volume) self.resume() return True def play_stream(self, url_or_stream: Union[str, MusicStream], volume=None): """ Play the given stream url. :param volume: :param str url_or_stream: a string Url or a MusicStream object :return: boolean True if success; False if stream name is invalid. """ if volume is not None and (volume < 0 or volume > 100): raise ValueError('volume must be between 0 and 100.') if url_or_stream is None: raise ValueError('url_or_stream must be specified.') if self._testMode: self._testLastCommand = 'playStream' return True if volume is not None: pe.set_number_value(self._volume_item, volume) if isinstance(url_or_stream, MusicStream): url = url_or_stream.url if self._out_current_stream_item is not None: pe.set_string_value(self._out_current_stream_item, url_or_stream.name) else: url = url_or_stream if url == self.get_stream_url(): self.resume() else: pe.play_stream_url(self.get_sink_name(), url) self.streamUrl = url return True def pause(self): """ Pauses the chrome cast player. """ if self._testMode: self._testLastCommand = 'pause' return pe.change_player_state_to_pause(self._player_item) def resume(self): """ Resumes playing. """ if self._testMode: self._testLastCommand = 'resume' return if pe.is_in_on_state(self._idling_item): pe.play_stream_url(self.get_sink_name(), self.get_stream_url()) else: pe.play_stream_url(self.get_sink_name(), self.get_stream_url()) pe.change_player_state_to_play(self._player_item) def is_active(self): """ Return true if the the chromecast is playing something. """ return not pe.is_in_on_state(self._idling_item) and pe.is_player_playing(self._player_item) def _has_title(self): """ :rtype: bool """ title = pe.get_string_value(self._title_item) return title is not None and title != '' def get_stream_url(self): """ Returns the current stream Uri or None if no stream set. :rtype: str """ return self.streamUrl def get_last_tts_message(self): """ :rtype: str """ return self.lastTtsMessage def get_sink_name(self): """ Return the sink name for Voice.say and Audio.playStream usages. :rtype: str """ return self._sink_name def _set_test_mode(self): self._testMode = True self._testLastCommand = None def _get_last_test_command(self): return self._testLastCommand
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/chromecast_audio_sink.py
chromecast_audio_sink.py
from zone_api.core.device import Device from zone_api import platform_encapsulator as pe class GasSensor(Device): """ Represents a generic gas sensor. """ def __init__(self, value_item, state_item, battery_powered=False, wifi=True, auto_report=True): """ Ctor :param NumberItem value_item: the item to get the value reading :param SwitchItem state_item: the item to get the state reading :param bool battery_powered: indicates if the device is powered by battery. :param bool wifi: indicate if the sensor communicates by WI-FI :param bool auto_report: indicate if the sensor reports periodically :raise ValueError: if value_item is invalid """ Device.__init__(self, value_item, [state_item], battery_powered, wifi, auto_report) if state_item is None: raise ValueError('state_item must not be None') self._state_item = state_item def get_value(self): """ :return: the current sensor value. :rtype: int """ return pe.get_number_value(self.get_item()) def is_triggered(self): """ :return: true if the gas sensor has detected a high level of concentration :rtype: bool """ return pe.is_in_on_state(self._state_item) def reset_value_states(self): """ Override. """ pe.set_number_value(self.get_item(), -1) pe.set_switch_state(self._state_item, False) class Co2GasSensor(GasSensor): """ Represents a CO2 sensor. """ def __init__(self, value_item, state_item): GasSensor.__init__(self, value_item, state_item) class NaturalGasSensor(GasSensor): """ Represents a natural gas sensor. """ def __init__(self, value_item, state_item): GasSensor.__init__(self, value_item, state_item) class SmokeSensor(GasSensor): """ Represents a smoke sensor. """ def __init__(self, value_item, state_item): GasSensor.__init__(self, value_item, state_item)
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/gas_sensor.py
gas_sensor.py
from zone_api.core.device import Device from zone_api import platform_encapsulator as pe class Plug(Device): """ Represents a smart plug with optional power reading in Watt. """ POWER_USAGE_THRESHOLD_IN_WATT = 8 """ The plug power usage threshold; if it is above this value, the zone containing this plug is considered to be occupied. """ def __init__(self, plug_item, power_reading_item=None, always_on=False): """ Ctor :param SwitchItem plug_item: :param NumberItem power_reading_item: the optional item to get the wattage reading :param Bool always_on: indicates if the plug should be on all the time :raise ValueError: if plug_item is invalid """ Device.__init__(self, plug_item) self.power_reading_item = power_reading_item self.always_on = always_on def is_on(self): """ :return: True if the partition is in alarm; False otherwise :rtype: bool """ return pe.is_in_on_state(self.get_item()) def has_power_reading(self): """ :return: True if the plug can read the current wattage. :rtype: bool """ return self.power_reading_item is not None def get_wattage(self): """ :return: the current wattage of the plug :rtype: int or 0 if the plug has no power reading """ if self.power_reading_item is None: raise ValueError("Plug has no power reading capability") return pe.get_number_value(self.power_reading_item) def is_always_on(self): """ Returns true if this plug should not be turned off automatically. """ return self.always_on def is_occupied(self, seconds_from_last_event=5 * 60): """ Returns True if the power reading is above the threshold. @override :rtype: bool """ return self.has_power_reading() and self.get_wattage() > Plug.POWER_USAGE_THRESHOLD_IN_WATT def turn_on(self, events): """ Turns on this plug, if it is not on yet. """ if not self.is_on(): events.send_command(self.get_item_name(), "ON") def turn_off(self, events): """ Turn off this plug. """ if self.is_on(): events.send_command(self.get_item_name(), "OFF") def __str__(self): """ @override """ return u"{}{}".format( super(Plug, self).__str__(), ", always on" if self.is_always_on() else "")
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/plug.py
plug.py
from enum import unique, Enum from zone_api import platform_encapsulator as pe from zone_api.core.device import Device from zone_api import time_utilities @unique class ActivityType(Enum): """ A list of activity period types. """ LUNCH = 'lunch' DINNER = 'dinner' SLEEP = 'sleep' QUIET = 'quiet' WAKE_UP = 'wakeup' AUTO_ARM_STAY = 'auto-arm-stay' TURN_OFF_PLUGS = 'turn-off-plugs' class ActivityTimes(Device): """ Represents a virtual device that represent the activities within the zone. This device has no real backed OpenHab item. """ def __init__(self, time_range_map): """ Ctor :param dictionary time_range_map: a map from activity ActivityType to time range string. A time range string can be a single or multiple ranges in the 24-hour format. Example: '10-12', or '6-9, 7-7, 8:30 - 14:45', or '19 - 8' (wrap around) :raise ValueError: if any parameter is invalid """ Device.__init__(self, pe.create_string_item('ActivityTimesItem')) acceptable_keys = ['lunch', 'dinner', 'sleep', 'quiet', 'wakeup', 'auto-arm-stay', 'turn-off-plugs'] for key in time_range_map.keys(): if key not in ActivityType: raise ValueError('Invalid time range key {}'.format(key)) self.timeRangeMap = time_range_map def is_lunch_time(self, epoch_seconds=None): return self._is_in_time_range(ActivityType.LUNCH, epoch_seconds) def is_dinner_time(self, epoch_seconds=None): return self._is_in_time_range(ActivityType.DINNER, epoch_seconds) def is_quiet_time(self, epoch_seconds=None): return self._is_in_time_range(ActivityType.QUIET, epoch_seconds) def is_sleep_time(self, epoch_seconds=None): return self._is_in_time_range(ActivityType.SLEEP, epoch_seconds) def is_wakeup_time(self, epoch_seconds=None): return self._is_in_time_range(ActivityType.WAKE_UP, epoch_seconds) def is_auto_arm_stay_time(self, epoch_seconds=None): return self._is_in_time_range(ActivityType.AUTO_ARM_STAY, epoch_seconds) def is_turn_off_plugs_time(self, epoch_seconds=None): return self._is_in_time_range(ActivityType.TURN_OFF_PLUGS, epoch_seconds) def _is_in_time_range(self, key, epoch_seconds): if key not in self.timeRangeMap.keys(): return False time_range_string = self.timeRangeMap[key] return time_utilities.is_in_time_range(time_range_string, epoch_seconds)
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/activity_times.py
activity_times.py
from zone_api import platform_encapsulator as pe from zone_api.core.devices.switch import Light from zone_api import time_utilities class Dimmer(Light): """ Represents a light dimmer with the dim level value ranges from 1 to 100. """ def __init__(self, switch_item, duration_in_minutes: int, dim_level: int = 5, time_ranges: str = None, illuminance_level: int = None, no_premature_turn_off_time_range=None): """ Constructs a new object. :raise ValueError: if any parameter is invalid """ Light.__init__(self, switch_item, duration_in_minutes, illuminance_level, no_premature_turn_off_time_range) if dim_level < 0 or dim_level > 100: raise ValueError('dimLevel must be between 0 and 100 inclusive') time_utilities.string_to_time_range_lists(time_ranges) # validate self.dim_level = dim_level self.time_ranges = time_ranges def turn_on(self, events): """ Turn on this light if it is not on yet. If the light is dimmable, and if the current time falls into the specified time ranges, it will be dimmed; otherwise it is turned on at 100%. The associated timer item is also turned on. @override """ if not pe.is_in_on_state(self.get_item()): if time_utilities.is_in_time_range(self.time_ranges): events.send_command(self.get_item_name(), str(self.dim_level)) else: events.send_command(self.get_item_name(), "100") self._handle_common_on_action(events) def is_on(self): """ Returns true if the dimmer is turned on; false otherwise. @override """ return pe.get_dimmer_percentage(self.get_item()) > 0 def __str__(self): """ @override """ return u"{}, dimLevel: {}, timeRanges: {}".format( super(Dimmer, self).__str__(), self.dim_level, self.time_ranges)
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/dimmer.py
dimmer.py
import time from threading import Timer from zone_api import platform_encapsulator as pe from zone_api.core.device import Device from zone_api import time_utilities class Switch(Device): """ Represents a light or fan switch. Each switch contains an internal timer. When the switch is turned on, the timer is started. As the timer expires, the switch is turned off (if it is not off already). If the switch is turned off not by the timer, the timer is cancelled. """ def __init__(self, switch_item, duration_in_minutes: float): """ Ctor :param SwitchItem switch_item: :param int duration_in_minutes: how long the switch will be kept on :raise ValueError: if any parameter is invalid """ Device.__init__(self, switch_item) self.lastOffTimestampInSeconds = -1 self.duration_in_minutes = duration_in_minutes self.timer = None def _start_timer(self, events): """ Creates and returns the timer to turn off the switch. """ def turn_off_switch(): zone = self.get_zone_manager().get_containing_zone(self) (occupied, device) = zone.is_occupied([Switch], 60) if not occupied: events.send_command(self.get_item_name(), "OFF") pe.log_debug("{}: turning off {}.".format( zone.get_name(), self.get_item_name())) else: self.timer = Timer(self.duration_in_minutes * 60, turn_off_switch) self.timer.start() pe.log_debug("{}: {} is in use by {}.".format( zone.get_name(), self.get_item_name(), device)) self._cancel_timer() # cancel the previous timer, if any. self.timer = Timer(self.duration_in_minutes * 60, turn_off_switch) self.timer.start() def _cancel_timer(self): """ Cancel the turn-off-switch timer. """ if self.timer is not None and self.timer.is_alive(): self.timer.cancel() self.timer = None def _is_timer_active(self): return self.timer is not None and self.timer.is_alive() def turn_on(self, events): """ Turns on this light, if it is not on yet. In either case, the associated timer item is also turned on. """ if self.is_on(): # already on, renew timer self._start_timer(events) else: events.send_command(self.get_item_name(), "ON") def turn_off(self, events): """ Turn off this light. """ if self.is_on(): events.send_command(self.get_item_name(), "OFF") self._cancel_timer() def is_on(self): """ Returns true if the switch is turned on; false otherwise. """ return pe.is_in_on_state(self.get_item()) def on_switch_turned_on(self, events, item_name): """ Invoked when a switch on event is triggered. Note that a switch can be turned on through this class' turnOn method, or through the event bus, or manually by the user. The following actions are done: - the on timestamp is set; - the timer is started or renewed. :param events: :param str item_name: the name of the item triggering the event :return True: if itemName refers to this switch; False otherwise """ is_processed = (self.get_item_name() == item_name) if is_processed: self._handle_common_on_action(events) return is_processed def on_switch_turned_off(self, events, item_name): """ Invoked when a switch off event is triggered. Note that a switch can be turned off through this class' turnOff method, or through the event bus, or manually by the user. The following actions are done: - the timer is cancelled. :param scope.events events: :param string item_name: the name of the item triggering the event :return: True if itemName refers to this switch; False otherwise """ is_processed = (self.get_item_name() == item_name) if is_processed: self.lastOffTimestampInSeconds = time.time() self._cancel_timer() return is_processed def get_last_off_timestamp_in_seconds(self): """ Returns the timestamp in epoch seconds the switch was last turned off. :return: -1 if the timestamp is not available, or an integer presenting\ the epoch seconds """ return self.lastOffTimestampInSeconds # Misc common things to do when a switch is turned on. def _handle_common_on_action(self, events): self.lastLightOnSecondSinceEpoch = time.time() self._start_timer(events) # start or renew timer def is_low_illuminance(self, current_illuminance): """ Always return False. """ return False def __str__(self): """ @override """ return u"{}, duration: {} minutes".format( super(Switch, self).__str__(), self.duration_in_minutes) class Light(Switch): """ Represents a regular light. """ def __init__(self, switch_item, duration_in_minutes: float, illuminance_level: int = None, no_premature_turn_off_time_range: str = None): """ :param int illuminance_level: the illuminance level in LUX unit. The \ light should only be turned on if the light level is below this unit. :param str no_premature_turn_off_time_range: optional parameter to define \ the time range when the light should not be turned off before its \ expiry time. """ Switch.__init__(self, switch_item, duration_in_minutes) self.illuminance_level = illuminance_level self.no_premature_turn_off_time_range = no_premature_turn_off_time_range def get_illuminance_threshold(self): """ Returns the illuminance level in LUX unit. Returns None if not applicable. :rtype: int or None """ return self.illuminance_level def is_low_illuminance(self, current_illuminance): """ Returns False if this light has no illuminance threshold or if current_illuminance is less than 0. Otherwise returns True if the current_illuminance is less than threshold. @override """ if self.get_illuminance_threshold() is None: return False if current_illuminance < 0: # current illuminance not available return False return current_illuminance < self.get_illuminance_threshold() def can_be_turned_off_by_adjacent_zone(self): """ Returns True if this light can be turned off when the light of an adjacent zone is turned on. A False value might be desired if movement in the adjacent zone causes the light to be turned off unexpectedly too often. :rtype: bool """ if self.no_premature_turn_off_time_range is None: return True if time_utilities.is_in_time_range(self.no_premature_turn_off_time_range): return False return True def is_occupied(self, seconds_from_last_event=5 * 60): """ Returns True if the device is on. @override :rtype: bool """ return self.is_on() def __str__(self): """ @override """ return u"{}, illuminance: {}{}".format( super(Light, self).__str__(), self.illuminance_level, ", no premature turn-off time range: {}".format(self.no_premature_turn_off_time_range) if self.no_premature_turn_off_time_range is not None else "") class Fan(Switch): """ Represents a fan switch. """ def __init__(self, switch_item, duration_in_minutes): Switch.__init__(self, switch_item, duration_in_minutes)
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/switch.py
switch.py
from datetime import datetime, timedelta import os.path import time from zone_api.core.device import Device class Camera(Device): """ Represents a network camera. """ def __init__(self, camera_name_item, camera_name, image_location='/home/pi/motion-os'): """ Ctor :param StringItem camera_name_item: a dummy item; won't be used by this device. :param str camera_name: the optional file location of the still images :param str image_location: the optional file location of the still images :raise ValueError: if cameraNameItem is invalid """ Device.__init__(self, camera_name_item) self._camera_name = camera_name self._image_location = image_location def has_motion_event(self): """ Sleep for 10 seconds to wait for the images to be flushed to the file system. After that, check to see if there is any snapshot. If yes, return true. :rtype: bool """ current_epoch = time.time() time.sleep(10) urls = self.get_snapshot_urls(current_epoch, 6, 5) return len(urls) > 0 def get_snapshot_urls(self, time_in_epoch_seconds=time.time(), max_number_of_seconds=15, offset_seconds=5): """ Retrieve the still camera image URLs. :param float time_in_epoch_seconds: the pivot time to calculate the start and end times for the still images. :param int max_number_of_seconds: the maximum # of seconds to retrieve the images for :param int offset_seconds: the # of seconds before the epochSeconds to retrieve the images for :return: list of snapshot URLs or empty list if there is no snapshot :rtype: list(str) """ return retrieve_snapshots_from_file_system( max_number_of_seconds, offset_seconds, time_in_epoch_seconds, self._camera_name, self._image_location) def __str__(self): """ @override """ return u"{}, cameraName: {}, imageLocation: {}".format( super(Camera, self).__str__(), self._camera_name, self._image_location) def retrieve_snapshots_from_file_system(max_number_of_seconds=15, offset_seconds=5, epoch_seconds: float = time.time(), camera='Camera1', image_location='/home/pi/motion-os'): """ Retrieve the still camera images from the specified folder. The image files must be in this folder structure: {year}-{month}-{day}/{hour}-{minute}-{sec} Example: 2019-11-06/22-54-02.jpg. If any of the field is less than 10, then it must be padded by '0'. These are the structures written out by MotionEyeOS. :param int max_number_of_seconds: the maximum # of seconds to retrieve the images for :param int offset_seconds: the # of seconds before the epochSeconds to retrieve the images for :param str camera: the name of the camera :param int epoch_seconds: the time the motion triggered time :param str image_location: :return: list of snapshot URLs or empty list if there is no snapshot :rtype: list(str) """ def pad(x: int): return "0{}".format(x) if x < 10 else x urls = [] if image_location.endswith('/'): image_location = image_location[:-1] current_time = datetime.fromtimestamp(epoch_seconds) path = "{}/{}/{}-{}-{}".format(image_location, camera, current_time.year, current_time.month, pad(current_time.day)) for second in range(-offset_seconds, max_number_of_seconds - offset_seconds): delta = timedelta(seconds=second) instant = current_time + delta file_name = "{}-{}-{}.jpg".format(pad(instant.hour), pad(instant.minute), pad(instant.second)) path_and_filename = "{}/{}".format(path, file_name) if os.path.exists(path_and_filename): url = "file://{}".format(path_and_filename) urls.append(url) return urls
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/devices/camera.py
camera.py
import random from threading import Timer from zone_api.audio_manager import Genre, get_music_streams_by_genres, get_nearby_audio_sink from zone_api.core.action import action from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.activity_times import ActivityTimes @action(events=[ZoneEvent.MOTION], devices=[MotionSensor], zone_name_pattern='.*Kitchen.*') class PlayMusicAtDinnerTime: """ Chooses a random URL stream when the motion sensor in the kitchen is triggered at dinner time. Turns off after the specified period. """ # noinspection PyDefaultArgument def __init__(self, music_streams=get_music_streams_by_genres( [Genre.CLASSICAL, Genre.INSTRUMENT, Genre.JAZZ]), duration_in_minutes: float = 180): """ Ctor :param list[str] music_streams: a list of music stream URL; a random stream will be selected from the list. :raise ValueError: if any parameter is invalid """ if music_streams is None or len(music_streams) == 0: raise ValueError('musicUrls must be specified') self._music_streams = music_streams self._duration_in_minutes = duration_in_minutes self._in_session = False self._timer = None def on_action(self, event_info): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() activities = zone_manager.get_devices_by_type(ActivityTimes) if len(activities) == 0: self.log_warning("Missing ActivityTimes; can't determine if this is dinner time.") return False sink = get_nearby_audio_sink(zone, zone_manager) if sink is None: self.log_warning("Missing audio device; can't play music.") return False activity = activities[0] if activity.is_dinner_time(): if not self._in_session: sink.play_stream(random.choice(self._music_streams), 40) self._in_session = True def stop_music_session(): sink.pause() self._in_session = False self._timer = Timer(self._duration_in_minutes * 60, stop_music_session) self._timer.start() return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/play_music_at_dinner_time.py
play_music_at_dinner_time.py
from datetime import datetime from enum import unique, Enum from zone_api.audio_manager import get_nearby_audio_sink from zone_api.core.action import action from zone_api.core.devices.switch import Light from zone_api.core.event_info import EventInfo from zone_api.core.immutable_zone_manager import ImmutableZoneManager from zone_api.core.zone_event import ZoneEvent @action(events=[ZoneEvent.TIMER], zone_name_pattern='.*Kitchen.*') class TellKidsToGoToBed: """ If there is one or more lights turned on on the first floor, the first audio message asks kids to clean up and prepare to go to bed. The second message is played 5' later; all the lights on the first floor will be turned off. """ @unique class Type(Enum): FIRST_NOTICE = 1 SECOND_NOTICE = 2 def on_startup(self, event_info: EventInfo): # start timer here. Main logic remains in on_action. def first_notice_timer_handler(): if self._is_applicable(): self.on_action(self.create_timer_event_info(event_info, TellKidsToGoToBed.Type.FIRST_NOTICE)) def second_notice_timer_handler(): if self._is_applicable(): self.on_action(self.create_timer_event_info(event_info, TellKidsToGoToBed.Type.SECOND_NOTICE)) scheduler = event_info.get_zone_manager().get_scheduler() scheduler.every().day.at('19:45').do(first_notice_timer_handler) scheduler.every().day.at('19:50').do(second_notice_timer_handler) def on_action(self, event_info: EventInfo): zone = event_info.get_zone() zone_manager: ImmutableZoneManager = event_info.get_zone_manager() sink = get_nearby_audio_sink(zone, zone_manager) if sink is None: self.log_warning("Missing audio device; can't play music.") return False time_str = datetime.now().strftime("%I:%M") if event_info.get_custom_parameter() == TellKidsToGoToBed.Type.FIRST_NOTICE: sink.play_message( f'Kids, it is {time_str}; please put away everything and prepare to go upstairs.') else: sink.play_message(f'Kids, it is {time_str}; please go upstairs now.') foyer_zone = None for z in zone_manager.get_zones(): if z.get_level() == zone.get_level(): if "Foyer" in z.get_name(): foyer_zone = z else: z.turn_off_lights(event_info.get_event_dispatcher()) if foyer_zone is not None: for light in foyer_zone.get_devices_by_type(Light): light.turn_on(event_info.get_event_dispatcher()) return True # noinspection PyMethodMayBeStatic def _is_applicable(self): """ Returns true if the next day is a school day. """ now = datetime.now() if (0 <= now.weekday() < 4) or now.weekday() == 6: # Mon - Thursday and Sunday if now.month >= 9 or now.month <= 5: # Between Sept and June 20 return True elif now.month == 6: return now.day <= 20 return False
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/tell_kids_to_go_to_bed.py
tell_kids_to_go_to_bed.py
from zone_api.alert import Alert from zone_api.core.immutable_zone_manager import ImmutableZoneManager class RangeViolationAlert: """ Given a valid value range, track the state of the value, and send an warning alert when the value is out of range. Send another info alert when the value is back to the normal range. """ def __init__(self, min_value, max_value, notification_step_value=3, label="value", unit="", module=None, interval_between_alerts_in_minutes=-1, admin_alert=False): """ Ctor :param int min_value: the minimum good value :param int max_value: the maximum good value :param int notification_step_value: the value at which point a notification email will be sent. E.g. with the default maxValue of 50 and the step value of 3, the first notification is at 53, and the next one is 56. :param str label: the name of the value :param str unit: the unit of the value :raise ValueError: if any parameter is invalid """ if max_value <= min_value: raise ValueError('maxValue must be greater than minValue') if notification_step_value <= 0: raise ValueError('notificationStepValue must be positive') self.min_value = min_value self.max_value = max_value self.notification_step_value = notification_step_value self.label = label self.unit = unit self.module = module self.interval_between_alerts_in_minutes = interval_between_alerts_in_minutes self.adminAlert = admin_alert self.sent_alert = False self.next_max_notification_threshold = None self.next_min_notification_threshold = None self.reset_states() def update_state(self, value, zone, zone_manager: ImmutableZoneManager): """ Update this object with the latest value. If the value is outside the range, an warning alert will be sent. If the value is back to the normal range, an info alert will be sent. """ if self.min_value <= value <= self.max_value: if self.sent_alert: # send an info alert that the value is back to normal self.reset_states() msg = f'The {zone.get_name()} {self.label} at {value}{self.unit} is back to the normal range ' \ f'({self.min_value}% - {self.max_value}%).' alert = Alert.create_info_alert(msg) if self.adminAlert: zone_manager.get_alert_manager().process_admin_alert(alert) else: zone_manager.get_alert_manager().process_alert(alert) else: alert_message = '' if value <= self.next_min_notification_threshold: alert_message = f'The {zone.get_name()} {self.label} at {value}{self.unit} is below the ' \ f'threshold of {self.min_value}%.' self.next_min_notification_threshold -= self.notification_step_value elif value >= self.next_max_notification_threshold: alert_message = f'The {zone.get_name()} {self.label} at {value}{self.unit} is above the ' \ f'threshold of {self.max_value}%.' self.next_max_notification_threshold += self.notification_step_value if alert_message != '': alert = Alert.create_warning_alert(alert_message, None, [], self.module, self.interval_between_alerts_in_minutes) if self.adminAlert: zone_manager.get_alert_manager().process_admin_alert(alert) else: zone_manager.get_alert_manager().process_alert(alert) self.sent_alert = True def reset_states(self): """ Resets the internal states including the next min/max notification thresholds. """ self.next_max_notification_threshold = self.max_value + self.notification_step_value self.next_min_notification_threshold = self.min_value - self.notification_step_value self.sent_alert = False
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/range_violation_alert.py
range_violation_alert.py
from zone_api import security_manager as sm from zone_api.audio_manager import get_nearby_audio_sink from zone_api.audio_manager import get_main_audio_sink from zone_api.core.action import action from zone_api.core.devices.activity_times import ActivityTimes from zone_api.core.devices.chromecast_audio_sink import ChromeCastAudioSink from zone_api.core.event_info import EventInfo from zone_api.core.immutable_zone_manager import ImmutableZoneManager from zone_api.core.zone import Level from zone_api.core.zone_event import ZoneEvent @action(events=[ZoneEvent.TIMER], devices=[ChromeCastAudioSink], levels=[Level.FIRST_FLOOR]) class PlayMindfulnessBell: """ Play a bell sound every x minutes. This is a Zen Buddhist practice. When the bell rings, stop if possible and do a deep breath for a few times. """ BELL_URL = 'bell-outside.wav' BELL_DURATION_IN_SECS = 15 def on_startup(self, event_info: EventInfo): # start timer here. Main logic remains in on_action. def invoke_action(): self.on_action(self.create_timer_event_info(event_info)) scheduler = event_info.get_zone_manager().get_scheduler() scheduler.every(25).minutes.do(invoke_action) def on_action(self, event_info: EventInfo): zone = event_info.get_zone() zone_manager: ImmutableZoneManager = event_info.get_zone_manager() if sm.is_armed_away(zone_manager): return False activity = zone_manager.get_first_device_by_type(ActivityTimes) if activity is None: self.log_info("Missing activities time; can't play meditation bell.") return False sink = get_nearby_audio_sink(zone, zone_manager) if sink is None: self.log_warning("Missing audio device; can't play music.") return False if activity.is_sleep_time(): return False if activity.is_quiet_time(): volume = 40 else: volume = 60 sink = get_main_audio_sink(zone_manager) sink.play_sound_file(PlayMindfulnessBell.BELL_URL, PlayMindfulnessBell.BELL_DURATION_IN_SECS, volume) return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/play_mindfulness_bell.py
play_mindfulness_bell.py
import random from threading import Timer from typing import Union from zone_api.audio_manager import Genre, get_music_streams_by_genres, get_nearby_audio_sink from zone_api.core.devices.weather import Weather from zone_api.environment_canada import EnvCanada from zone_api.core.action import action from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.activity_times import ActivityTimes @action(events=[ZoneEvent.MOTION], external_events=[ZoneEvent.DOOR_CLOSED], devices=[MotionSensor], zone_name_pattern='.*Kitchen.*') class AnnounceMorningWeatherAndPlayMusic: """ Announces the current weather and plays a random music stream twice during the wake up period. This is based on the assumption of a household having two adults that leave work at different times. The music stops when the front door is closed. """ # noinspection PyDefaultArgument def __init__(self, music_streams=get_music_streams_by_genres( [Genre.CLASSICAL, Genre.INSTRUMENT, Genre.JAZZ]), duration_in_minutes: float = 120, max_start_count: int = 2): """ Ctor :param list[str] music_streams: a list of music stream URL; a random stream will be selected from the list. :raise ValueError: if any parameter is invalid """ if music_streams is None or len(music_streams) == 0: raise ValueError('musicUrls must be specified') self._music_streams = music_streams self._max_start_count = max_start_count self._duration_in_minutes = duration_in_minutes self._in_session = False self._start_count = 0 self._timer = None self._sink = None def on_action(self, event_info): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() activity = zone_manager.get_first_device_by_type(ActivityTimes) if activity is None: self.log_warning("Missing ActivityTimes; can't determine if this is morning time.") return False def stop_music_session(): self._sink.pause() self._in_session = False if event_info.get_event_type() == ZoneEvent.DOOR_CLOSED: if self._in_session: owning_zone = event_info.get_owning_zone() if owning_zone.is_external(): stop_music_session() return True return False else: self._sink = get_nearby_audio_sink(zone, zone_manager) if self._sink is None: self.log_warning("Missing audio device; can't play music.") return False if activity.is_wakeup_time() and \ not self._in_session and \ self._start_count < self._max_start_count: self._in_session = True weather_msg = self.get_morning_announcement(zone_manager) if weather_msg is not None: self._sink.play_message(weather_msg) self._sink.play_stream(random.choice(self._music_streams), 40) self._start_count += 1 def reset_state(): stop_music_session() self._sink = None self._start_count = 0 if self._timer is not None and self._timer.is_alive(): self._timer.cancel() self._timer = Timer(self._duration_in_minutes * 60, reset_state) self._timer.start() return True # noinspection PyMethodMayBeStatic def get_morning_announcement(self, zone_manager) -> Union[None, str]: """ Returns a string containing the current's weather and today's forecast. """ weather = zone_manager.get_first_device_by_type(Weather) if weather is None or not weather.support_forecast_min_temperature() \ or not weather.support_forecast_max_temperature(): return None message = u'Good morning. It is {} degree currently; the weather ' \ 'condition is {}. Forecasted temperature range is between {} and {} ' \ 'degrees.'.format(weather.get_temperature(), weather.get_condition(), weather.get_forecast_min_temperature(), weather.get_forecast_max_temperature()) forecasts = EnvCanada.retrieve_hourly_forecast('Ottawa', 12) rain_periods = [f for f in forecasts if 'High' == f.get_precipitation_probability() or 'Medium' == f.get_precipitation_probability()] if len(rain_periods) > 0: if len(rain_periods) == 1: message += u" There will be precipitation at {}.".format( rain_periods[0].get_user_friendly_forecast_time()) else: message += u" There will be precipitation from {} to {}.".format( rain_periods[0].get_user_friendly_forecast_time(), rain_periods[-1].get_user_friendly_forecast_time()) return message
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/announce_morning_weather_and_play_music.py
announce_morning_weather_and_play_music.py
from zone_api.alert_manager import * from zone_api.core.devices.alarm_partition import AlarmPartition from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.devices.camera import Camera from zone_api.core.devices.contact import Door from zone_api import platform_encapsulator as pe @action(events=[ZoneEvent.MOTION], devices=[Camera], internal=False, external=True) class AlertOnEntranceActivity: """ The alert is triggered from a PIR motion sensor. The motion sensor sometimes generate false positive event. This is remedied by determining if the camera also detects motion (through the image differential). If both the PIR sensor and the camera detect motions, sends an alert if the system is armed-away or if the activity is during the night. The alert is suppressed if the zone's door was just opened. This indicates the occupant walking out of the house, and thus shouldn't triggered the event. """ def __init__(self): pass def on_action(self, event_info): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() current_epoch = time.time() door_open_period_in_seconds = 10 for door in zone.get_devices_by_type(Door): if door.was_recently_activated(door_open_period_in_seconds): pe.log_info("A door was just open for zone {}; ignore motion event.".format( zone.get_name())) return cameras = zone.get_devices_by_type(Camera) if len(cameras) == 0: pe.log_info("No camera found for zone {}".format(zone.get_name())) return camera = cameras[0] if not camera.has_motion_event(): pe.log_info("Camera doesn't indicate motion event; likely a false positive PIR event.") return time.sleep(10) # wait for a bit to retrieve more images offset_seconds = 5 max_number_of_seconds = 15 attachment_urls = camera.get_snapshot_urls(current_epoch, max_number_of_seconds, offset_seconds) if len(attachment_urls) > 0: time_struct = time.localtime() hour = time_struct[3] msg = 'Activity detected at the {} area.'.format( zone.get_name(), len(attachment_urls)) armed_away = False security_partitions = zone_manager.get_devices_by_type(AlarmPartition) if len(security_partitions) > 0 and security_partitions[0].is_armed_away(): armed_away = True if armed_away or hour <= 6: alert = Alert.create_warning_alert(msg, None, attachment_urls) else: alert = Alert.create_audio_warning_alert(msg) zone_manager.get_alert_manager().process_alert(alert) return True else: pe.log_info("No images from {} camera.".format(zone.get_name())) return False
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/alert_on_entrance_activity.py
alert_on_entrance_activity.py
from enum import unique, Enum from zone_api.alert import Alert from zone_api import platform_encapsulator as pe from zone_api.core.event_info import EventInfo from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action @action(events=[ZoneEvent.TIMER], devices=[], zone_name_pattern='.*Virtual.*') class AlertOnInactiveDevices: """ Send an admin info alert if a battery-powered or an auto-report device hasn't got any update in the specified duration. There are different thresholds for these types of devices as battery-powered devices tend to not auto-report (cause rapid battery drain). As such, the inactivity timer for those devices are much bigger than for auto-report devices. """ @unique class Type(Enum): BATTERY_DEVICES = 1 AUTO_REPORT_WIFI_DEVICES = 2 def __init__(self, battery_powered_period_in_hours: float = 3 * 24, auto_report_period_in_hours: float = 0.25): """ Ctor :raise ValueError: if any parameter is invalid """ if battery_powered_period_in_hours <= 0: raise ValueError('battery_powered_period_in_hours must be positive') if auto_report_period_in_hours <= 0: raise ValueError('auto_report_period_in_hours must be positive') self._battery_powered_period_in_hours = battery_powered_period_in_hours self._auto_report_period_in_hours = auto_report_period_in_hours def on_startup(self, event_info: EventInfo): def battery_device_timer_handler(): self.on_action( self.create_timer_event_info(event_info, AlertOnInactiveDevices.Type.BATTERY_DEVICES)) def auto_report_device_timer_handler(): self.on_action( self.create_timer_event_info(event_info, AlertOnInactiveDevices.Type.AUTO_REPORT_WIFI_DEVICES)) scheduler = event_info.get_zone_manager().get_scheduler() scheduler.every(self._battery_powered_period_in_hours).hours.do(battery_device_timer_handler) scheduler.every(self._auto_report_period_in_hours).hours.do(auto_report_device_timer_handler) def on_action(self, event_info): zone_manager = event_info.get_zone_manager() if event_info.get_custom_parameter() == AlertOnInactiveDevices.Type.BATTERY_DEVICES: self._check_and_send_alert(zone_manager, self.get_inactive_battery_devices, "battery", self._battery_powered_period_in_hours) elif event_info.get_custom_parameter() == AlertOnInactiveDevices.Type.AUTO_REPORT_WIFI_DEVICES: self._check_and_send_alert(zone_manager, self.get_inactive_auto_report_devices, "auto-report WiFi", self._auto_report_period_in_hours) else: raise RuntimeError("Invalid state.") return True # noinspection PyMethodMayBeStatic def _check_and_send_alert(self, zone_manager, check_function, device_type_string, threshold_in_hours): inactive_devices = check_function(zone_manager, threshold_in_hours * 3600) if len(inactive_devices) > 0: subject = "{} inactive {} devices".format( len(inactive_devices), device_type_string) body = f"The following devices haven't triggered in the last {threshold_in_hours} hours\r\n - " body += "\r\n - ".join(inactive_devices) alert = Alert.create_info_alert(subject, body) zone_manager.get_alert_manager().process_admin_alert(alert) else: pe.log_info(f"No inactive {device_type_string} devices detected.") # noinspection PyMethodMayBeStatic def get_inactive_battery_devices(self, zone_manager, threshold_in_seconds): """ :rtype: list(str) the list of inactive devices """ inactive_device_name = [] for z in zone_manager.get_zones(): battery_devices = [d for d in z.get_devices() if d.is_battery_powered()] for d in battery_devices: if not d.was_recently_activated(threshold_in_seconds): inactive_device_name.append(f"{z.get_name()}: {d.get_item_name()}") return inactive_device_name # noinspection PyMethodMayBeStatic def get_inactive_auto_report_devices(self, zone_manager, threshold_in_seconds): """ :rtype: list(str) the list of auto-reported WiFi devices that haven't sent anything in the specified number of seconds. """ inactive_device_name = [] for z in zone_manager.get_zones(): auto_report_devices = [d for d in z.get_devices() if d.is_auto_report()] for d in auto_report_devices: if not d.was_recently_activated(threshold_in_seconds): inactive_device_name.append(f"{z.get_name()}: {d.get_item_name()}") return inactive_device_name
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/alert_on_inactive_devices.py
alert_on_inactive_devices.py
from zone_api.alert import Alert from zone_api.core.event_info import EventInfo from zone_api.core.zone_event import ZoneEvent from zone_api.environment_canada import EnvCanada from zone_api import platform_encapsulator as pe from zone_api.core.action import action @action(events=[ZoneEvent.TIMER], devices=[], zone_name_pattern='.*Virtual.*') class AlertOnRainOrSnowDuringTheDay: def __init__(self, city: str = 'Ottawa'): self._city = city def on_startup(self, event_info: EventInfo): # start timer here. Main logic remains in on_action. def timer_handler(): self.on_action(self.create_timer_event_info(event_info)) weekday_time = '06:15' weekend_time = '08:00' scheduler = event_info.get_zone_manager().get_scheduler() scheduler.every().monday.at(weekday_time).do(timer_handler) scheduler.every().tuesday.at(weekday_time).do(timer_handler) scheduler.every().wednesday.at(weekday_time).do(timer_handler) scheduler.every().thursday.at(weekday_time).do(timer_handler) scheduler.every().friday.at(weekday_time).do(timer_handler) scheduler.every().saturday.at(weekend_time).do(timer_handler) scheduler.every().sunday.at(weekend_time).do(timer_handler) def on_action(self, event_info: EventInfo): forecasts = EnvCanada.retrieve_hourly_forecast(self._city, 12) rain_periods = [f for f in forecasts if 'High' == f.get_precipitation_probability() or 'Medium' == f.get_precipitation_probability()] if len(rain_periods) > 0: if len(rain_periods) == 1: subject = u"Possible precipitation at {}".format( rain_periods[0].get_user_friendly_forecast_time()) else: subject = u"Possible precipitation from {} to {}".format( rain_periods[0].get_user_friendly_forecast_time(), rain_periods[-1].get_user_friendly_forecast_time()) body = u'Forecasts:\n' body += u"{:5} {:7} {:25} {:6} {:6}\n".format('Hour: ', 'Celsius', 'Condition', 'Prob.', 'Wind') for f in forecasts: body += str(f) + '\n' alert_message = Alert.create_info_alert(subject, body) zm = event_info.get_zone_manager() result = zm.get_alert_manager().process_alert(alert_message, zm) if not result: pe.log_info('Failed to send rain/snow alert') return True else: pe.log_info('There is no rain/snow today.') return False
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/alert_on_rain_or_snow_during_the_day.py
alert_on_rain_or_snow_during_the_day.py
from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.actions.range_violation_alert import RangeViolationAlert from zone_api.core.devices.temperature_sensor import TemperatureSensor @action(events=[ZoneEvent.TEMPERATURE_CHANGED], devices=[TemperatureSensor], internal=True, unique_instance=True) class AlertOnTemperatureOutOfRange: """ Send an warning alert if the temperature is outside the range. @see RangeViolationAlert. """ def __init__(self, min_temperature=16, max_temperature=30, notification_step_value=2): """ Ctor :param int min_temperature: the minimum temperature in percentage. :param int max_temperature: the maximum temperature in percentage. :param int notification_step_value: the value at which point a notification email will be sent. E.g. with the default maxTemperature of 50 and the step value of 3, the first notification is at 53, and the next one is 56. :raise ValueError: if any parameter is invalid """ if min_temperature <= 0: raise ValueError('minTemperature must be positive') if max_temperature <= 0: raise ValueError('maxTemperature must be positive') if max_temperature <= min_temperature: raise ValueError('maxTemperature must be greater than minTemperature') if notification_step_value <= 0: raise ValueError('notificationStepValue must be positive') self.rangeAlert = RangeViolationAlert(min_temperature, max_temperature, notification_step_value, "temperature", "C", "TEMPERATURE", 30, False) def on_action(self, event_info): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() percentage = event_info.get_device().get_temperature() self.rangeAlert.update_state(percentage, zone, zone_manager) return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/alert_on_temperature_out_of_range.py
alert_on_temperature_out_of_range.py
from zone_api.alert import Alert from zone_api.core.devices.computer import Computer from zone_api.core.event_info import EventInfo from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api import platform_encapsulator as pe @action(events=[ZoneEvent.COMPUTER_CPU_TEMPERATURE_CHANGED, ZoneEvent.COMPUTER_GPU_TEMPERATURE_CHANGED], devices=[Computer], unique_instance=True) class AlertOnBadComputerStates: """ Send a critical alert if a bad state is detected. """ def __init__(self, max_cpu_temperature_in_degree=70, max_gpu_temperature_in_degree=70, interval_between_alerts_in_minutes=15): """ Ctor :raise ValueError: if any parameter is invalid """ if max_cpu_temperature_in_degree <= 0: raise ValueError('max_cpu_temperature_in_degree must be positive') if max_gpu_temperature_in_degree <= 0: raise ValueError('max_gpu_temperature_in_degree must be positive') if interval_between_alerts_in_minutes <= 0: raise ValueError('intervalBetweenAlertsInMinutes must be positive') self._thresholds = [max_cpu_temperature_in_degree, max_gpu_temperature_in_degree] self._notified = [False, False] self._names = ["CPU", "GPU"] self._interval_between_alerts_in_minutes = interval_between_alerts_in_minutes def on_action(self, event_info: EventInfo): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() computer: Computer = zone.get_device_by_event(event_info) if event_info.get_event_type() == ZoneEvent.COMPUTER_CPU_TEMPERATURE_CHANGED: self._process_event(zone_manager, zone, computer, computer.get_cpu_temperature(), 0) elif event_info.get_event_type() == ZoneEvent.COMPUTER_GPU_TEMPERATURE_CHANGED: self._process_event(zone_manager, zone, computer, computer.get_gpu_temperature(), 1) else: return False return True def _process_event(self, zone_manager, zone, computer, temperature, index: int): if temperature > self._thresholds[index]: self._notified_cpu_temperature = True alert_message = f'{self._names[index]} temperature for {computer.get_item_name()} at {temperature} ' \ f'is above the threshold of {self._thresholds[index]} degree. ' alert_module = alert_message alert = Alert.create_critical_alert(alert_message, None, [], alert_module, self._interval_between_alerts_in_minutes) zone_manager.get_alert_manager().process_alert(alert, zone_manager) self._notified[index] = True elif self._notified[index]: alert_message = f'{self._names[index]} temperature for {computer.get_item_name()} is back to normal' alert = Alert.create_info_alert(alert_message) zone_manager.get_alert_manager().process_alert(alert, zone_manager) self._notified[index] = False
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/alert_on_bad_computer_states.py
alert_on_bad_computer_states.py
import random from threading import Timer from zone_api import platform_encapsulator as pe from zone_api import security_manager as sm from zone_api.audio_manager import MusicStreams, get_main_audio_sink from zone_api.core.action import action from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.activity_times import ActivityTimes @action(events=[ZoneEvent.MOTION], devices=[MotionSensor], internal=False, external=True) class SimulateDaytimePresence: """ Play the provided URL stream when an external motion sensor is triggered and while the system is in arm-away mode, and when it is not sleep time. @todo: use local URL to avoid reliance on the Internet connection. """ def __init__(self, music_url=MusicStreams.CLASSIC_ROCK_FLORIDA.value.url, music_volume=90, play_duration_in_seconds: float = None): """ Ctor :param str music_url: :param int music_volume: percentage from 0 to 100 :param int play_duration_in_seconds: how long the music will be played. \ If not specified, this value will be generated randomly. :raise ValueError: if any parameter is invalid """ if music_url is None: raise ValueError('musicUrl must be specified') self.music_url = music_url self.music_volume = music_volume self.play_duration_in_seconds = play_duration_in_seconds self.timer = None def on_action(self, event_info): zone_manager = event_info.get_zone_manager() if not sm.is_armed_away(zone_manager): return False audio_sink = get_main_audio_sink(zone_manager) if audio_sink is None: pe.log_info(f"{self.__module__} - No audio sink available") return False activities = zone_manager.get_devices_by_type(ActivityTimes) if len(activities) > 0: if activities[0].is_sleep_time(): return False audio_sink.play_stream(self.music_url, self.music_volume) if self.timer is not None: self.timer.cancel() duration_in_seconds = self.play_duration_in_seconds if duration_in_seconds is None: duration_in_seconds = random.randint(3 * 60, 10 * 60) self.timer = Timer(duration_in_seconds, lambda: audio_sink.pause()) self.timer.start() pe.log_info(f"{self.__module__} - playing music for {duration_in_seconds} seconds") return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/simulate_daytime_presence.py
simulate_daytime_presence.py
from threading import Timer from zone_api.alert import Alert from zone_api.core.devices.plug import Plug from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.devices.alarm_partition import AlarmPartition from zone_api.core.devices.contact import Door from zone_api import platform_encapsulator as pe @action(events=[ZoneEvent.DOOR_CLOSED], devices=[Door], internal=False, external=True) class ArmAfterFrontDoorClosed: """ Automatically arm the house if a front door was closed and there was no activity in the house for x number of seconds. Once armed, an alert will be sent out. """ def __init__(self, max_elapsed_time_in_seconds: float = 15 * 60): """ Ctor :param int max_elapsed_time_in_seconds: the elapsed time in second since a door has been closed at which point the timer will determine if there was any previous activity in the house. If not, the security system is armed. Note that a motion sensor might not switched to OFF until a few minutes later; do take this into consideration. :raise ValueError: if any parameter is invalid """ if max_elapsed_time_in_seconds <= 0: raise ValueError('maxElapsedTimeInSeconds must be positive') self.timer = None self.max_elapsed_time_in_seconds = max_elapsed_time_in_seconds def on_action(self, event_info): events = event_info.get_event_dispatcher() zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() if zone.get_name() == "Patio": # todo: add Zone::isBack() return False security_partitions = zone_manager.get_devices_by_type(AlarmPartition) if len(security_partitions) == 0: return False if not security_partitions[0].is_unarmed(): return False for door in zone.get_devices_by_type(Door): if door.is_closed(): if self.timer is not None: self.timer.cancel() def arm_and_send_alert(): occupied = False active_device = None for z in zone_manager.get_zones(): if z.is_external(): continue (occupied, active_device) = z.is_occupied([Plug], self.max_elapsed_time_in_seconds) if occupied: break if occupied: pe.log_info('Auto-arm cancelled (activities detected @ {}).'.format( active_device)) else: security_partitions[0].arm_away(events) msg = 'The house has been automatically armed-away (front door closed and no activity)' alert = Alert.create_warning_alert(msg) zone_manager.get_alert_manager().process_alert(alert, zone_manager) self.timer = Timer(self.max_elapsed_time_in_seconds, arm_and_send_alert) self.timer.start() return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/arm_after_front_door_closed.py
arm_after_front_door_closed.py
from zone_api import security_manager as sm from zone_api.core.devices.activity_times import ActivityTimes from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.devices.network_presence import NetworkPresence from zone_api.core.event_info import EventInfo from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.devices.alarm_partition import AlarmPartition @action(events=[ZoneEvent.TIMER], devices=[AlarmPartition, MotionSensor]) class ArmIfNoMovement: """ Automatically arm-stay the house if there has been no occupancy event in the last x minutes. Use case: user is at home but perhaps taking a nap. Accompanied disarm rule will automatically disarm on internal motion sensor. If the house is in vacation mode, arm away instead. """ def __init__(self, unoccupied_duration_in_minutes=30): self._unoccupied_duration_in_minutes = unoccupied_duration_in_minutes def on_startup(self, event_info: EventInfo): scheduler = event_info.get_zone_manager().get_scheduler() scheduler.every(15).minutes.do(lambda: self.on_action(self.create_timer_event_info(event_info))) def on_action(self, event_info): events = event_info.get_event_dispatcher() zone_manager = event_info.get_zone_manager() if not sm.is_unarmed(zone_manager): return False activity = zone_manager.get_first_device_by_type(ActivityTimes) if activity is None: self.log_warning("Missing activities time; can't determine wake-up time.") return False if activity.is_auto_arm_stay_time(): # taken care by another deterministic rule. return False for z in zone_manager.get_zones(): (occupied, device) = z.is_occupied([NetworkPresence], self._unoccupied_duration_in_minutes * 60) if occupied: return False if zone_manager.is_in_vacation(): sm.arm_away(zone_manager, events) else: sm.arm_stay(zone_manager, events) return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/arm_if_no_movement.py
arm_if_no_movement.py
import time from functools import reduce from zone_api import platform_encapsulator as pe from zone_api.core.action import action from zone_api.core.event_info import EventInfo from zone_api.core.immutable_zone_manager import ImmutableZoneManager from zone_api.core.zone_event import ZoneEvent from zone_api.core.neighbor import NeighborType from zone_api.core.devices.switch import Light, Switch, Fan from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.actions.turn_off_adjacent_zones import TurnOffAdjacentZones DEBUG = False @action(events=[ZoneEvent.MOTION], devices=[Switch], internal=True, external=True, priority=1) class TurnOnSwitch: """ Turns on a switch (fan, dimmer or regular light), after being triggered by a motion event. If the switch is a dimmer or light, it is only turned on if: 1. It is evening time, or 2. The illuminance is below a threshold. A light/dimmer switch won't be turned on if: 1. The light has the flag set to ignore motion event, or 2. The adjacent zone is of type OPEN_SPACE_MASTER with the light on, or 3. The light was just turned off, or 4. The neighbor zone has a light switch that shares the same motion sensor, and that light switch was just recently turned off. No matter whether the switch is turned on or not (see the condition above), any adjacent zones of type OPEN_SPACE, and OPEN_SPACE_SLAVE that currently has the light on, will be sent a command to shut off the light. """ DELAY_AFTER_LAST_OFF_TIME_IN_SECONDS = 8 """ The period of time in seconds (from the last timestamp a switch was turned off) to ignore the motion sensor event. This takes care of the scenario when the user manually turns off a light, but that physical spot is covered by a motion sensor, which immediately turns on the light again. """ # noinspection PyMethodMayBeStatic def on_action(self, event_info: EventInfo): events = event_info.get_event_dispatcher() zone = event_info.get_zone() zone_manager: ImmutableZoneManager = event_info.get_zone_manager() motion_sensor: MotionSensor = event_info.get_device() is_processed = False can_turn_off_adjacent_zones = True light_on_time = zone_manager.is_light_on_time() zone_illuminance = zone.get_illuminance_level() switch = None zone_switches = zone.get_devices_by_type(Switch) for switch in zone_switches: if switch.is_on(): switch.turn_on(events) # renew the timer if a switch is already on is_processed = True can_turn_off_adjacent_zones = False continue if not motion_sensor.can_trigger_switches(): # A special case: if a switch is configured not to be # triggered by a motion sensor, it means there is # already another switch sharing that motion sensor. In this case, we # don't want to turn off the # other switch. can_turn_off_adjacent_zones = False if DEBUG: pe.log_info("{}: rejected - can't be triggered by motion sensor".format( switch.get_item_name())) continue # Break if switch was just turned off. if switch.get_last_off_timestamp_in_seconds() is not None: if (time.time() - switch.get_last_off_timestamp_in_seconds()) <= \ TurnOnSwitch.DELAY_AFTER_LAST_OFF_TIME_IN_SECONDS: if DEBUG: pe.log_info("{}: rejected - switch was just turned off".format( switch.get_item_name())) continue # Break if the switch of a neighbor sharing the motion sensor was # just turned off. open_space_zones = [zone_manager.get_zone_by_id(n.get_zone_id()) for n in zone.get_neighbors() if n.is_open_space()] shared_motion_sensor_zones = [z for z in open_space_zones if zone.share_sensor_with(z, MotionSensor)] their_switches = reduce(lambda a, b: a + b, [z.get_devices_by_type(Switch) for z in shared_motion_sensor_zones], []) if any(time.time() - s.get_last_off_timestamp_in_seconds() <= TurnOnSwitch.DELAY_AFTER_LAST_OFF_TIME_IN_SECONDS for s in their_switches): if DEBUG: pe.log_info("{}: rejected - can't be triggered by motion sensor".format( switch.get_item_name())) continue if isinstance(switch, Light): if light_on_time or switch.is_low_illuminance(zone_illuminance): is_processed = True if is_processed and zone_manager is not None: master_zones = [zone_manager.get_zone_by_id(n.get_zone_id()) for n in zone.get_neighbors() if NeighborType.OPEN_SPACE_MASTER == n.get_type()] if any(z.is_light_on() for z in master_zones): is_processed = False # This scenario indicates that there is already # activity in the master zone, and thus such activity # must not prematurely turns off the light in the # adjacent zone. can_turn_off_adjacent_zones = False if DEBUG: pe.log_info("{}: rejected - a master zone's light is on".format( switch.get_item_name())) if is_processed: switch.turn_on(events) else: switch.turn_on(events) is_processed = True # Special case when the zone has only fans; must not turn off adjacent lights. if can_turn_off_adjacent_zones: fans = zone.get_devices_by_type(Fan) if len(zone_switches) == len(fans): can_turn_off_adjacent_zones = False # Now shut off the light in any shared space zones if can_turn_off_adjacent_zones: if DEBUG: pe.log_info("{}: turning off adjacent zone's light".format( switch.get_item_name())) off_event_info = EventInfo(ZoneEvent.SWITCH_TURNED_ON, event_info.get_item(), event_info.get_zone(), event_info.get_zone_manager(), event_info.get_event_dispatcher()) turn_off_action = TurnOffAdjacentZones().disable_filtering() turn_off_action.on_action(off_event_info) return is_processed
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/turn_on_switch.py
turn_on_switch.py
from threading import Timer from zone_api.alert import Alert from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.devices.contact import Door @action(events=[ZoneEvent.DOOR_OPEN, ZoneEvent.DOOR_CLOSED], devices=[Door], internal=False, external=True) class AlertOnExternalDoorLeftOpen: """ Send an warning alert if a door on an external zone has been left open for a period of time. Triggered when a door is open (--> start the timer), or when a door is closed (--> stop the timer) """ def __init__(self, max_elapsed_time_in_seconds: float = 15 * 60): """ Ctor :param int max_elapsed_time_in_seconds: the elapsed time in second since a door has been open, and at which point an alert will be sent :raise ValueError: if any parameter is invalid """ if max_elapsed_time_in_seconds <= 0: raise ValueError('maxElapsedTimeInSeconds must be positive') self.timers = {} self.maxElapsedTimeInSeconds = max_elapsed_time_in_seconds def on_action(self, event_info): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() def send_alert(): alert_message = 'The {} door has been opened for {} minutes.'.format( zone.get_name(), int(self.maxElapsedTimeInSeconds / 60)) zone_manager.get_alert_manager().process_alert(Alert.create_warning_alert(alert_message), zone_manager) for door in zone.get_devices_by_type(Door): timer = self.timers[door] if door in self.timers else None if door.is_open(): if timer is not None: timer.cancel() del self.timers[door] timer = Timer(self.maxElapsedTimeInSeconds, send_alert) timer.start() self.timers[door] = timer else: if timer is not None: if timer.is_alive(): timer.cancel() else: # alert door now closed if a warning was previous sent msg = f'The {zone.get_name()} door is now closed.' alert = Alert.create_warning_alert(msg) zone_manager.get_alert_manager().process_alert(alert, zone_manager) del self.timers[door] return True def has_running_timer(self): """ Returns true if at least one timer is running. """ return any(t.is_alive() for t in self.timers.values())
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/alert_on_external_door_left_open.py
alert_on_external_door_left_open.py
import random from threading import Timer from zone_api import platform_encapsulator as pe from zone_api.core.action import action from zone_api.core.devices.astro_sensor import AstroSensor from zone_api.core.devices.switch import Light from zone_api.core.event_info import EventInfo from zone_api.core.immutable_zone_manager import ImmutableZoneManager from zone_api.core.zone_event import ZoneEvent ON_EVENTS = [ZoneEvent.VACATION_MODE_ON, ZoneEvent.ASTRO_LIGHT_ON] OFF_EVENTS = [ZoneEvent.ASTRO_LIGHT_OFF, ZoneEvent.ASTRO_BED_TIME, ZoneEvent.VACATION_MODE_OFF] DISPLAY_ITEM_NAME = 'Out_Light_Simulation' @action(events=ON_EVENTS + OFF_EVENTS, external_events=ON_EVENTS + OFF_EVENTS, devices=[AstroSensor]) class SimulateNighttimePresence: """ When on vacation mode, after the sunset and before bed time, randomly turn on a managed light for a random period. After the period expires, randomly select another light (could be the same one again) and turn it on. Repeat this process until the vacation mode ends or until bed time. If the OH switch item DISPLAY_ITEM_NAME is present, set its value to True if light simulation is running. """ def __init__(self, min_light_on_duration_in_minutes=3, max_light_on_duration_in_minutes=8): """ Ctor """ self.min_light_on_duration_in_minutes = min_light_on_duration_in_minutes self.max_light_on_duration_in_minutes = max_light_on_duration_in_minutes # noinspection PyTypeChecker self.timer: Timer = None # noinspection PyTypeChecker self.light: Light = None self.iteration_count = 0 # for unit testing; how many times we have looped. # noinspection PyMethodMayBeStatic def on_action(self, event_info: EventInfo): zm: ImmutableZoneManager = event_info.get_zone_manager() if event_info.get_event_type() in ON_EVENTS: if not zm.is_light_on_time() or not zm.is_in_vacation(): return False def turn_on_random_light(): self.iteration_count += 1 if self.light is not None: # turn off the previous light. self.light.turn_off(event_info.get_event_dispatcher()) self.light = random.choice(zm.get_devices_by_type(Light)) self.light.turn_on(event_info.get_event_dispatcher()) duration_in_seconds = random.randint(self.min_light_on_duration_in_minutes * 60, self.max_light_on_duration_in_minutes * 60) self.log_info(f"turning on {self.light.get_item_name()} for " f"{int(duration_in_seconds / 60)} minutes") if not zm.is_light_on_time() or not zm.is_in_vacation(): return self.timer = Timer(duration_in_seconds, turn_on_random_light) self.timer.start() if self.timer is None: # is simulation is already running self.log_info("Starting light simulation.") turn_on_random_light() if pe.has_item(DISPLAY_ITEM_NAME): pe.set_switch_state(DISPLAY_ITEM_NAME, True) else: # events to turn off simulation mode self.cancel_timer() if self.light is not None: self.light.turn_off(event_info.get_event_dispatcher()) self.light = None return True def cancel_timer(self): if self.timer is not None: self.timer.cancel() self.timer = None self.iteration_count = 0 self.log_info("Canceled light simulation mode.") if pe.has_item(DISPLAY_ITEM_NAME): pe.set_switch_state(DISPLAY_ITEM_NAME, False)
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/simulate_nighttime_presence.py
simulate_nighttime_presence.py
from zone_api.core.devices.activity_times import ActivityTimes from zone_api.core.devices.motion_sensor import MotionSensor from zone_api.core.devices.plug import Plug from zone_api.core.event_info import EventInfo from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.devices.alarm_partition import AlarmPartition @action(events=[ZoneEvent.TIMER, ZoneEvent.MOTION, ZoneEvent.PARTITION_ARMED_AWAY, ZoneEvent.PARTITION_DISARMED_FROM_AWAY], devices=[AlarmPartition, MotionSensor]) class ManagePlugs: """ Turns off the plugs if the house is armed-away or if it is evening time (via ActivityTimes). Turn on the plug on the first motion sensor trigger during wake-up time period, or when the house is disarmed (from armed-away) NOT during the turn-off-plugs time period. """ def on_startup(self, event_info: EventInfo): # start timer here. Main logic remains in on_action. def timer_handler(): self.on_action(self.create_timer_event_info(event_info)) scheduler = event_info.get_zone_manager().get_scheduler() scheduler.every().hour.at(':00').do(timer_handler) scheduler.every().hour.at(':15').do(timer_handler) scheduler.every().hour.at(':30').do(timer_handler) scheduler.every().hour.at(':45').do(timer_handler) def on_action(self, event_info: EventInfo): events = event_info.get_event_dispatcher() zm = event_info.get_zone_manager() activities = zm.get_devices_by_type(ActivityTimes) if len(activities) == 0: self.log_warning("Missing activities time; can't determine turn-off-plugs time.") return False activity: ActivityTimes = activities[0] zone_event = event_info.get_event_type() if zone_event == ZoneEvent.TIMER: if activity.is_turn_off_plugs_time(): for z in zm.get_zones(): occupied, device = z.is_occupied([Plug]) if not occupied: for p in z.get_devices_by_type(Plug): if not p.is_always_on(): p.turn_off(events) return True elif zone_event == ZoneEvent.MOTION: if activity.is_wakeup_time(): for p in zm.get_devices_by_type(Plug): p.turn_on(events) return True elif zone_event == ZoneEvent.PARTITION_ARMED_AWAY: for p in zm.get_devices_by_type(Plug): if not p.is_always_on(): p.turn_off(events) return True elif zone_event == ZoneEvent.PARTITION_DISARMED_FROM_AWAY: if not activity.is_turn_off_plugs_time(): for p in zm.get_devices_by_type(Plug): p.turn_on(events) return True else: return False
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/manage_plugs.py
manage_plugs.py
from zone_api.core.zone import Level from zone_api.core.zone_event import ZoneEvent from zone_api.core.action import action from zone_api.core.actions.range_violation_alert import RangeViolationAlert from zone_api.core.devices.humidity_sensor import HumiditySensor @action(events=[ZoneEvent.HUMIDITY_CHANGED], devices=[HumiditySensor], internal=True, levels=[Level.FIRST_FLOOR], unique_instance=True) class AlertOnHumidityOutOfRange: """ Send an warning alert if the humidity is outside the range. @see RangeViolationAlert. """ def __init__(self, min_humidity: int = 35, max_humidity: int = 50, notification_step_value: int = 3): """ Ctor :param int min_humidity: the minimum humidity in percentage. :param int max_humidity: the maximum humidity in percentage. :param int notification_step_value: the value at which point a notification email will be sent. E.g. with the default maxHumidity of 50 and the step value of 3, the first notification is at 53, and the next one is 56. :raise ValueError: if any parameter is invalid """ if min_humidity <= 0: raise ValueError('minHumidity must be positive') if max_humidity <= 0: raise ValueError('maxHumidity must be positive') if max_humidity <= min_humidity: raise ValueError('maxHumidity must be greater than minHumidity') if notification_step_value <= 0: raise ValueError('notificationStepValue must be positive') self.rangeAlert = RangeViolationAlert(min_humidity, max_humidity, notification_step_value, "humidity", "%", "HUMIDITY", 60, True) def on_action(self, event_info): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() percentage = event_info.get_device().get_humidity() self.rangeAlert.update_state(percentage, zone, zone_manager) return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/alert_on_humidity_out_of_range.py
alert_on_humidity_out_of_range.py
import random from zone_api.audio_manager import get_nearby_audio_sink, get_music_streams_by_genres from zone_api.core.action import action from zone_api.core.devices.switch import Fan from zone_api.core.zone_event import ZoneEvent from zone_api.core.devices.activity_times import ActivityTimes from zone_api.music_streams import Genre, MusicStreams @action(events=[ZoneEvent.SWITCH_TURNED_ON, ZoneEvent.SWITCH_TURNED_OFF], devices=[Fan]) class PlayMusicDuringShower: """ Play the provided URL stream when the washroom fan is turned on. Pause when it it turned off. Won't play if it is sleep time. Otherwise, adjust the volume based on the current activity. """ # noinspection PyDefaultArgument def __init__(self, music_streams=[m.value for m in list(MusicStreams)]): """ Ctor :param str music_streams: list of music streams :raise ValueError: if any parameter is invalid """ if music_streams is None or len(music_streams) == 0: raise ValueError('music_streams must be specified') self._music_streams = music_streams def on_action(self, event_info): zone = event_info.get_zone() zone_manager = event_info.get_zone_manager() sink = get_nearby_audio_sink(zone, zone_manager) if sink is None: self.log_warning("Missing audio device; can't play music.") return False activity = None if zone_manager is not None: activities = zone_manager.get_devices_by_type(ActivityTimes) if len(activities) > 0: activity = activities[0] if activity.is_sleep_time(): return False if ZoneEvent.SWITCH_TURNED_ON == event_info.get_event_type(): volume = 25 if (activity is not None and activity.is_quiet_time()) else 35 sink.play_stream(random.choice(self._music_streams), volume) elif ZoneEvent.SWITCH_TURNED_OFF == event_info.get_event_type(): sink.pause() return True
zone-api
/zone_api-0.2.1.tar.gz/zone_api-0.2.1/src/zone_api/core/actions/play_music_during_shower.py
play_music_during_shower.py
import copy import datetime import time import argparse from collections import defaultdict from .configs import SUPPORTED_RECORDS, DEFAULT_TEMPLATE from .exceptions import InvalidLineException class ZonefileLineParser(argparse.ArgumentParser): def error(self, message): """ Silent error message """ raise InvalidLineException(message) def make_rr_subparser(subparsers, rec_type, args_and_types): """ Make a subparser for a given type of DNS record """ sp = subparsers.add_parser(rec_type) sp.add_argument("name", type=str) sp.add_argument("ttl", type=int, nargs='?') sp.add_argument(rec_type, type=str) for (argname, argtype) in args_and_types: sp.add_argument(argname, type=argtype) return sp def make_parser(): """ Make an ArgumentParser that accepts DNS RRs """ line_parser = ZonefileLineParser() subparsers = line_parser.add_subparsers() # parse $ORIGIN sp = subparsers.add_parser("$ORIGIN") sp.add_argument("$ORIGIN", type=str) # parse $TTL sp = subparsers.add_parser("$TTL") sp.add_argument("$TTL", type=int) # parse each RR args_and_types = [ ("mname", str), ("rname", str), ("serial", int), ("refresh", int), ("retry", int), ("expire", int), ("minimum", int) ] make_rr_subparser(subparsers, "SOA", args_and_types) make_rr_subparser(subparsers, "NS", [("host", str)]) make_rr_subparser(subparsers, "A", [("ip", str)]) make_rr_subparser(subparsers, "AAAA", [("ip", str)]) make_rr_subparser(subparsers, "CNAME", [("alias", str)]) make_rr_subparser(subparsers, "MX", [("preference", str), ("host", str)]) make_rr_subparser(subparsers, "TXT", [("txt", str)]) make_rr_subparser(subparsers, "PTR", [("host", str)]) make_rr_subparser(subparsers, "SRV", [("priority", int), ("weight", int), ("port", int), ("target", str)]) make_rr_subparser(subparsers, "SPF", [("data", str)]) make_rr_subparser(subparsers, "URI", [("priority", int), ("weight", int), ("target", str)]) return line_parser def tokenize_line(line): """ Tokenize a line: * split tokens on whitespace * treat quoted strings as a single token * drop comments * handle escaped spaces and comment delimiters """ ret = [] escape = False quote = False tokbuf = "" ll = list(line) while len(ll) > 0: c = ll.pop(0) if c.isspace(): if not quote and not escape: # end of token if len(tokbuf) > 0: ret.append(tokbuf) tokbuf = "" elif quote: # in quotes tokbuf += c elif escape: # escaped space tokbuf += c escape = False else: tokbuf = "" continue if c == '\\': escape = True continue elif c == '"': if not escape: if quote: # end of quote ret.append(tokbuf) tokbuf = "" quote = False continue else: # beginning of quote quote = True continue elif c == ';': if not escape: # comment ret.append(tokbuf) tokbuf = "" break # normal character tokbuf += c escape = False if len(tokbuf.strip(" ").strip("\n")) > 0: ret.append(tokbuf) return ret def serialize(tokens): """ Serialize tokens: * quote whitespace-containing tokens * escape semicolons """ ret = [] for tok in tokens: if " " in tok: tok = '"%s"' % tok if ";" in tok: tok = tok.replace(";", "\;") ret.append(tok) return " ".join(ret) def remove_comments(text): """ Remove comments from a zonefile """ ret = [] lines = text.split("\n") for line in lines: if len(line) == 0: continue line = serialize(tokenize_line(line)) ret.append(line) return "\n".join(ret) def flatten(text): """ Flatten the text: * make sure each record is on one line. * remove parenthesis """ lines = text.split("\n") # tokens: sequence of non-whitespace separated by '' where a newline was tokens = [] for l in lines: if len(l) == 0: continue l = l.replace("\t", " ") tokens += filter(lambda x: len(x) > 0, l.split(" ")) + [''] # find (...) and turn it into a single line ("capture" it) capturing = False captured = [] flattened = [] while len(tokens) > 0: tok = tokens.pop(0) if not capturing and len(tok) == 0: # normal end-of-line if len(captured) > 0: flattened.append(" ".join(captured)) captured = [] continue if tok.startswith("("): # begin grouping tok = tok.lstrip("(") capturing = True if capturing and tok.endswith(")"): # end grouping. next end-of-line will turn this sequence into a flat line tok = tok.rstrip(")") capturing = False captured.append(tok) return "\n".join(flattened) def remove_class(text): """ Remove the CLASS from each DNS record, if present. The only class that gets used today (for all intents and purposes) is 'IN'. """ # see RFC 1035 for list of classes lines = text.split("\n") ret = [] for line in lines: tokens = tokenize_line(line) tokens_upper = [t.upper() for t in tokens] if "IN" in tokens_upper: tokens.remove("IN") elif "CS" in tokens_upper: tokens.remove("CS") elif "CH" in tokens_upper: tokens.remove("CH") elif "HS" in tokens_upper: tokens.remove("HS") ret.append(serialize(tokens)) return "\n".join(ret) def add_default_name(text): """ Go through each line of the text and ensure that a name is defined. Use '@' if there is none. """ global SUPPORTED_RECORDS lines = text.split("\n") ret = [] for line in lines: tokens = tokenize_line(line) if tokens[0] in SUPPORTED_RECORDS and not tokens[0].startswith("$"): # add back the name tokens = ['@'] + tokens ret.append(serialize(tokens)) return "\n".join(ret) def parse_line(parser, record_token, parsed_records): """ Given the parser, capitalized list of a line's tokens, and the current set of records parsed so far, parse it into a dictionary. Return the new set of parsed records. Raise an exception on error. """ global SUPPORTED_RECORDS line = " ".join(record_token) # match parser to record type if len(record_token) >= 2 and record_token[1] in SUPPORTED_RECORDS: # with no ttl record_token = [record_token[1]] + record_token elif len(record_token) >= 3 and record_token[2] in SUPPORTED_RECORDS: # with ttl record_token = [record_token[2]] + record_token try: rr, unmatched = parser.parse_known_args(record_token) assert len(unmatched) == 0, "Unmatched fields: %s" % unmatched except (SystemExit, AssertionError, InvalidLineException): # invalid argument raise InvalidLineException(line) record_dict = rr.__dict__ # what kind of record? including origin and ttl record_type = None for key in record_dict.keys(): if key in SUPPORTED_RECORDS and (key.startswith("$") or record_dict[key] == key): record_type = key if record_dict[key] == key: del record_dict[key] break assert record_type is not None, "Unknown record type in %s" % rr # clean fields for field in record_dict.keys(): if record_dict[field] is None: del record_dict[field] current_origin = record_dict.get('$ORIGIN', parsed_records.get('$ORIGIN', None)) # special record-specific fix-ups if record_type == 'PTR': record_dict['fullname'] = record_dict['name'] + '.' + current_origin if len(record_dict) > 0: if record_type.startswith("$"): # put the value directly record_dict_key = record_type.lower() parsed_records[record_dict_key] = record_dict[record_type] else: record_dict_key = record_type.lower() parsed_records[record_dict_key].append(record_dict) return parsed_records def parse_lines(text, ignore_invalid=False): """ Parse a zonefile into a dict. @text must be flattened--each record must be on one line. Also, all comments must be removed. """ json_zone_file = defaultdict(list) record_lines = text.split("\n") parser = make_parser() for record_line in record_lines: record_token = tokenize_line(record_line) try: json_zone_file = parse_line(parser, record_token, json_zone_file) except InvalidLineException: if ignore_invalid: continue else: raise return json_zone_file def parse_zone_file(text, ignore_invalid=False): """ Parse a zonefile into a dict """ text = remove_comments(text) text = flatten(text) text = remove_class(text) text = add_default_name(text) json_zone_file = parse_lines(text, ignore_invalid=ignore_invalid) return json_zone_file
zone-file
/zone-file-0.1.5.tar.gz/zone-file-0.1.5/zone_file/parse_zone_file.py
parse_zone_file.py
from .record_processors import ( process_origin, process_ttl, process_soa, process_ns, process_a, process_aaaa, process_cname, process_mx, process_ptr, process_txt, process_srv, process_spf, process_uri ) from .configs import DEFAULT_TEMPLATE def make_zone_file(json_zone_file, template=None): """ Generate the DNS zonefile, given a json-encoded description of the zone file (@json_zone_file) and the template to fill in (@template) json_zone_file = { "$origin": origin server, "$ttl": default time-to-live, "soa": [ soa records ], "ns": [ ns records ], "a": [ a records ], "aaaa": [ aaaa records ] "cname": [ cname records ] "mx": [ mx records ] "ptr": [ ptr records ] "txt": [ txt records ] "srv": [ srv records ] "spf": [ spf records ] "uri": [ uri records ] } """ if template is None: template = DEFAULT_TEMPLATE[:] soa_records = [json_zone_file.get('soa')] if json_zone_file.get('soa') else None zone_file = template zone_file = process_origin(json_zone_file.get('$origin', None), zone_file) zone_file = process_ttl(json_zone_file.get('$ttl', None), zone_file) zone_file = process_soa(soa_records, zone_file) zone_file = process_ns(json_zone_file.get('ns', None), zone_file) zone_file = process_a(json_zone_file.get('a', None), zone_file) zone_file = process_aaaa(json_zone_file.get('aaaa', None), zone_file) zone_file = process_cname(json_zone_file.get('cname', None), zone_file) zone_file = process_mx(json_zone_file.get('mx', None), zone_file) zone_file = process_ptr(json_zone_file.get('ptr', None), zone_file) zone_file = process_txt(json_zone_file.get('txt', None), zone_file) zone_file = process_srv(json_zone_file.get('srv', None), zone_file) zone_file = process_spf(json_zone_file.get('spf', None), zone_file) zone_file = process_uri(json_zone_file.get('uri', None), zone_file) # remove newlines, but terminate with one zone_file = "\n".join( filter( lambda l: len(l.strip()) > 0, [tl.strip() for tl in zone_file.split("\n")] ) ) + "\n" return zone_file
zone-file
/zone-file-0.1.5.tar.gz/zone-file-0.1.5/zone_file/make_zone_file.py
make_zone_file.py
import copy def process_origin(data, template): """ Replace {$origin} in template with a serialized $ORIGIN record """ record = "" if data is not None: record += "$ORIGIN %s" % data return template.replace("{$origin}", record) def process_ttl(data, template): """ Replace {$ttl} in template with a serialized $TTL record """ record = "" if data is not None: record += "$TTL %s" % data return template.replace("{$ttl}", record) def process_soa(data, template): """ Replace {SOA} in template with a set of serialized SOA records """ record = template[:] if data is not None: assert len(data) == 1, "Only support one SOA RR at this time" data = data[0] soadat = [] domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields + param_fields: assert f in data.keys(), "Missing '%s' (%s)" % (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append("IN") soadat.append("SOA") for key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append("(") for key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(")") soa_txt = " ".join(soadat) record = record.replace("{soa}", soa_txt) else: # clear all SOA fields record = record.replace("{soa}", "") return record def quote_field(data, field): """ Quote a field in a list of DNS records. Return the new data records. """ if data is None: return None data_dup = copy.deepcopy(data) for i in xrange(0, len(data_dup)): data_dup[i][field] = '"%s"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(";", "\;") return data_dup def process_rr(data, record_type, record_keys, field, template): """ Meta method: Replace $field in template with the serialized $record_type records, using @record_key from each datum. """ if data is None: return template.replace(field, "") if type(record_keys) == list: pass elif type(record_keys) == str: record_keys = [record_keys] else: raise ValueError("Invalid record keys") assert type(data) == list, "Data must be a list" record = "" for i in xrange(0, len(data)): for record_key in record_keys: assert record_key in data[i].keys(), "Missing '%s'" % record_key record_data = [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys] record += " ".join(record_data) + "\n" return template.replace(field, record) def process_ns(data, template): """ Replace {ns} in template with the serialized NS records """ return process_rr(data, "NS", "host", "{ns}", template) def process_a(data, template): """ Replace {a} in template with the serialized A records """ return process_rr(data, "A", "ip", "{a}", template) def process_aaaa(data, template): """ Replace {aaaa} in template with the serialized A records """ return process_rr(data, "AAAA", "ip", "{aaaa}", template) def process_cname(data, template): """ Replace {cname} in template with the serialized CNAME records """ return process_rr(data, "CNAME", "alias", "{cname}", template) def process_mx(data, template): """ Replace {mx} in template with the serialized MX records """ return process_rr(data, "MX", ["preference", "host"], "{mx}", template) def process_ptr(data, template): """ Replace {ptr} in template with the serialized PTR records """ return process_rr(data, "PTR", "host", "{ptr}", template) def process_txt(data, template): """ Replace {txt} in template with the serialized TXT records """ # quote txt data_dup = quote_field(data, "txt") return process_rr(data_dup, "TXT", "txt", "{txt}", template) def process_srv(data, template): """ Replace {srv} in template with the serialized SRV records """ return process_rr(data, "SRV", ["priority", "weight", "port", "target"], "{srv}", template) def process_spf(data, template): """ Replace {spf} in template with the serialized SPF records """ return process_rr(data, "SPF", "data", "{spf}", template) def process_uri(data, template): """ Replace {uri} in templtae with the serialized URI records """ # quote target data_dup = quote_field(data, "target") return process_rr(data_dup, "URI", ["priority", "weight", "target"], "{uri}", template)
zone-file
/zone-file-0.1.5.tar.gz/zone-file-0.1.5/zone_file/record_processors.py
record_processors.py
GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
zone4
/zone4-0.0.1-py3-none-any.whl/zone4-0.0.1.dist-info/LICENSE.md
LICENSE.md
zone53 ====== [zone53](https://github.com/aglyzov/zone53) is a convenient Python API to manage Amazon's DNS web service [route53](http://aws.amazon.com/route53/). Essentially, it is a thin layer on top of [boto.route53](http://boto.readthedocs.org/en/latest/ref/route53.html) providing Zone and Record classes. How to install -------------- ~~~sh # using pip (recommended) pip install zone53 ~~~ ~~~sh # or using pip from the git repo pip install git+https://github.com/aglyzov/zone53.git ~~~ ~~~sh # or using setup.py (assuming you downloaded the sources) python setup.py install ~~~ Authentication -------------- zone53 uses [boto.route53](http://boto.readthedocs.org/en/latest/ref/route53.html) to make all connections so all boto authentication rules apply here. Basically, you either use a boto config file (~/.boto): ~~~ini [Credentials] aws_access_key_id = <YOUR-AWS-ACCESS-KEY> aws_secret_access_key = <YOUR-AWS-SECRET-KEY> ~~~ or set special environment variables: ~~~sh # in a shell export AWS_ACCESS_KEY_ID="<YOUR-AWS-ACCESS-KEY" export AWS_SECRET_ACCESS_KEY="<YOUR-AWS-SECRET-KEY>" ~~~ ~~~python # or in a python source from os import env env['AWS_ACCESS_KEY_ID'] = '<YOUR-AWS-ACCESS-KEY>' env['AWS_SECRET_ACCESS_KEY'] = '<YOUR-AWS-SECRET-KEY>' ~~~ Examples -------- ~~~python from zone53 import Zone, Record # creating new zone example.com. zone = Zone.create('example.com') # getting all available zones as a list zones = Zone.get_all() # getting an existing zone by name zone = Zone.get('example.com') # constructing an FQDN for a name zone.fqdn() == 'example.com' zone.fqdn('test') == 'test.example.com' zone.fqdn('test.example.com') == 'test.example.com' zone.fqdn('test.example.com', trailing_dot=True) == 'test.example.com.' # stripping off the domain zone.short() == '' zone.short('example.com') == '' zone.short('.example.com.') == '' zone.short('test') == 'test' zone.short('test.example.com') == 'test' zone.short('abc.test.example.com.') == 'abc.test' # fetching all records records = zone.get_records() # fetching CNAME records with ttl=300 cnames = zone.get_records( type='CNAME', ttl=300 ) # fetching A records for test.example.com. (using incomplete name) empty = zone.get_records( type='A', name='test' ) # fetching nameservers ns_records = zone.get_records( type='NS' ) nameservers = ns_records and ns_records[0].value or [] # adding a CNAME record with ttl=60 # (note, you can use incomplete names when passing zone as a kw-argument) rec = Record( type='CNAME', name='www', value='', ttl=60, zone=zone ) rec.add() # same as zone.add_record( rec ) # adding a multi-resource A record for the domain rec = Record( name='example.com', value='192.168.1.1, 192.168.1.2, 192.168.1.3' ) status = rec.add( zone ) # watching status of a change from time import sleep while status == 'pending': sleep(5) print status.update() # adding three A records Record( name='node01.example.com', value='192.168.1.1' ).add( zone ) Record( name='node02.example.com', value='192.168.1.2' ).add( zone ) Record( name='node03.example.com', value='192.168.1.3' ).add( zone ) # adding a weighted CNAME record set (WRR) for name in ['node01', 'node02', 'node03']: value = zone.fqdn( name ) r = Record( type='CNAME', name='node', value=value, weight=2, id=name, zone=zone ) r.add() # updaing a record r1.update( id='heavy-node', weight=5, value='node04.example.com' ) # deleting a record r2.delete() # deleting a zone for rec in zone.get_records( type='CNAME' ): rec.delete() for rec in zone.get_records( type='A' ): rec.delete() zone.delete() ~~~
zone53
/zone53-0.3.3.tar.gz/zone53-0.3.3/README.md
README.md
__version__ = '0.3.3' __author__ = 'Alexander Glyzov' __maintainer__ = 'Alexander Glyzov' __email__ = '[email protected]' __all__ = ['Zone', 'Record'] from socket import gethostbyname from functools import partial from boto import connect_route53 from boto.route53.record import ResourceRecordSets def norm_weight( weight ): #{ if weight: try: weight = max(int(weight), 0) except: weight = None return weight or None #} class Record(object): #{ def __init__(self, name, value, type='A', ttl=300, weight=None, id=None, zone=None, normalize=True): type = str(type).upper() if not normalize or type == 'PTR': norm_host = lambda h: h elif zone: assert isinstance(zone, Zone) norm_host = partial( zone.fqdn, trailing_dot=True ) else: norm_host = lambda h: h if h.endswith('.') else h+'.' if not normalize: norm_value = lambda v: v elif type in ('A','AAAA'): norm_value = lambda v: v or gethostbyname( zone.name ) else: norm_value = lambda v: (v or zone.name).rstrip('.')+'.' if not isinstance(value, (list, tuple, set, dict)): value = str(value).split(',') value = [h.strip() for h in value] self.type = type self.name = norm_host( name ) self.value = map(norm_value, value) self.ttl = ttl self.weight = norm_weight( weight ) self.id = id self.zone = zone @classmethod def from_boto_record(cls, boto_record, zone=None): return cls( boto_record.name, boto_record.resource_records, type = boto_record.type, ttl = boto_record.ttl, weight = boto_record.weight, id = boto_record.identifier, zone = zone, normalize = False # don't change original host names ) def __repr__(self): return '<%s: %s, %s, %s, [%s]%s>' % ( self.__class__.__name__, self.type, self.ttl, self.name, ', '.join( self.value ), ' (WRR id=%s, weight=%s)' % (self.id, self.weight) if self.weight or self.id else '' ) def add(self, zone=None): """Add this record to a zone""" zone = zone or self.zone assert isinstance(zone, Zone) return zone.add_record( self ) def update(self, **kw): zone = kw.pop('zone', None) or getattr(self, 'zone') assert isinstance(zone, Zone) return zone.update_record( self, **kw ) def delete(self, zone=None): """Delete this record from a zone""" zone = zone or self.zone assert isinstance(zone, Zone) return zone.delete_record( self ) #} class Zone(object): #{ def __init__(self, zone_dict, conn=None): self.conn = conn or connect_route53() self.id = zone_dict.pop('Id','').replace('/hostedzone/','') for key, value in zone_dict.items(): setattr(self, key.lower(), value) if not self.name.endswith('.'): self.name += '.' # make sure the name is fully qualified @classmethod def create(cls, name, conn=None): """ Create new hosted zone.""" conn = conn or connect_route53() name = name if name.endswith('.') else name+'.' zone = conn.create_hosted_zone(name) zone = zone['CreateHostedZoneResponse']['HostedZone'] return cls(zone, conn=conn) @classmethod def get(cls, name): """ Retrieve a hosted zone defined by name.""" name = name if name.endswith('.') else name+'.' matched = [z for z in cls.get_all() if z.name == name] return matched and matched[0] or None @classmethod def get_all(cls, conn=None): """ Retrieve a list of all hosted zones.""" conn = conn or connect_route53() zones = conn.get_all_hosted_zones() zones = zones['ListHostedZonesResponse']['HostedZones'] return [cls(z, conn=conn) for z in zones] def __repr__(self): return '<Zone: %s, %s>' % (self.name, self.id) def fqdn(self, host='', trailing_dot=False): """ Returns a fully qualified domain name for the argument trailing_dot=<bool> - enforce a presence of trailing dot """ if not host.endswith('.'): if host.endswith( self.name[:-1] ): host += '.' elif host: host += '.%s' % self.name else: host = self.name host = host.rstrip('.') if trailing_dot: host += '.' return host def short(self, host=''): """ Returns a short name with the domain name stripped off """ host = str(host).rstrip('.') domain = self.name.rstrip('.') if host == domain: host = '' elif host.endswith('.'+domain): host = host[:-len(domain)-1] return host def add_record(self, record, comment=''): """Add a new record to this zone""" assert isinstance(record, Record) changes = ResourceRecordSets( self.conn, self.id, comment ) change = changes.add_change( "CREATE", record.name, record.type, ttl = record.ttl, weight = record.weight, identifier = record.id ) for value in record.value: change.add_value(value) record.zone = self return Status( changes.commit(), conn=self.conn ) def update_record( self, record, type = None, name = None, value = None, ttl = None, weight = None, # for weighed or latency-based resource sets id = None, # for weighed or latency-based resource sets comment = "" ): assert isinstance(record, Record) changes = ResourceRecordSets( self.conn, self.id, comment ) change = changes.add_change( "DELETE", record.name, record.type, ttl = record.ttl, weight = record.weight, identifier = record.id ) for val in record.value: change.add_value( val ) record.name = self.fqdn( name or record.name ) record.type = type or record.type record.ttl = ttl or record.ttl record.weight = weight or record.weight record.id = id or record.id change = changes.add_change( 'CREATE', record.name, record.type, ttl = record.ttl, weight = record.weight, identifier = record.id ) new = Record( record.name, value or record.value, type=record.type, zone=self ) for val in new.value: change.add_value( val ) record.value = new.value record.zone = self return Status( changes.commit(), conn=self.conn ) def delete_record(self, record): """Delete a record from this zone""" assert isinstance(record, Record) changes = ResourceRecordSets(self.conn, self.id) change = changes.add_change( "DELETE", record.name, record.type, ttl = record.ttl, weight = record.weight, identifier = record.id ) for value in record.value: change.add_value(value) record.zone = None return Status( changes.commit(), conn=self.conn ) def get_records(self, name=None, type=None, ttl=None, weight=None, id=None): """Get a list of this zone records (optionally filtered)""" records = [] if name and type != 'PTR': name = self.fqdn( name ) weight = norm_weight( weight ) for boto_record in self.conn.get_all_rrsets(self.id): record = Record.from_boto_record( boto_record, zone=self ) record_name = self.fqdn( record.name ) record_weight = norm_weight( record.weight ) if (record_name == name if name else True)\ and (record.type == type if type else True)\ and (record.ttl == ttl if ttl else True)\ and (record_weight == weight if weight else True)\ and (record.id == id if id else True): records.append( record ) return records def delete(self): """ Delete this zone.""" return Status( self.conn.delete_hosted_zone(self.id), key='DeleteHostedZoneResponse' ) #} class Status(object): #{ def __init__(self, change_resp, conn=None, key='ChangeResourceRecordSetsResponse'): self.conn = conn or connect_route53() _dict = change_resp[key]['ChangeInfo'] for key, value in _dict.items(): setattr(self, key.lower(), value) self.id = (self.id or '').replace('/change/','') self.status = (self.status or '').lower() def update(self): """ Update the status of this request.""" change_resp = self.conn.get_change(self.id) self.status = change_resp['GetChangeResponse']['ChangeInfo']['Status'].lower() return self.status def __repr__(self): return '<Status: %s>' % self.status def __str__(self): return self.status def __eq__(self, other): return str(self) == str(other) #}
zone53
/zone53-0.3.3.tar.gz/zone53-0.3.3/zone53.py
zone53.py
# ZoneBot - A ZoneMinder Slack Bot This is a [Slack Bot](https://api.slack.com/bot-users) that monitors one or more [Slack](https://slack.com) channels for commands and interacts with a [ZoneMinder](https://www.zoneminder.com/) system to report events and obtain information. There are two parts to the project 1. A script that is invoked by ZoneMinder whenever an event/alarm is detected (`zonebot-alert`). This will post a message with the most significant frame of the event to a specified Slack channel. ![ZoneBot posting an event](https://raw.githubusercontent.com/rjclark/zoneminder-slack-bot/master/docs/images/ZoneBot-Post-Event.png) 2. A bot that listens in a Slack channel for commands from approved users and passes them along to the ZoneMinder server. [![Screen cast of basic features](https://raw.githubusercontent.com/rjclark/zoneminder-slack-bot/master/docs/images/ZoneBot-Screen-Cast-Static.png)](https://rjclark.github.io/zoneminder-slack-bot/docs/images/ZoneBot-Screen-Cast.webm) The primary use for this bot is to allow access to some parts of a ZoneMinder system that is behind a firewall, without having to expose the actual system to the Internet. Making a ZoneMinder system available to the Internet has several requirements (static IP, secure system) that may not be feasible for all users. By providing a bot that can interact with both ZoneMinder and Slack, remote access to and notification from ZoneMinder is possible, without needing a static IP. The security and authentication provided by the Slack environment is used to control access to the script, and the bot also has a permissions section in it's configuration that controls which users are allowed which actions. ## Installation ### Easiest : Using pip The easiest method of installation is via `pip` as the package is available from the [Python Package Index](https://pypi.python.org/pypi) ```sh > pip install zonebot ``` This will create a script called `zonebot` in your path ("`which zonebot`" will tell you exactly where) that you can run. ### Download source and build You can download the source from GitHub and build it yourself if you would like. 1. Download the release you want from https://github.com/rjclark/zoneminder-slack-bot/releases 1. Extract it 1. Run `python setup.py build install` ### Clone the source and build You can also clone the source from GitHub if you would like to build the very latest version. **This is not guaranteed to work**. The unreleased source code from GitHub could be in the middle of development and running it directly is not recommended. 1. Clone this repository https://github.com/rjclark/zoneminder-slack-bot 1. Run `python setup.py build install` ## Configuration ### Bot Configuration Also installed is a sample configuration file called `zonebot-example-config.cfg`. You can copy this to your preferred location for config files and edit it to put in your [Slack API token](https://api.slack.com/tokens) and the [ID of your bot user](https://api.slack.com/bot-users) The example configuration file is installed into the Python package directory on your system, which can be somewhat difficult to find. The latest version of the file is always available from [the GitHub repository](https://github.com/rjclark/zoneminder-slack-bot/blob/master/docs/zonebot-example-config.cfg) if needed. To configure the bot, you will need several pieces of information 1. Your Slack API token. This can be found by 1. Going to the [Slack Bot user page](https://api.slack.com/bot-users) and creating a new bot user. You will have a chance to get the API token here 2. Going to the page for your [existing bot user](https://my.slack.com/apps/manage/custom-integrations). 2. The User ID of your bot user. This can be found by: 1. Running the script `zonebot-getid` distributed with this package and providing the name of the Slack bot user and you Slack API token as command line options. For example: ```sh > zonebot-getid -a "your-slack-token" -b zoneminder > User ID for bot 'zoneminder' is AA22BB44C ``` Once you have those, make a copy of the config file and add the Slack API token and user ID of the bot, You will also want to edit the `Permissions` section. **NOTE**: The default config file allows only read permission to the ZoneMinder system. ### ZoneMinder Configuration If you want ZoneMinder events posted to Slack as they occur, you must define a ZoneMinder filter that invokes the `zonebot-alert` script. The script gets all required configuration information from the same config file as the bot. ![Defining a ZoneMinder filter](https://raw.githubusercontent.com/rjclark/zoneminder-slack-bot/master/docs/images/ZoneBot-Define-Filter.png) ### Config File Locations The default config file can be placed in any of these locations (checked in this order) * Any file specified by the `-c/--config` command line option * `$XDG_CONFIG_HOME/zonebot/zonebot.conf` if the `XDG_CONFIG_HOME` environment variable is defined * `${DIR}/zonebot/zonebot.conf` for any directory in the `XDG_CONFIG_DIRS` environment variable * `~/.config/zonebot/zonebot.conf` * `/etc/zonebot/zonebot.conf` * `/etc/default/zonebot` ## Reporting Problems 1. The best way to report problems is to log a report on the GitHub Issues page [https://github.com/rjclark/zoneminder-slack-bot/issues](https://github.com/rjclark/zoneminder-slack-bot/issues) for this project. 2. If you do not have a GItHub account, you can also contact me via email: [[email protected]](mailto:[email protected]) ## Building and Contributing If you wish to contribute, pull requests against the [GitHub repository](https://github.com/rjclark/zoneminder-slack-bot), `master` branch, are welcomed. [![Build Status](https://travis-ci.org/rjclark/zoneminder-slack-bot.svg?branch=master)](https://travis-ci.org/rjclark/zoneminder-slack-bot) [![Coverage Status](https://coveralls.io/repos/github/rjclark/zoneminder-slack-bot/badge.svg?branch=master)](https://coveralls.io/github/rjclark/zoneminder-slack-bot?branch=master) [![PyPI version](https://badge.fury.io/py/zonebot.svg)](https://pypi.python.org/pypi/zonebot) [![Dependency Status](https://www.versioneye.com/user/projects/57def689037c2000458f770d/badge.svg?style=flat-square)](https://www.versioneye.com/user/projects/57def689037c2000458f770d) [![Code Health](https://landscape.io/github/rjclark/zoneminder-slack-bot/master/landscape.svg?style=flat)](https://landscape.io/github/rjclark/zoneminder-slack-bot/master) ### Requirements and Tools If you are new to the concept of building either a Python application or a Slack bot, I encourage you to review the excellent posting over at [Full Stack Python](https://www.fullstackpython.com) called [How to Build Your First Slack Bot with Python](https://www.fullstackpython.com/blog/build-first-slack-bot-python.html). This document will provide a summary of the requirements and steps necessary, but it assumes a basica familiarity with the tools and environment that the linked article covers in some depth. This list of tools from the [First Slack Bot](https://www.fullstackpython.com/blog/build-first-slack-bot-python.html) blog is all that is needed to build this bot. > * Either [Python 2 or 3](https://wiki.python.org/moin/Python2orPython3) > * [pip](https://pip.pypa.io/en/stable/) and [virtualenv](https://virtualenv.pypa.io/> en/stable/) to handle Python application dependencies > * A [Slack account](https://slack.com/) with a team on which you have API access. > * Official Python [slackclient](https://github.com/slackhq/python-slackclient) code library built by the Slack team > * [Slack API testing token](https://api.slack.com/tokens) > > It is also useful to have the [Slack API docs](https://api.slack.com/) handy while you're building this tutorial. ### Setup 1. Use `virtualenv` and `pip` to create a development ```sh > virtualenv venv > source venv/bin/activate (or . venv/bin/activate.fish of you use the fish shell) > venv/bin/pip install install -r requirements.txt ``` 2. Obtain a Slack API token (and optionally create a dedicated [bot user](https://api.slack.com/bot-users) for the API token) from Slack 3. Since the API token needs to remain secret, you should set it as an environment variable rather than putting it into any source file. ```sh > export SLACK_BOT_TOKEN='your slack token pasted here' ``` 4. Run `utils/get_bot_id.py` to get the number ID of the bot (as opposed to the name you gave the bot user. This is also our first real test of the API token 5. Put the bot ID into an environment variable as well. ```sh > export BOT_ID='bot id returned by script' ``` Later on the BOT_ID and SLACK_API_TOKEN (along with a lot of the other config options) will be loaded from a config file. This is to make running the script as a daemon less of a hassle.
zonebot
/zonebot-1.0.tar.gz/zonebot-1.0/README.md
README.md
# Name zonefile-migrate - Migrate DNS managed zones # Synopsis ```text zonefile-migrate to-cloudformation [OPTIONS] [SRC]... DST zonefile-migrate to-terraform [OPTIONS] [SRC]... DST ``` # Options ``` to-cloudformation --sceptre-group DIRECTORY to write sceptre stack group configuration --maximum-ttl INTEGER maximum TTL of domain name records to-terraform --maximum-ttl INTEGER maximum TTL of domain name records --provider PROVIDER to generate for ``` # Description Converts one or more `SRC` zonefiles into AWS CloudFormation or Terraform templates in `DST`. The zonefiles must contain a $ORIGIN and $TTL statement. If the SRC points to a directory all files which contain one of these statements will be converted. If a $ORIGIN is missing, the name of the file will be used as the domain name. Optionally generates the Sceptre stack config for each of the templates in the `--sceptre-group` directory. Each generated CloudFormation template contains a single Route53 HostedZone and all associated ResourceRecordSet. The SOA and NS records for the origin domain are not copied into the template. # Installation to install the utility, type: ```bash pip install zonefile-migrate ``` # Example - to-cloudformation In the source code we have an example, to try it out, type: ```bash $ git clone https://gitlab.com/binxio/zonefile-migrate.git $ cd zonefile-migrate/example $ zonefile-migrate to-cloudformation --sceptre-group config/dns ./zones ./templates/dns INFO: reading zonefile zones/asample.org INFO: reading zonefile zones/land-5.com ``` To deploy all the managed zones to AWS, type: ```bash $ sceptre --var aws_profile=$AWS_PROFILE launch -y dns [2022-05-14 14:58:23] - dns/zone-land-5-com - Launching Stack [2022-05-14 14:58:23] - dns/zone-example-org - Launching Stack [2022-05-14 14:58:23] - dns/zone-land-5-com - Stack is in the PENDING state [2022-05-14 14:58:23] - dns/zone-land-5-com - Creating Stack [2022-05-14 14:58:23] - dns/zone-asample-org - Stack is in the PENDING state [2022-05-14 14:58:23] - dns/zone-asample-org - Creating Stack [2022-05-14 14:58:24] - dns/zone-asample-org binxio-dns-zone-asample-org AWS::CloudFormation::Stack CREATE_IN_PROGRESS User Initiated [2022-05-14 14:58:24] - dns/zone-land-5-com binxio-dns-zone-land-5-com AWS::CloudFormation::Stack CREATE_IN_PROGRESS User Initiated ... ``` # Example - to-terraform ```bash $ git clone https://gitlab.com/binxio/zonefile-migrate.git $ cd zonefile-migrate/example $ zonefile-migrate to-terraform --provider google ./zones ./terraform INFO: reading zonefile zones/asample.org INFO: reading zonefile zones/land-5.com ``` To deploy all the managed zones to Google Cloud Platform, type: ```bash $ cd terraform $ terraform init $ export GOOGLE_PROJECT=$(gcloud config get-value core/project) $ terraform apply -auto-approve ... Terraform will perform the following actions: # module.asample_org.google_dns_managed_zone.managed_zone will be created + resource "google_dns_managed_zone" "managed_zone" { + description = "Managed by Terraform" + dns_name = "asample.org." + force_destroy = false + id = (known after apply) + name = "asample-org" + name_servers = (known after apply) + project = (known after apply) + visibility = "public" } ... Plan: 49 to add, 0 to change, 0 to destroy. module.land-5_com.google_dns_managed_zone.managed_zone: Creating... module.asample_org.google_dns_managed_zone.managed_zone: Creating... ... ```
zonefile-migrate
/zonefile-migrate-0.4.4.tar.gz/zonefile-migrate-0.4.4/README.md
README.md
import click import json import logging import re import sys import os import pkgutil from zonefile_migrate.utils import convert_zonefiles, target_file from pathlib import Path from ruamel.yaml import YAML, CommentedMap from zonefile_migrate.logger import logging from easyzone import easyzone from dns.exception import SyntaxError from zonefile_migrate.dns_record_set import create_from_zone from jinja2 import Template from zonefile_migrate.utils import get_all_zonefiles_in_path tf_managed_zone_template = """ module managed_zone_{{ resource_name }} { source = "./{{ provider }}-managed-zone" domain_name = "{{ domain_name.encode("idna").decode("ascii") }}" resource_record_sets = [{% for record in resource_record_sets %} { name = "{{ record.name }}" type = "{{ record.rectype }}" ttl = {{ maximum_ttl if maximum_ttl and record.ttl > maximum_ttl else record.ttl }} rrdatas = [{% for rrdata in record.rrdatas %} "{{ rrdata.strip('"') }}",{% endfor %} ] },{% endfor %} ] } """ def convert_to_terraform(zone: easyzone.Zone, provider: str, maximum_ttl: int) -> str: """ Converts the zonefile into a terraform tempalte for Google """ domain_name = zone.domain idna_domain_name = domain_name.encode("idna").decode("ascii") resource_name = re.sub(r"\.", "_", zone.domain.removesuffix(".")) resource_record_sets = list( filter( lambda r: not ( r.rectype in ["SOA", "NS"] and r.name in [domain_name, idna_domain_name] ), create_from_zone(zone), ) ) template = Template(tf_managed_zone_template) return template.render( { "domain_name": domain_name, "resource_name": resource_name, "provider": provider, "maximum_ttl": maximum_ttl, "resource_record_sets": resource_record_sets, } ) @click.command(name="to-terraform") @click.option( "--provider", required=False, default="google", help="name of provider to generate the managed zone for (google)", ) @click.option( "--maximum-ttl", required=False, type=int, help="maximum TTL of domain name records", ) @click.argument("src", nargs=-1, type=click.Path()) @click.argument("dst", nargs=1, type=click.Path()) def command(provider, maximum_ttl, src, dst): """ Converts one or more `SRC` zonefiles into Terraform templates in `DST`. Each generated Terraform template contains a single hosted zone and all associated resource record sets. The SOA and NS records for the origin domain are not copied into the template. The zonefiles must contain a $ORIGIN and $TTL statement. If the SRC points to a directory all files which contain one of these statements will be converted. If a $ORIGIN is missing, the name of the file will be used as the domain name. You may override the maximum TTL of records through the option --maximum-ttl """ tf_module_template = Path(__file__).parent.joinpath( f"terraform-modules/{provider}-managed-zone.tf" ) if not tf_module_template.exists(): raise click.UsageError(f"provider {provider} is not supported") if not src: raise click.UsageError("no source files were specified") try: inputs = get_all_zonefiles_in_path(src) if len(inputs) == 0: raise click.UsageError("no zonefiles were found") except ValueError as error: raise click.UsageError(error) dst = Path(dst) if len(inputs) > 1: if dst.exists() and not dst.is_dir(): raise click.UsageError(f"{dst} is not a directory") if not dst.exists(): dst.mkdir(parents=True, exist_ok=True) outputs = list(map(lambda d: target_file(d, dst, ".tf"), inputs)) if dst.is_dir(): main_path = dst.joinpath(f"{provider}-managed-zone/main.tf") if not main_path.exists(): main_path.parent.mkdir(exist_ok=True) main_path.write_bytes(tf_module_template.read_bytes()) def _transform_to_terraform(zone: easyzone.Zone, output: Path): with output.open("w") as file: file.write(convert_to_terraform(zone, provider, maximum_ttl)) convert_zonefiles(inputs, outputs, _transform_to_terraform) if __name__ == "__main__": command()
zonefile-migrate
/zonefile-migrate-0.4.4.tar.gz/zonefile-migrate-0.4.4/src/zonefile_migrate/to_terraform.py
to_terraform.py
import click import re from slugify import slugify from encodings import idna import encodings.idna from pathlib import Path from ruamel.yaml import YAML, CommentedMap from zonefile_migrate.logger import log from easyzone import easyzone from zonefile_migrate.dns_record_set import create_from_zone from zonefile_migrate.utils import ( get_all_zonefiles_in_path, convert_zonefiles, target_file, ) def logical_resource_id(name: str): """ create a CloudFormation logical resource id for `name`, ignoring non letters or digits. >>> logical_resource_id('asample.org') 'AsampleOrg' >>> logical_resource_id('v-r-v.com') 'VRVCom' >>> logical_resource_id('chapter9.com') 'Chapter9Com' >>> logical_resource_id('/is/this/not/pretty?') 'IsThisNotPretty' """ return re.sub(r"\W+", " ", name).title().replace(" ", "") def generate_unique_logical_resource_id(prefix: str, resources: dict) -> str: """ generates a unique logical resource id using `prefix` as a key into `resources`. This is to avoid potential name clashes in the CloudFormation Resource section. >>> generate_unique_logical_resource_id('key', {}) 'key' >>> generate_unique_logical_resource_id('key', {'key': 'value'}) 'key1' >>> generate_unique_logical_resource_id('key', {'key': 'value', 'key1': 'value1'}) 'key2' """ same_prefix = set(filter(lambda n: n.startswith(prefix), resources.keys())) if not same_prefix: return prefix count = 1 while f"{prefix}{count}" in same_prefix: count = count + 1 return f"{prefix}{count}" def convert_to_cloudformation(zone: easyzone.Zone, maximum_ttl: int) -> dict: """ Converts the zonefile into a CloudFormation template. """ ttl = zone.root.ttl domain_name = zone.domain idna_domain_name = domain_name.encode("idna").decode("ascii") result = CommentedMap() result["AWSTemplateFormatVersion"] = "2010-09-09" resources = CommentedMap() resources["HostedZone"] = CommentedMap( {"Type": "AWS::Route53::HostedZone", "Properties": {"Name": idna_domain_name}} ) result["Resources"] = resources for record_set in create_from_zone(zone): if record_set.name in [zone.domain, idna_domain_name]: if record_set.rectype in ["NS", "SOA"]: log.debug("ignoring %s records for origin %s", record_set.rectype, zone.domain) continue logical_name = generate_unique_logical_resource_id( re.sub( r"[^0-9a-zA-Z]", "", logical_resource_id( re.sub( r"^\*", "wildcard", record_set.name.removesuffix("." + zone.domain) if record_set.name != zone.domain else "Origin", ) ), ) + record_set.rectype + "Record", resources, ) resources[logical_name] = CommentedMap( { "Type": "AWS::Route53::RecordSet", "Properties": { "Name": record_set.name, "Type": record_set.rectype, "ResourceRecords": record_set.rrdatas, "TTL": maximum_ttl if maximum_ttl and record_set.ttl > maximum_ttl else record_set.ttl, "HostedZoneId": {"Ref": "HostedZone"}, }, } ) return result def common_parent(one: Path, other: Path) -> Path: """ returns the commons parent of two paths >>> common_parent(Path('/a/b/c'), Path('/a/e/f')).as_posix() '/a' >>> common_parent(Path('/one/b/c'), Path('/other/f')).as_posix() '/' >>> common_parent(Path('/usr/share/var/lib/one'), Path('/usr/share/var/lib/other')).as_posix() '/usr/share/var/lib' """ one_parts = one.absolute().parts other_parts = other.absolute().parts for i, part in enumerate(one_parts): if i >= len(other_parts): break if part != other_parts[i]: break return Path(*one_parts[:i]) def template_in_sceptre_project( template_path: Path, sceptre_config_directory: Path ) -> bool: """ determines whether the template directory is in the sceptre project directory. >>> template_in_sceptre_project(Path('example/templates/cfn-template-name'), Path('example/config/dns')) True >>> template_in_sceptre_project(Path('example/templates/cfn-template-name'), Path('somewhere-else/config/dns')) False >>> template_in_sceptre_project(Path('templates/cfn-template-name'), Path('example/config/dns')) False """ parent = common_parent(template_path, sceptre_config_directory) sceptre_dir = sceptre_config_directory.absolute().relative_to(parent) templates_dir = template_path.absolute().relative_to(parent) return sceptre_dir.parts[0] == "config" and templates_dir.parts[0] == "templates" def generate_sceptre_configuration( zone: easyzone.Zone, template: Path, config_directory: Path ): """ generates a sceptre stack config for the CloudFormation template for the zone. """ stack_name = "zone-" + re.sub( r"-{2,}", "-", re.sub(r"[^\w]+", "-", slugify(zone.domain)) ).strip("-") stack_config = config_directory.joinpath(Path(stack_name).with_suffix(".yaml")) # create empty stack group configuration file config_directory.mkdir(parents=True, exist_ok=True) group_config = config_directory.joinpath("config.yaml") if not group_config.exists(): with group_config.open("w") as file: pass # create stack configuration file config = None if stack_config.exists(): with stack_config.open("r") as file: config = YAML().load(file) if not config: config = {} parent = common_parent(config_directory, template) template_path = ( template.absolute().relative_to(parent.joinpath("templates")).as_posix() ) if config.get("template_path") != template_path: config["template_path"] = template_path with stack_config.open("w") as file: YAML().dump(config, file) @click.command(name="to-cloudformation") @click.option( "--sceptre-group", required=False, type=click.Path(file_okay=False), help="to write sceptre stack group configuration", ) @click.option( "--maximum-ttl", required=False, type=int, help="maximum TTL of domain name records", ) @click.argument("src", nargs=-1, type=click.Path()) @click.argument("dst", nargs=1, type=click.Path()) def command(sceptre_group, maximum_ttl, src, dst): """ Converts one or more `SRC` zonefiles into AWS CloudFormation templates in `DST`. Optionally generates the Sceptre stack config for each of the templates in the `--sceptre-group` directoru. Each generated CloudFormation template contains a single Route53 HostedZone and all associated ResourceRecordSet. The SOA and NS records for the origin domain are not copied into the template. The zonefiles must contain a $ORIGIN and $TTL statement. If the SRC points to a directory all files which contain one of these statements will be converted. If a $ORIGIN is missing, the name of the file will be used as the domain name. You may override the maximum TTL of records through the option --maximum-ttl """ if sceptre_group: sceptre_group = Path(sceptre_group) if not src: raise click.UsageError("no source files were specified") inputs = get_all_zonefiles_in_path(src) if len(inputs) == 0: click.UsageError("no zonefiles were found") dst = Path(dst) if len(inputs) > 1: if dst.exists() and not dst.is_dir(): raise click.UsageError(f"{dst} is not a directory") if not dst.exists(): dst.mkdir(parents=True, exist_ok=True) outputs = list(map(lambda d: target_file(d, dst, ".yaml"), inputs)) def transform_to_cloudformation(zone: easyzone.Zone, output: Path): with output.open("w") as file: YAML().dump(convert_to_cloudformation(zone, maximum_ttl), stream=file) if sceptre_group: generate_sceptre_configuration(zone, output, sceptre_group) convert_zonefiles(inputs, outputs, transform_to_cloudformation) if __name__ == "__main__": command()
zonefile-migrate
/zonefile-migrate-0.4.4.tar.gz/zonefile-migrate-0.4.4/src/zonefile_migrate/to_cloudformation.py
to_cloudformation.py
import re from pathlib import Path from typing import Callable, List from easyzone import easyzone from zonefile_migrate.logger import log def is_zonefile(path: Path) -> bool: """ returns true if the file pointed to by `path` contains a $ORIGIN or $TTL pragma, otherwise False """ if path.exists() and path.is_file(): with path.open("r") as file: for line in file: if re.search(r"^\s*\$(ORIGIN|TTL)\s+", line, re.IGNORECASE): return True return False def get_all_zonefiles_in_path(src: [Path]) -> [Path]: """ creates a list of filenames of zonefiles from a list of paths. If the path is not a directory, the path will be added as is. If the path points to a directory, the files of the directory will be scanned to determined if they are a zonefile (see is_zonefile) """ inputs = [] for filename in map(lambda s: Path(s), src): if not filename.exists(): raise ValueError(f"{filename} does not exist") if filename.is_dir(): inputs.extend( [f for f in filename.iterdir() if f.is_file() and is_zonefile(f)] ) else: inputs.append(filename) return inputs def convert_zonefiles( inputs: [Path], outputs: [Path], transform: Callable[[easyzone.Zone, Path], None] ): for i, input in enumerate(map(lambda s: Path(s), inputs)): with input.open("r") as file: content = file.read() found = re.search( r"\$ORIGIN\s+(?P<domain_name>.*)\s*", content, re.MULTILINE | re.IGNORECASE, ) if found: domain_name = found.group("domain_name") else: domain_name = input.name.removesuffix(".zone") log.warning( "could not find $ORIGIN from zone file %s, using %s", input, domain_name, ) try: log.info("reading zonefile %s", input.as_posix()) zone = easyzone.zone_from_file(domain_name, input.as_posix()) transform(zone, outputs[i]) except SyntaxError as error: log.error(error) exit(1) def target_file(src: Path, dst: Path, extension: str) -> Path: if dst.is_file(): return dst if src.suffix == ".zone": return dst.joinpath(src.name).with_suffix(extension) return dst.joinpath(src.name + extension)
zonefile-migrate
/zonefile-migrate-0.4.4.tar.gz/zonefile-migrate-0.4.4/src/zonefile_migrate/utils.py
utils.py
# zone-file-parser [![unit-tests](https://github.com/aredwood/zonefile-parser/actions/workflows/unit-test.yml/badge.svg)](https://github.com/aredwood/zonefile-parser/actions/workflows/unit-test.yml) ! this package is not currently RFC compliant, but if you open up an issue on github - i'm more than likely to attempt to solve it. ## install ```bash pip install zonefile-parser ``` ## usage ```python import zonefile_parser with open("zone.txt","r") as stream: content = stream.read() records = zonefile_parser.parse(content) for record in records: print(record) ``` ``` {'rtype': 'SOA', 'name': 'mywebsite.com.', 'rclass': 'IN', 'rdata': {'mname': 'mywebsite.com.', 'rname': 'root.mywebsite.com.', 'serial': '2034847964', 'refresh': '7200', 'retry': '3600', 'expire': '86400', 'minimum': '3600'}, 'ttl': '3600'} {'rtype': 'A', 'name': 'mywebsite.com.', 'rclass': 'IN', 'rdata': {'value': '105.33.55.52'}, 'ttl': '7200'} {'rtype': 'MX', 'name': 'mywebsite.com.', 'rclass': 'IN', 'rdata': {'priority': '10', 'host': 'alt3.aspmx.l.google.com.'}, 'ttl': '1'} {'rtype': 'MX', 'name': 'mywebsite.com.', 'rclass': 'IN', 'rdata': {'priority': '5', 'host': 'alt2.aspmx.l.google.com.'}, 'ttl': '1'} {'rtype': 'TXT', 'name': 'mywebsite.com.', 'rclass': 'IN', 'rdata': {'value': 'v=spf1 include:_spf.google.com ~all'}, 'ttl': '1'} ``` Detailed Documentation -> [https://aredwood.github.io/zonefile-parser/](https://aredwood.github.io/zonefile-parser/)
zonefile-parser
/zonefile_parser-0.1.14.tar.gz/zonefile_parser-0.1.14/README.md
README.md
import re from typing import List def remove_comments(line:str): for index,character in enumerate(line): if character == ";" and not is_in_quote(line,index): line = line[:index] break return line def is_in_quote(text:str,index:int): return text[:index].count("\"") % 2 == 1 # TODO remove def remove_trailing_spaces(line:str): return line # TODO remove def collapse_brackets(text:str): return text def is_integer(n): try: int(n) return True except ValueError: return False def parse_bind(bind:str): periods = { "s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800 } seconds = 0 parts = [] buffer = "" for char in bind: if is_integer(char): buffer += char else: parts.append(buffer + char) buffer = "" for part in parts: period = part[-1] amount = int(part.replace(period,"")) seconds += amount * periods[period.lower()] return seconds # TODO unit test def default_ttl(text:str): lines = text.splitlines() for line in lines: if "$TTL".casefold() in line.casefold(): ttl_str = line.split(" ")[1] try: ttl = int(ttl_str) return int(ttl) except ValueError: # the value could be BIND format, attempt to parse # https://www.zytrax.com/books//dns/apa/time.html ttl = parse_bind(ttl_str) return ttl return None # TODO write test case def default_origin(text:str): lines = text.splitlines() for line in lines: if "$ORIGIN".casefold() in line.casefold(): origin = line.split(" ")[1] return origin return None # ensure that the string: # 1. ends and starts with round brackets # 2. there is no whitespace between the brackets and the content # e.g. " ( 'test string') " should be "('test string')" def trim_brackets(input_string:str): # regex that matches either round bracket, # preceded or followed by whitespace # pattern = re.compile(r"(\(\s)|(\s\()|(\)\s)|(\s\))") pattern = re.compile(r"(\(\s)|(\)\s)|(\s\))") # print(re.match(pattern,input_string).groups()) # while re.search(pattern, input_string) is not None: while re.search(pattern, input_string) is not None: matched_groups = (g for g in re.search(pattern, input_string).groups() if g is not None) for group in matched_groups: input_string = input_string.replace( group, group.strip() ) return input_string # worth renaming tbh def remove_whitespace_between_quotes_between_brackets(input_string:str): whitespace_pattern = re.compile(r'"(.*?)"') bracket_pattern = re.compile(r"\((.*?)\)") # get bracket portion of record bracket_match = re.search(bracket_pattern,input_string) if bracket_match is None: return input_string bracket_contents = bracket_match.group(0) bracket_contents_cleaned = "(" + "".join( re.findall(whitespace_pattern, bracket_contents) ) + ")" result = re.sub( bracket_pattern, bracket_contents_cleaned, input_string ) print(result) return result def collapse_lines(lines:List[str],delimiter = ""): buffer = [] collapsed_lines = [] for line in lines: # if the single line has both a closing and # opening bracket, then it can be added straight away # because it cannot be further collapsed if "(" in line and ")" in line: collapsed_lines.append(trim_brackets(line)) # start of a multi-line record, store in buffer elif "(" in line: buffer.append(line) # add the line to the buffer, the buffer forms a single record # close the buffer elif ")" in line: buffer.append(line) # remove whitespace between quotes, between brackets collapsed_lines.append(delimiter.join(buffer)) buffer = "" # if the buffer has content in it, add current line elif len(buffer) > 0: buffer.append(line) # record is not part of a multiline record, no alteration needed. else: collapsed_lines.append(line) return collapsed_lines # TODO unit test # TODO refactor def find_soa_lines(text:str): lines = text.splitlines() soa_start_line = 0 soa_end_line = 0 find_bracket = False soa_found = False for line_number in range(0,len(lines)-1): line = lines[line_number] if "SOA" in line.upper(): soa_found = True soa_start_line = line_number if "(" in line: find_bracket = True else: soa_end_line = soa_start_line break if ")" in line and find_bracket is True: soa_end_line = line_number break if not soa_found: return None else: return range(soa_start_line,soa_end_line + 1) # TODO unit test def parted_soa(text:str): # flatten text = text.replace("\n","") # part out the soa parts = text.split() # remove multiple spaces, and replace them with a single space parts = list( filter( lambda x : ")" not in x and "(" not in x, parts ) ) return parts
zonefile-parser
/zonefile_parser-0.1.14.tar.gz/zonefile_parser-0.1.14/zonefile_parser/helper.py
helper.py
import os from zonefile_parser.helper import remove_comments from zonefile_parser.helper import remove_trailing_spaces from zonefile_parser.helper import default_ttl from zonefile_parser.helper import default_origin from zonefile_parser.helper import find_soa_lines from zonefile_parser.helper import parted_soa from zonefile_parser.parser import parse_record from zonefile_parser.helper import collapse_lines from zonefile_parser.helper import trim_brackets from zonefile_parser.helper import remove_whitespace_between_quotes_between_brackets import shlex def clean(text:str): lines = text.splitlines() clean_lines = [] for line in lines: line = remove_comments(line) line = remove_trailing_spaces(line) if len(line) == 0: continue clean_lines.append(line) return "\n".join(clean_lines) # TODO unit test # TODO break apart # TODO error handling def parse(text:str): text = clean(text) raw_lines = text.splitlines() # function to collapse records that are spread with brackets lines = collapse_lines(raw_lines) ttl = default_ttl(text) origin = default_origin(text) default_rclass = "IN" # find the SOA, process it, and add it back as a single line soa_lines = find_soa_lines(text) if soa_lines is not None: raw_soa = "\n".join([lines[index] for index in soa_lines]) soa_parts = parted_soa(raw_soa) for index in reversed(soa_lines): lines.pop(index) lines.insert(soa_lines[0]," ".join(soa_parts)) # remove all the $TTL & $ORIGIN lines, we have the values, # they are no longer needed. record_lines = list( filter( lambda x : "$TTL".casefold() not in x.casefold() and "$ORIGIN".casefold() not in x.casefold(), lines ) ) # each line now represents a single record # we need to fill in the name of each record # go through the zone file and add a name to every record normalized_records = [] last_name = None for record_line in record_lines: # replace all tabs with spaces record_line = record_line.replace("\t"," ") name = record_line[:record_line.index(" ")] # if the line starts with "@", replace it with the origin if record_line[0] == "@" and origin is not None: record_line = record_line.replace("@",origin) last_name = origin # if the line behinds with a space, # it inherits the name of the previously processed record elif record_line[0] == " ": record_line = last_name + record_line # if you specify a name, add the origin to the end of the name # provided that the name doesnt already have the origin # # $ORIGIN example.com # test test.example.com # test.example.com test.example.com elif origin is not None and not name.endswith(origin): record_line = record_line.replace(name,name + "." + origin) else: last_name = name # clean up any records that have brackets record_line = remove_whitespace_between_quotes_between_brackets(record_line) record_line = trim_brackets(record_line) normalized_records.append(record_line) normalized_records = list( map( lambda x : shlex.split(x), normalized_records ) ) # collapse lines again due to shlex handling normalized_records = list(map( lambda x : collapse_lines(x," "), normalized_records )) # add a TTL to records where one doesn't exist def add_ttl(record:list): if not record[1].isdigit(): record.insert(1,ttl) return record # add an rclass (defaults to IN) when one isn't present def add_rclass(record:list): if not (str(record[2]).upper() in ('IN','CS','CH','HS')): record.insert(2,default_rclass) return record normalized_records = list( map( lambda x : add_ttl(x), normalized_records ) ) normalized_records = list( map( lambda x : add_rclass(x), normalized_records ) ) normalized_records = list( map( lambda x : parse_record(x), normalized_records ) ) return normalized_records
zonefile-parser
/zonefile_parser-0.1.14.tar.gz/zonefile_parser-0.1.14/zonefile_parser/main.py
main.py
from zonefile_parser.record import Record from enum import IntEnum import re class RecordEnum(IntEnum): NAME = 0 TTL = 1 RCLASS = 2 RTYPE = 3 RDATA = 4 MX_PRIORITY = 4 MX_HOST = 5 SOA_MNAME = 4 SOA_RNAME = 5 SOA_SERIAL = 6 SOA_REFRESH = 7 SOA_RETRY = 8 SOA_EXPIRE = 9 SOA_MINIMUM = 10 SRV_PRIORITY = 4 SRV_WEIGHT= 5 SRV_PORT = 6 SRV_HOST = 7 CAA_FLAG = 4 CAA_TAG = 5 CAA_VALUE = 6 # TODO unit test def parse_record(parts:list) -> Record: record = Record() record.set_name(parts[RecordEnum.NAME]) record.set_ttl(parts[RecordEnum.TTL]) record.set_rclass(parts[RecordEnum.RCLASS].upper()) record.set_rtype(parts[RecordEnum.RTYPE].upper()) # rdata is unique for MX, OA, SRV and CAA, everything else is the same. if record.rtype not in ["MX","SOA","SRV","CAA"]: # if the rdata is surrounded by round brackets they can be removed # as they are just containers for the data within, see RFC1035 5.1 rdata = re.sub( # a round bracket at the end or start re.compile(r"(^\()|(\)$)"), "", parts[RecordEnum.RDATA] ) record.set_rdata({ "value":rdata }) elif record.rtype == "MX": # the record is a SOA, MX, SRV or CAA record.set_rdata({ "priority": parts[RecordEnum.MX_PRIORITY], "host":parts[RecordEnum.MX_HOST] }) elif record.rtype == "SOA": record.set_rdata({ "mname": parts[RecordEnum.SOA_MNAME], "rname": parts[RecordEnum.SOA_RNAME], "serial": parts[RecordEnum.SOA_SERIAL], "refresh": parts[RecordEnum.SOA_REFRESH], "retry": parts[RecordEnum.SOA_RETRY], "expire": parts[RecordEnum.SOA_EXPIRE], "minimum": parts[RecordEnum.SOA_MINIMUM] }) elif record.rtype == "SRV": record.set_rdata({ "priority": parts[RecordEnum.SRV_PRIORITY], "weight": parts[RecordEnum.SRV_WEIGHT], "port": parts[RecordEnum.SRV_PORT], "host": parts[RecordEnum.SRV_HOST] }) elif record.rtype == "CAA": record.set_rdata({ "flag": parts[RecordEnum.CAA_FLAG], "tag": parts[RecordEnum.CAA_TAG], "value": parts[RecordEnum.CAA_VALUE], }) return record
zonefile-parser
/zonefile_parser-0.1.14.tar.gz/zonefile_parser-0.1.14/zonefile_parser/parser.py
parser.py
import copy import datetime import time import argparse from collections import defaultdict from .configs import SUPPORTED_RECORDS, DEFAULT_TEMPLATE from .exceptions import InvalidLineException class ZonefileLineParser(argparse.ArgumentParser): def error(self, message): """ Silent error message """ raise InvalidLineException(message) def make_rr_subparser(subparsers, rec_type, args_and_types): """ Make a subparser for a given type of DNS record """ sp = subparsers.add_parser(rec_type) sp.add_argument("name", type=str) sp.add_argument("ttl", type=int, nargs='?') sp.add_argument(rec_type, type=str) for (argname, argtype) in args_and_types: sp.add_argument(argname, type=argtype) return sp def make_parser(): """ Make an ArgumentParser that accepts DNS RRs """ line_parser = ZonefileLineParser() subparsers = line_parser.add_subparsers() # parse $ORIGIN sp = subparsers.add_parser("$ORIGIN") sp.add_argument("$ORIGIN", type=str) # parse $TTL sp = subparsers.add_parser("$TTL") sp.add_argument("$TTL", type=int) # parse each RR args_and_types = [ ("mname", str), ("rname", str), ("serial", int), ("refresh", int), ("retry", int), ("expire", int), ("minimum", int) ] make_rr_subparser(subparsers, "SOA", args_and_types) make_rr_subparser(subparsers, "NS", [("host", str)]) make_rr_subparser(subparsers, "A", [("ip", str)]) make_rr_subparser(subparsers, "AAAA", [("ip", str)]) make_rr_subparser(subparsers, "CNAME", [("alias", str)]) make_rr_subparser(subparsers, "MX", [("preference", str), ("host", str)]) make_rr_subparser(subparsers, "TXT", [("txt", str)]) make_rr_subparser(subparsers, "PTR", [("host", str)]) make_rr_subparser(subparsers, "SRV", [("priority", int), ("weight", int), ("port", int), ("target", str)]) make_rr_subparser(subparsers, "SPF", [("data", str)]) make_rr_subparser(subparsers, "URI", [("priority", int), ("weight", int), ("target", str)]) return line_parser def tokenize_line(line): """ Tokenize a line: * split tokens on whitespace * treat quoted strings as a single token * drop comments * handle escaped spaces and comment delimiters """ ret = [] escape = False quote = False tokbuf = "" ll = list(line) while len(ll) > 0: c = ll.pop(0) if c.isspace(): if not quote and not escape: # end of token if len(tokbuf) > 0: ret.append(tokbuf) tokbuf = "" elif quote: # in quotes tokbuf += c elif escape: # escaped space tokbuf += c escape = False else: tokbuf = "" continue if c == '\\': escape = True continue elif c == '"': if not escape: if quote: # end of quote ret.append(tokbuf) tokbuf = "" quote = False continue else: # beginning of quote quote = True continue elif c == ';': if not escape: # comment ret.append(tokbuf) tokbuf = "" break # normal character tokbuf += c escape = False if len(tokbuf.strip(" ").strip("\n")) > 0: ret.append(tokbuf) return ret def serialize(tokens): """ Serialize tokens: * quote whitespace-containing tokens * escape semicolons """ ret = [] for tok in tokens: if " " in tok: tok = '"%s"' % tok if ";" in tok: tok = tok.replace(";", "\;") ret.append(tok) return " ".join(ret) def remove_comments(text): """ Remove comments from a zonefile """ ret = [] lines = text.split("\n") for line in lines: if len(line) == 0: continue line = serialize(tokenize_line(line)) ret.append(line) return "\n".join(ret) def flatten(text): """ Flatten the text: * make sure each record is on one line. * remove parenthesis """ lines = text.split("\n") # tokens: sequence of non-whitespace separated by '' where a newline was tokens = [] for l in lines: if len(l) == 0: continue l = l.replace("\t", " ") tokens += filter(lambda x: len(x) > 0, l.split(" ")) + [''] # find (...) and turn it into a single line ("capture" it) capturing = False captured = [] flattened = [] while len(tokens) > 0: tok = tokens.pop(0) if not capturing and len(tok) == 0: # normal end-of-line if len(captured) > 0: flattened.append(" ".join(captured)) captured = [] continue if tok.startswith("("): # begin grouping tok = tok.lstrip("(") capturing = True if capturing and tok.endswith(")"): # end grouping. next end-of-line will turn this sequence into a flat line tok = tok.rstrip(")") capturing = False captured.append(tok) return "\n".join(flattened) def remove_class(text): """ Remove the CLASS from each DNS record, if present. The only class that gets used today (for all intents and purposes) is 'IN'. """ # see RFC 1035 for list of classes lines = text.split("\n") ret = [] for line in lines: tokens = tokenize_line(line) tokens_upper = [t.upper() for t in tokens] if "IN" in tokens_upper: tokens.remove("IN") elif "CS" in tokens_upper: tokens.remove("CS") elif "CH" in tokens_upper: tokens.remove("CH") elif "HS" in tokens_upper: tokens.remove("HS") ret.append(serialize(tokens)) return "\n".join(ret) def add_default_name(text): """ Go through each line of the text and ensure that a name is defined. Use '@' if there is none. """ global SUPPORTED_RECORDS lines = text.split("\n") ret = [] for line in lines: tokens = tokenize_line(line) if tokens[0] in SUPPORTED_RECORDS and not tokens[0].startswith("$"): # add back the name tokens = ['@'] + tokens ret.append(serialize(tokens)) return "\n".join(ret) def parse_line(parser, record_token, parsed_records): """ Given the parser, capitalized list of a line's tokens, and the current set of records parsed so far, parse it into a dictionary. Return the new set of parsed records. Raise an exception on error. """ global SUPPORTED_RECORDS line = " ".join(record_token) # match parser to record type if len(record_token) >= 2 and record_token[1] in SUPPORTED_RECORDS: # with no ttl record_token = [record_token[1]] + record_token elif len(record_token) >= 3 and record_token[2] in SUPPORTED_RECORDS: # with ttl record_token = [record_token[2]] + record_token try: rr, unmatched = parser.parse_known_args(record_token) assert len(unmatched) == 0, "Unmatched fields: %s" % unmatched except (SystemExit, AssertionError, InvalidLineException): # invalid argument raise InvalidLineException(line) record_dict = rr.__dict__ # what kind of record? including origin and ttl record_type = None for key in record_dict.keys(): if key in SUPPORTED_RECORDS and (key.startswith("$") or record_dict[key] == key): record_type = key if record_dict[key] == key: del record_dict[key] break assert record_type is not None, "Unknown record type in %s" % rr # clean fields for field in record_dict.keys(): if record_dict[field] is None: del record_dict[field] current_origin = record_dict.get('$ORIGIN', parsed_records.get('$ORIGIN', None)) # special record-specific fix-ups if record_type == 'PTR': record_dict['fullname'] = record_dict['name'] + '.' + current_origin if len(record_dict) > 0: if record_type.startswith("$"): # put the value directly record_dict_key = record_type.lower().replace('$', '') parsed_records[record_dict_key] = record_dict[record_type] else: record_dict_key = record_type.lower() parsed_records[record_dict_key].append(record_dict) return parsed_records def parse_lines(text, ignore_invalid=False): """ Parse a zonefile into a dict. @text must be flattened--each record must be on one line. Also, all comments must be removed. """ json_zone_file = defaultdict(list) record_lines = text.split("\n") parser = make_parser() for record_line in record_lines: record_token = tokenize_line(record_line) try: json_zone_file = parse_line(parser, record_token, json_zone_file) except InvalidLineException: if ignore_invalid: continue else: raise return json_zone_file def parse_zone_file(text, ignore_invalid=False): """ Parse a zonefile into a dict """ text = remove_comments(text) text = flatten(text) text = remove_class(text) text = add_default_name(text) json_zone_file = parse_lines(text, ignore_invalid=ignore_invalid) return json_zone_file
zonefile
/zonefile-0.1.1.tar.gz/zonefile-0.1.1/zone_file/parse_zone_file.py
parse_zone_file.py
from .record_processors import ( process_origin, process_ttl, process_soa, process_ns, process_a, process_aaaa, process_cname, process_mx, process_ptr, process_txt, process_srv, process_spf, process_uri ) from .configs import DEFAULT_TEMPLATE def make_zone_file(json_zone_file, template=None): """ Generate the DNS zonefile, given a json-encoded description of the zone file (@json_zone_file) and the template to fill in (@template) json_zone_file = { "$origin": origin server, "$ttl": default time-to-live, "soa": [ soa records ], "ns": [ ns records ], "a": [ a records ], "aaaa": [ aaaa records ] "cname": [ cname records ] "mx": [ mx records ] "ptr": [ ptr records ] "txt": [ txt records ] "srv": [ srv records ] "spf": [ spf records ] "uri": [ uri records ] } """ if template is None: template = DEFAULT_TEMPLATE[:] soa_records = [json_zone_file.get('soa')] if json_zone_file.get('soa') else None zone_file = template zone_file = process_origin(json_zone_file.get('$origin', None), zone_file) zone_file = process_ttl(json_zone_file.get('$ttl', None), zone_file) zone_file = process_soa(soa_records, zone_file) zone_file = process_ns(json_zone_file.get('ns', None), zone_file) zone_file = process_a(json_zone_file.get('a', None), zone_file) zone_file = process_aaaa(json_zone_file.get('aaaa', None), zone_file) zone_file = process_cname(json_zone_file.get('cname', None), zone_file) zone_file = process_mx(json_zone_file.get('mx', None), zone_file) zone_file = process_ptr(json_zone_file.get('ptr', None), zone_file) zone_file = process_txt(json_zone_file.get('txt', None), zone_file) zone_file = process_srv(json_zone_file.get('srv', None), zone_file) zone_file = process_spf(json_zone_file.get('spf', None), zone_file) zone_file = process_uri(json_zone_file.get('uri', None), zone_file) # remove newlines, but terminate with one zone_file = "\n".join( filter( lambda l: len(l.strip()) > 0, [tl.strip() for tl in zone_file.split("\n")] ) ) + "\n" return zone_file
zonefile
/zonefile-0.1.1.tar.gz/zonefile-0.1.1/zone_file/make_zone_file.py
make_zone_file.py
import copy def process_origin(data, template): """ Replace {$origin} in template with a serialized $ORIGIN record """ record = "" if data is not None: record += "$ORIGIN %s" % data return template.replace("{$origin}", record) def process_ttl(data, template): """ Replace {$ttl} in template with a serialized $TTL record """ record = "" if data is not None: record += "$TTL %s" % data return template.replace("{$ttl}", record) def process_soa(data, template): """ Replace {SOA} in template with a set of serialized SOA records """ record = template[:] if data is not None: assert len(data) == 1, "Only support one SOA RR at this time" data = data[0] soadat = [] domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields + param_fields: assert f in data.keys(), "Missing '%s' (%s)" % (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append("IN") soadat.append("SOA") for key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append("(") for key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(")") soa_txt = " ".join(soadat) record = record.replace("{soa}", soa_txt) else: # clear all SOA fields record = record.replace("{soa}", "") return record def quote_field(data, field): """ Quote a field in a list of DNS records. Return the new data records. """ if data is None: return None data_dup = copy.deepcopy(data) for i in xrange(0, len(data_dup)): data_dup[i][field] = '"%s"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(";", "\;") return data_dup def process_rr(data, record_type, record_keys, field, template): """ Meta method: Replace $field in template with the serialized $record_type records, using @record_key from each datum. """ if data is None: return template.replace(field, "") if type(record_keys) == list: pass elif type(record_keys) == str: record_keys = [record_keys] else: raise ValueError("Invalid record keys") assert type(data) == list, "Data must be a list" record = "" for i in xrange(0, len(data)): for record_key in record_keys: assert record_key in data[i].keys(), "Missing '%s'" % record_key record_data = [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys] record += " ".join(record_data) + "\n" return template.replace(field, record) def process_ns(data, template): """ Replace {ns} in template with the serialized NS records """ return process_rr(data, "NS", "host", "{ns}", template) def process_a(data, template): """ Replace {a} in template with the serialized A records """ return process_rr(data, "A", "ip", "{a}", template) def process_aaaa(data, template): """ Replace {aaaa} in template with the serialized A records """ return process_rr(data, "AAAA", "ip", "{aaaa}", template) def process_cname(data, template): """ Replace {cname} in template with the serialized CNAME records """ return process_rr(data, "CNAME", "alias", "{cname}", template) def process_mx(data, template): """ Replace {mx} in template with the serialized MX records """ return process_rr(data, "MX", ["preference", "host"], "{mx}", template) def process_ptr(data, template): """ Replace {ptr} in template with the serialized PTR records """ return process_rr(data, "PTR", "host", "{ptr}", template) def process_txt(data, template): """ Replace {txt} in template with the serialized TXT records """ # quote txt data_dup = quote_field(data, "txt") return process_rr(data_dup, "TXT", "txt", "{txt}", template) def process_srv(data, template): """ Replace {srv} in template with the serialized SRV records """ return process_rr(data, "SRV", ["priority", "weight", "port", "target"], "{srv}", template) def process_spf(data, template): """ Replace {spf} in template with the serialized SPF records """ return process_rr(data, "SPF", "data", "{spf}", template) def process_uri(data, template): """ Replace {uri} in templtae with the serialized URI records """ # quote target data_dup = quote_field(data, "target") return process_rr(data_dup, "URI", ["priority", "weight", "target"], "{uri}", template)
zonefile
/zonefile-0.1.1.tar.gz/zonefile-0.1.1/zone_file/record_processors.py
record_processors.py
Zoner - A DNS zone management UI ================================ Overview -------- Zoner is a web application to make management of DNS zone files simple and easy. The authoritative copy of each domain remains in the original zone file, which Zoner reads & writes as needed, as opposed to storing domain details in a database. This means that zone files can still be edited manually and Zoner will pick up the changes as necessary. Zoner features: * Domain details remain in original zone files, not in a database. * Zoner reads & writes actual zone files, which can also be safely modified outside of Zoner. * Zone serial numbers are incremented automatically when changes are made. * Zoner can signal bind to reload a zone, via rndc. * An audit of all zone changes is maintained for each domain. Any previous version of a zone file can be inspected and zones can be rolled back to any previous version. Requirements: * Zoner is a Python application built with the TurboGears framework. Both Python and TurboGears (version 1.x) are required. * Zoner requires the easyzone and dnspython Python packages for DNS/zone management. * Zoner also requires SQLAlchemy, TGBooleanFormWidget and TGExpandingFormWidget Python packages. (All dependencies should be installed automatically if using setuptools, which will usually be the case for a properly installed TurboGears environment.) Installation ------------ The easiest way to install Zoner is by using setuptools:: $ easy_install zoner Alternatively, install TurboGears then download the Zoner package from http://pypi.python.org/pypi/zoner/ and install with:: $ python setup.py install Create a config file. A template sample-prod.cfg file is included with the package (or installed alongside the package). Example:: $ cp /usr/lib/python2.4/site-packages/zoner-1.3.1-py2.4.egg/config/sample-prod.cfg zoner.cfg Customise the config file, then initialise the database:: $ tg-admin sql create Next, create a user to login to the Zoner application with:: $ zoner_users -c zoner.cfg add Finally, start the Zoner application:: $ zoner zoner.cfg Point your browser at http://localhost:8080/ (or the appropriate host/port as per your configuration) and you should be able to login. Apache Proxy ------------ It is a common requirement to proxy this application behind an Apache hosted secure address. For example, let's say this application is listening locally on http://127.0.0.1:8080/ and Apache needs to proxy all requests to it from https://my.host.name/zoner/ Here is a sample of the Apache configuration (excluding all the directives not relevant to this example):: <VirtualHost _default_:443> #### Proxy Requests to Zoner under /zoner/ ProxyRequests Off ProxyPass /zoner/ http://127.0.0.1:8080/ ProxyPassReverse /zoner/ http://127.0.0.1:8080/ </VirtualHost> In your application config (dev.cfg or prod.cfg) you will want to add the following:: [global] server.webpath="/zoner" That should be all that is required.
zoner
/zoner-1.4.1.tar.gz/zoner-1.4.1/README.txt
README.txt
MIT License Copyright (c) 2023 nguemechieu. All rights reserved. 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.
zones
/zones-0.0.3.tar.gz/zones-0.0.3/LICENSE.md
LICENSE.md
# ZONES copyright (c) 2022 - 2023 !['ZONES'](./src/images/zones_ea.png) ## Icon !['ZONES'](./src/images/zones_ea.ico) # Description ZONES EA is an ai powered professional trading application using the standard platform MT4 ,MT5 and others # Architecture !['Architecture'](./src/images/Architecture/zones_ea/Slide3.PNG) !['Architecture'](./src/images/Architecture/zones_ea/Slide4.PNG) !['docs'](./src/License/LICENSE) ## Growing list of features: - AI Trading Terminal - Mysql database connection - Telegram client - screenshot - Trade Reports - Trade News event - Live trade on Telegram - Live trade copies - VPS - Upcoming features cryptocurrencies trading Terminal integration ![screenshot](MQL4/Files/USDCHF5.gif) # ________ Installation _____________ ## Requirements - Python ~= 3.11 - pyzmq - zmq - mysql - mql-zmq (library package) - pandas # Zones_EA.exe ,MT4 or MT5 Installation flow !['alt text'](src/images/ZONESEA/Slide2.PNG) ## Documentation See documentation [click here !](src/docs/ZONESEA.pdf) # Linux installation: You can run your strategies on linux through wine. Here is a ready docker Wine: [click here](https://hub.docker.com/docker-wine/nguemechieu/zones_ea) # Virtual environment - command: docker pull , docker run -d zones_ea - docker login - docker pull zones_ea - docker run -d zones_ea
zones
/zones-0.0.3.tar.gz/zones-0.0.3/README.md
README.md
import datetime import os from src.DwxClient import DwxClient class TickProcessor(object): def __init__(self, db, sleep_delay=0.005, # 5 ms for time.sleep() max_retry_command_seconds=10, # retry to send to commend for 10 seconds if not successful. verbose=True ): self.dat = {} self.lot = 0.01 self.price = 0.0 self.bid = 0.0 self.ask = 0.0 self.time_frame = 'H1' self.prices = {} self.symbol = "AUDUSD" self.db = db # if true, it will randomly try to open and close orders every few seconds. self.account_data = {} self._MarketStates = {} self.live_data: dict = {} self.MT4_directory_path = os.getenv("AppData") + "\\MetaQuotes\\Terminal" \ "\\3212703ED955F10C7534BE8497B221F4\\MQL4\\Files\\" self.server_status = { "status": "online", "server_time": datetime.datetime.utcnow().timestamp(), "server_time_utc": datetime.datetime.utcnow().isoformat(), "server_time_local": datetime.datetime.utcnow().astimezone().isoformat(), "message": "Connected to MetaTrader" } self.last_open_time = datetime.datetime.utcnow() self.last_modification_time = datetime.datetime.utcnow() self.dwx = DwxClient(self, metatrader_dir_path=self.MT4_directory_path, sleep_delay=sleep_delay, max_retry_command_seconds=max_retry_command_seconds, verbose=verbose,db=self.db) # request historic data: self.end = datetime.datetime.utcnow() self.start = self.end - datetime.timedelta(days=30) # last 30 days self.on_historic_trades() self.on_order_event() def on_historic_trades(self): print(f'historic_trades: {len(self.dwx.historic_trades)}') self.server_status['message'] = "On historic trades " + str(datetime.datetime.utcnow()) + " trades " + str( len(self.dwx.historic_trades)) self.account_data['trades'] = self.dwx.historic_trades def on_message(self, message): if message['type'] == 'ERROR': print(message['type'], '|', message['error_type'], '|', message['description']) self.server_status['status'] = 'offline' self.server_status['message'] = message['description'] elif message['type'] == 'INFO': print(message['type'], '|', message['message']) self.server_status['message'] = message['message'] elif message['type'] == 'TICK': print(message['type'], '|', message['symbol'], '|', message['bid'], '|', message['ask']) self.server_status['message'] = message['symbol'] elif message['type'] == 'BAR': print(message['type'], '|', message['symbol'], '|', message['time_frame'], '|', message['time'], '|', message['open'], '|', message['high'], '|', message['low'], '|', message['close'], '|', message['volume']) self.server_status['message'] = message['symbol'] # triggers when an order is added or removed, not when only modified. def on_order_event(self): print(f'on_order_event. open_orders: {len(self.dwx.open_orders)} open orders') self.server_status['message'] = "order event " + str(datetime.datetime.utcnow()) + " open orders " + \ str(len(self.dwx.open_orders))+" \n"+self.dwx.historic_trades.__str__() ########################################################################## # Here were i write my trading strange def save_to_db(self, _db): _db.save(self.dat) ##############################################################################
zones
/zones-0.0.3.tar.gz/zones-0.0.3/src/TickProcessor.py
TickProcessor.py
import datetime import json import os from os.path import join, exists from threading import Thread, Lock from time import sleep from traceback import print_exc import joblib import numpy as np import pandas as pd import requests import self from pandas import DataFrame from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.svm._libsvm import predict from ta.trend import MACD from tensorflow_estimator.python.estimator.canned.timeseries import model """Client class This class includes all of the functions needed for communication with MT4/MT5. """ def try_read_file(file_path: str) -> object: try: if exists(file_path): with open(file_path) as f: text = f.read() return text # can happen if mql writes to the file. don't print anything here. except (IOError, PermissionError): pass except Exception as e: print(e) print_exc() return '' def preprocess_data(data): # Calculate technical indicators (example: moving averages) data['SMA_10'] = data['close'].rolling(window=10).mean() data['SMA_50'] = data['close'].rolling(window=50).mean() # Create target variable (future price) by shifting the Close price data['Target'] = data['close'].shift(-1) # Drop rows with NaN values in the Target column (last row will have NaN) data.dropna(subset=['Target'], inplace=True) # Create features for the model x = data[['SMA_10', 'SMA_50']] y = data['Target'] return x, y def try_remove_file(file_path): for _ in range(10): try: os.remove(file_path) break except (IOError, PermissionError): pass except Exception as e: print(e) print_exc() def mm_size(sl_: float = 0.005): risk_percentage = 10 max_lot = 100000 min_lot = 0.01 lots = risk_percentage * 1.0 / 100 / sl_ / 1000000 if lots > max_lot: lots = max_lot elif lots < min_lot: lots = min_lot return lots def get_signal(prediction_): return 1 if prediction_ > 0 else -1 def calculate_macd(data=None): series = pd.Series(data) print(series) close_prices = series if len(close_prices) < 2: return 0, 0 macd, signal = MACD(close_prices) return macd, signal def predict_signal(symbol, data): if data is None or len(data) < 2: print("Not enough data for prediction") return 0 macd, signal = calculate_macd(data) prediction = predict(np.array([macd, signal]).reshape(1, -1)) print('Prediction: ', prediction) return get_signal(prediction_=prediction.array[0][0]) class DwxClient(object): def __init__(self, event_handler=None, metatrader_dir_path: str = "", sleep_delay=0.005, # 5 ms for time.sleep() # retry to send to commend for 10 seconds if not successful. max_retry_command_seconds=10, # to load orders from file on initialization. load_orders_from_file=True, verbose=True, db=None ): self.db_schema = None self.stop_loss = None self.take_profit = None self.path_account_data = None self._last_account_data_str = None self.balance = None self.sl = None self.model = None self.db = db self.clf_model = None self._last_market_data = {} self.mql_dir_path = metatrader_dir_path self.clf_save = None self.bar_data1 = None self.df_ = None self.market_data = {} self.data = {} self.dat = {} self.live_data = {} self.ask: float = 0.0 self.bid: float = 0.0 self.price: float = 0.0 self.time_frame = 'H1' self.prices = {} self.symbol = 'AUDUSD' self.account_data = {} self.server_status = { "status": "off", "message": "not connected", "server_time": datetime.datetime.now() } self.last_open_time = datetime.datetime.now() self.last_modification_time = 0 self.check_historic_trades = {} self.event_handler = event_handler self.sleep_delay = sleep_delay self.max_retry_command_seconds = max_retry_command_seconds self.load_orders_from_file = load_orders_from_file self.verbose = verbose self.command_id = 0 self.num_command_files = 50 self._last_messages_millis = 0 self._last_open_orders_str = "" self._last_messages_str = "" self._last_market_data_str = "" self._last_bar_data_str = "" self._last_historic_data_str = "" self._last_historic_trades_str = "" self.open_orders = {} self.account_info = {} self.bar_data = {} self.historic_data = {} self.historic_trades = {} self.last_bar_data = {} if not exists(metatrader_dir_path): # create directory os.makedirs(metatrader_dir_path) print('ERROR: metatrader_dir_path does not exist!') self.path_orders = join(metatrader_dir_path + "\\Files\\", "DWX\\", 'DWX_Orders.txt') self.path_messages = join(metatrader_dir_path, "DWX\\", 'DWX_Messages.txt') self.path_market_data = join(metatrader_dir_path, "DWX\\", 'DWX_Market_Data.txt') self.path_bar_data: str = join(metatrader_dir_path, "DWX\\", 'DWX_Bar_Data.txt') self.path_historic_data = join(metatrader_dir_path, "DWX\\", 'DWX_Historic_Data.txt') self.path_historic_trades = join(metatrader_dir_path, 'DWX\\', 'DWX_Historic_Trades.txt') self.path_orders_stored = join(metatrader_dir_path, 'DWX\\', 'DWX_Orders_Stored.txt') self.path_messages_stored = join(metatrader_dir_path, 'DWX\\', 'DWX_Messages_Stored.txt') self.path_commands_prefix = join(metatrader_dir_path, 'DWX\\', 'DWX_Commands_') self.path_commands_account_data = join(metatrader_dir_path, 'DWX\\', 'DWX_Commands_Account_Data.txt') self.ACTIVE = True self.START = False self.lock = Lock() self.load_messages() if self.load_orders_from_file: self.load_orders() self.reset_command_ids() # no need to wait. if self.event_handler: self.check_historic_data_Thread = Thread(target=self.check_historic_data, args=()) self.check_historic_data_Thread.daemon = True self.check_historic_data_Thread.start() self.check_market_data_Thread = Thread(target=self.check_market_data, args=()) self.check_market_data_Thread.daemon = True self.check_market_data_Thread.start() self.check_bar_data_Thread = Thread(target=self.check_bar_data, args=()) self.check_bar_data_Thread.daemon = True self.check_bar_data_Thread.start() self.check_account_data_Thread = Thread(target=self.check_account_data, args=()) self.messages_thread = Thread(target=self.check_messages, args=()) self.messages_thread.daemon = True self.messages_thread.start() self.open_orders_thread = Thread(target=self.check_open_orders, args=()) self.open_orders_thread.daemon = True self.open_orders_thread.start() self.start_() self._t = Thread(target=self.trader_, args=()) self._t.daemon = True self._t.start() """START can be used to check if the client has been initialized. """ def start_(self): self.START = True self.server_status['status'] = "running" """Tries to read a file. """ def set_trade_symbols(self, symbols=None, time_frame=None): if time_frame is None: time_frame = ['H1', 'M30'] if symbols is None: symbols = ['EURUSD'] self.server_status['message'] = "subscribed to " + str(symbols.__str__()) + " " + str( datetime.datetime.utcnow()) # subscribe to tick data: if self.subscribe_symbols(symbols): # subscribe to bar data: for symbol in symbols: self.subscribe_symbols_bar_data([[symbol, time_frame]]) """Tries to remove a file. """ """Regularly checks the file for open orders and triggers the event_handler.on_order_event() function. """ def close_signal(self, symbol, data): return get_signal(prediction_=predict_signal(symbol=symbol, data=data)) def check_open_orders(self): while self.ACTIVE: self.server_status['message'] = " check_open_orders " + str(datetime.datetime.utcnow()) sleep(self.sleep_delay) if self.START: text = try_read_file(self.path_orders) if len(text.strip()) == 0 or text == self._last_open_orders_str: continue self._last_open_orders_str = text data = json.loads(str(text)) self.server_status['message'] = " open_orders " + str(data) new_event = False for order_id, order in self.open_orders.items(): # also triggers if a pending order got filled? if order_id not in data['orders'].keys(): new_event = True if self.verbose: print('Order removed: ', order) for order_id, order in data['orders'].items(): if order_id not in self.open_orders: new_event = True if self.verbose: print('New order: ', order) self.account_info = data['account_info'] self.balance = data['balance'] self.open_orders = data['orders'] with open(self.path_orders_stored, 'w') as f: f.write(json.dumps(data)) if self.event_handler is not None and new_event: self.event_handler.on_order_event() else: if self.event_handler is not None: self.event_handler.on_order_event() """Regularly checks the file for messages and triggers the event_handler.on_message() function. """ def check_messages(self): while self.ACTIVE: sleep(self.sleep_delay) self.server_status['message'] = " check_messages " + str(datetime.datetime.utcnow()) if not self.START: continue text = try_read_file(self.path_messages) if len(text.strip()) == 0 or text == self._last_messages_str: continue self._last_messages_str = text data = json.loads(str(text)) self.server_status['message'] = " messages " + str(data) # use sorted() to make sure that we don't miss messages # because of (int(millis) > self._last_messages_millis). for millis, message in sorted(data.items()): if int(millis) > self._last_messages_millis: self._last_messages_millis = int(millis) print(message) if self.event_handler is not None: self.event_handler.on_message(message) with open(self.path_messages_stored, 'w') as f: f.write(json.dumps(data)) f.close() """Regularly checks the file for market data and triggers the event_handler.on_tick() function. """ def signal(self, symbol: str = 'AUDUSD', data: dict = None): self.server_status['message'] = 'signal ' + symbol + " " print(str(self.market_data)) if data.values() is None: return data2 = pd.DataFrame(data=data, columns=['open', 'high', 'low', 'close', 'volume']) series = pd.Series(data=data2['close'].values, dtype='float64', index=data2.index) macd0 = MACD(series) print("signal " + str(macd0.macd_signal())) self.server_status['message'] = "signal " + symbol + " " + str(macd0.macd_signal()) if datetime.datetime.utcnow() - self.last_open_time > datetime.timedelta(minutes=10): macd = 1 else: macd = -1 if macd > 0: return 1 elif macd < 0: return -1 else: return 0 def trader_(self): self.last_open_time = datetime.datetime.utcnow() # SET TRADING symbols symbols = ['EURUSD', 'NZDUSD'] time_frames = ['H1'] if self.set_trade_symbols(symbols=symbols, time_frame=time_frames): self.subscribe_symbols_bar_data( [[symbol, time_frame] for symbol in symbols for time_frame in time_frames]) self.subscribe_symbols_bar_data([[self.symbol, self.time_frame], [self.symbol, self.time_frame]]) self.server_status['status'] = "== Live Trading ==" self.server_status['message'] = "trader initialized " + str(datetime.datetime.utcnow()) else: self.server_status['status'] = "== Live Trading ==" self.server_status['message'] = "trader failed to initialize " + str(datetime.datetime.utcnow()) return while self.ACTIVE: # Create a 2D array to store the data if self.bar_data1 is None: print("last_bar_data is None" + str(self.bar_data1)) self.server_status['message'] = "last_bar_data is None " + str(datetime.datetime.utcnow()) return self.dat = self.bar_data1 print('dat ' + str(self.dat)) print(self.dat) row = ['open', 'high', 'low', 'close', 'volume'] self.df_ = DataFrame(data=self.dat, columns=row) self.df_['open'] = self.dat['open'] self.df_['high'] = self.dat['high'] self.df_['low'] = self.dat['low'] self.df_['close'] = self.dat['close'] self.df_['volume'] = self.dat['volume'] # Saving the data to database self.df_.to_sql("candles", con=self.db, schema=self.db_schema, if_exists='append', index=False) self.server_status['status'] = '======== Live Trading =======' self.server_status['message'] = "trader started \n" + str( datetime.datetime.utcnow()) + self.df_.__str__() ma = self._last_market_data self.ask = ma[self.symbol]['ask'] self.bid = ma[self.symbol]['bid'] print("ask " + str(self.ask)) print("bid " + str(self.bid)) self.server_status['message'] = self.symbol + " BID " + str(self.bid) + " ASK " + str(self.ask) + "\n" \ + self.df_.__str__() # Learning rate # Replace X_new with your new data for trading decision columns = ['open', 'high', 'low', 'close', 'volume'] labels = columns self.server_status['message'] = self.symbol + " BID " + str(self.bid) + " ASK " + str(self.ask) features = self.df_[columns].values x_train, x_test, y_train, y_test = train_test_split(features, labels, test_size=0.09) clf = MLPClassifier(hidden_layer_sizes=(100, 100, 100, 100, 100)) clf = clf.fit(x_train, y_train) print("clf " + clf.__str__()) accuracy = clf.score(x_train, y_train) print(' training data accuracy ', accuracy * 100) accuracy = clf.score(x_test, y_test) print(' testing data accuracy ', accuracy * 100) ypredict = clf.predict(x_train) print('\n Training classification report\n', classification_report(y_train, ypredict)) ypredict = clf.predict(y_train) print("predicted " + str(ypredict)) print('\n Testing classification report\n', classification_report(y_test, ypredict)) self.server_status['status'] = 'Learning rate' + str( clf.score(x_train, y_train)) + '%' + '\n' + self.df_.__str__() # Output a pickle file for the model joblib.dump(clf, 'src/saved_model.pkl') self.server_status['message'] = self.symbol + " BID " + str(self.bid) + " ASK " + str(self.ask) self.on_tick( symbol=self.symbol, bid=self.bid, ask=self.ask) #################################################################### def on_tick(self, symbol='EURUSD', bid=0.0, ask=0.0): account_balance = self.get_account_data() print("account_balance " + str(account_balance)) self.server_status['message'] = str(datetime.datetime.utcnow()) + "\n symbol " + str(symbol) + "\n bid " + str( bid) + "\n ask " + str(ask) self.server_status['server_time'] = datetime.datetime.now() self.live_trading(symbol=self.symbol, bid=bid, ask=ask, close_signal_=self.close_signal(symbol=self.symbol, data=self.dat), signal_=self.signal(symbol=self.symbol, data=self.dat)) def get_account_data(self): return self.account_data def on_historic_data(self, symbol_, time_frame: str, data): # you can also access the historic data via self.dwx.historic_data. print('historic_data:', symbol_, time_frame, f'{len(data)} bars') self.server_status['message'] = "On historic data " + str(datetime.datetime.utcnow()) + " TimeFrame " + str( time_frame) + " bars " + str(len(data)) self.historic_data['symbol'] = symbol_ self.historic_data['time_frame'] = time_frame self.historic_data['bars'] = data self.historic_data['time'] = datetime.datetime.utcnow() print("bars " + str(self.historic_data)) return self.historic_data def check_account_data(self) -> dict: while self.ACTIVE: sleep(self.sleep_delay) if self.START: text = try_read_file(self.path_account_data) if len(text.strip()) == 0 or text == self._last_account_data_str: continue self._last_account_data_str = text data = json.loads(str(text)) self.account_data = data print(self.account_data) if self.event_handler is not None: self.event_handler.on_account_data(symbol=self.account_data['symbol'], data=self.account_data) return self.account_data def check_market_data(self) -> dict: while self.ACTIVE: sleep(self.sleep_delay) if not self.START: continue text = try_read_file(self.path_market_data) if len(text.strip()) == 0 or text == self._last_market_data_str: continue self._last_market_data_str = text data = json.loads(str(text)) self.market_data = data print(self.market_data) if self.event_handler is not None: for symbol in data.keys(): if symbol not in self._last_market_data or \ self.market_data[symbol] != self._last_market_data[symbol]: self._last_market_data[symbol] = self.market_data[symbol] self._last_market_data = data self.on_tick(symbol=symbol, bid=self._last_market_data[symbol]['bid'], ask=self._last_market_data[symbol]['ask'] ) # self.event_handler.market_data(symbol=symbol, data=data[symbol]) return self.market_data """Regularly checks the file for bar data and triggers the event_handler.on_bar_data() function. """ def check_bar_data(self) -> None: open_ = [] high_ = [] low_ = [] close_ = [] volume_ = [] symbol_ = [] tf_ = [] time_ = [] while self.ACTIVE: sleep(self.sleep_delay) if self.START: text = try_read_file(file_path=str(self.path_bar_data)) if len(text.strip()) == 0 or text == self._last_bar_data_str: continue self._last_bar_data_str = text data = json.loads(text.__str__()) self.bar_data = data if self.event_handler is None: print("no event handler") else: for st in data.keys(): if st not in self.last_bar_data or self.bar_data[st] != self.last_bar_data[st]: time_frame = st.split('_') open_ = self.bar_data[st]['open'] high_ = self.bar_data[st]['high'] low_ = self.bar_data[st]['low'] close_ = self.bar_data[st]['close'] volume_ = self.bar_data[st]['tick_volume'] symbol_ = st tf_ = time_frame time_ = self.bar_data[st]['time'] self.last_bar_data[st] = self.bar_data[st] self.last_bar_data = { 'open': open_, 'high': high_, 'low': low_, 'close': close_, 'volume': volume_, 'time': time_, 'time_frame': tf_, 'symbol': symbol_ } print("loading bar data..." + str(self.last_bar_data)) data1: dict = { 'open': open_, 'high': high_, 'low': low_, 'close': close_, 'volume': volume_, 'time': time_, 'time_frame': tf_, 'symbol': symbol_ } self.bar_data1 = data1 """Regularly checks the file for historic data and trades and triggers the event_handler.on_historic_data() function. """ def check_historic_data(self): while self.ACTIVE: sleep(self.sleep_delay) if not self.START: continue text = try_read_file(file_path=self.path_historic_data) if len(text.strip()) > 0 and text != self._last_historic_data_str: self._last_historic_data_str = text data = json.loads(text.__str__()) for st in data.keys(): self.historic_data[st] = data[st] if self.event_handler is not None: symbol, time_frame = st.split('_') self.on_historic_data( symbol, time_frame, data[st]) try_remove_file(self.path_historic_data) # also check historic trades in the same thread. text = try_read_file(file_path=self.path_historic_trades) if len(text.strip()) > 0 and text != self._last_historic_trades_str: self._last_historic_trades_str = text data = json.loads(text.__str__()) self.historic_trades = data self.event_handler.on_historic_trades() try_remove_file(self.path_historic_trades) """Loads stored orders from file (in case of a restart). """ def load_orders(self): text = try_read_file(file_path=self.path_orders_stored) if len(text.__str__()) > 0: self._last_open_orders_str = text data = json.loads(text.__str__()) self.account_info = data['account_info'] self.open_orders = data['orders'] """Loads stored messages from file (in case of a restart). """ def load_messages(self): text = try_read_file(self.path_messages_stored) if len(text.__str__()) > 0: self._last_messages_str = text data = json.loads(text.__str__()) # here we don't have to sort because we just need the latest millis value. for millis in data.keys(): if int(millis) > self._last_messages_millis: self._last_messages_millis = int(millis) """Sends a SUBSCRIBE_SYMBOLS command to subscribe to market (tick) data. Args: symbols (list[str]): List of symbols to subscribe to. Returns: None The data will be stored in self.market_data. On receiving the data the event_handler.on_tick() function will be triggered. """ def subscribe_symbols(self, symbols): self.send_command('SUBSCRIBE_SYMBOLS', ','.join(symbols)) for symbol in symbols: if symbol not in self.market_data: self.market_data[symbol] = { } return False self.market_data[symbol]['bid'] = 0 self.market_data[symbol]['ask'] = 0 return True """Sends a SUBSCRIBE_SYMBOLS_BAR_DATA command to subscribe to bar data. Kwargs: symbols (list[list[str]]): List of lists containing symbol/time frame combinations to subscribe to. For example: symbols = [['EURUSD', 'M1'], ['GBPUSD', 'H1']] Returns: None The data will be stored in self.bar_data. On receiving the data the event_handler.on_bar_data() function will be triggered. """ def subscribe_symbols_bar_data(self, symbols=None): if symbols is None: symbols = [['EURUSD', 'H1']] data = [f'{st[0]},{st[1]}' for st in symbols] self.send_command('SUBSCRIBE_SYMBOLS_BAR_DATA', ','.join(str(p) for p in data)) """Sends a GET_HISTORIC_DATA command to request historic data. Kwargs: symbol (str): Symbol to get historic data. time_frame (str): Time frame for the requested data. start (int): Start timestamp (seconds since epoch) of the requested data. end (int): End timestamp of the requested data. Returns: None The data will be stored in self.historic_data. On receiving the data the event_handler.on_historic_data() function will be triggered. """ def get_historic_data(self, symbol='EURUSD', time_frame='H1', start=datetime.datetime.utcnow() - datetime.timedelta(days=30), end=datetime.datetime.now()): self.data = [symbol, time_frame, start, end] self.send_command('GET_HISTORIC_DATA', ','.join(str(p) for p in self.data)) """Sends a GET_HISTORIC_TRADES command to request historic trades. Kwargs: lookback_days (int): Days to look back into the trade history. The history must also be visible in MT4. Returns: None The data will be stored in self.historic_trades. On receiving the data the event_handler.on_historic_trades() function will be triggered. """ def get_historic_trades(self, lookback_days=60): self.send_command('GET_HISTORIC_TRADES', str(lookback_days)) """Sends an OPEN_ORDER command to open an order. Kwargs: symbol (str): Symbol for which an order should be opened. order_type (str): Order type. Can be one of: 'buy', 'sell', 'buylimit', 'selllimit', 'buystop', 'sellstop' lots (float): Volume in lots price (float): Price of the (pending) order. Can be zero for market orders. stop_loss (float): SL as absolute price. Can be zero if the order should not have an SL. take_profit (float): TP as absolute price. Can be zero if the order should not have a TP. magic (int): Magic number comment (str): Order comment expiration (int): Expiration time given as timestamp in seconds. Can be zero if the order should not have an expiration time. """ def open_order(self, symbol='AUDUSD', order_type='buy', lots: float = 0.02, price: float = 0.0, stop_loss: float = 100.5, take_profit: float = 100.4, magic=1, comment='Zones EA', expiration=0): data = [symbol, order_type, lots, price, stop_loss, take_profit, magic, comment, expiration] self.send_command('OPEN_ORDER', ','.join(str(p) for p in data)) """Sends a MODIFY_ORDER command to modify an order. Args: ticket (int): Ticket of the order that should be modified. Kwargs: lots (float): Volume in lots price (float): Price of the (pending) order. Non-zero only works for pending orders. stop_loss (float): New stop loss price. take_profit (float): New take profit price. expiration (int): New expiration time given as timestamp in seconds. Can be zero if the order should not have an expiration time. """ def modify_order(self, ticket, lots: float = 0.01, price: float = 1.6, stop_loss: float = 100.9, take_profit: float = 100.3, expiration=0): data = [ticket, lots, price, stop_loss, take_profit, expiration] self.send_command('MODIFY_ORDER', ','.join(str(p) for p in data)) """Sends a CLOSE_ORDER command to close an order. Args: ticket (int): Ticket of the order that should be closed. Kwargs: lots (float): Volume in lots. If lots=0 it will try to close the complete position. """ def close_order(self, ticket, lots): data = [ticket, lots] self.send_command('CLOSE_ORDER', ','.join(str(p) for p in data)) """Sends a CLOSE_ALL_ORDERS command to close all orders. """ def close_all_orders(self): self.send_command('CLOSE_ALL_ORDERS', '') """Sends a CLOSE_ORDERS_BY_SYMBOL command to close all orders with a given symbol. Args: symbol (str): Symbol for which all orders should be closed. """ def close_orders_by_symbol(self, symbol): self.send_command('CLOSE_ORDERS_BY_SYMBOL', symbol) """Sends a CLOSE_ORDERS_BY_MAGIC command to close all orders with a given magic number. Args: magic (str): Magic number for which all orders should be closed. """ def close_orders_by_magic(self, magic): self.send_command('CLOSE_ORDERS_BY_MAGIC', magic) """Sends a RESET_COMMAND_IDS command to reset stored command IDs. This should be used when restarting the python side without restarting the mql side. """ def reset_command_ids(self): self.command_id = 0 self.send_command("RESET_COMMAND_IDS", "") # sleep to make sure it is read before other commands. sleep(0.5) """Sends a command to the mql server by writing it to one of the command files. Multiple command files are used to allow for fast execution of multiple commands in the correct chronological order. """ def send_command(self, command, content): # Acquire lock so that different threads do not use the same # command_id or write at the same time. self.lock.acquire() self.command_id = (self.command_id + 1) % 100000 end_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=self.max_retry_command_seconds) now = datetime.datetime.utcnow() # trying again for X seconds in case all files exist or are # currently read from mql side. while now < end_time: # using 10 different files to increase the execution speed # for multiple commands. success = False for i in range(self.num_command_files): # only send commend if the file does not exist so that we # do not overwrite all commands. file_path = f'{self.path_commands_prefix}{i}.txt' if not exists(file_path): try: with open(file_path, 'w') as f: f.write(f'<:{self.command_id}|{command}|{content}:>') f.close() success = True break except Exception as e: print(e) print_exc() if success: break sleep(self.sleep_delay) now = datetime.datetime.utcnow() print(f'Waiting for {self.max_retry_command_seconds} seconds...') # release lock again self.lock.release() def live_trading(self, symbol='EURUSD', bid: float = 0.0, ask: float = 0.0, close_signal_=0, signal_=0): global positions, sl, tp self.stop_loss = 0.002 self.take_profit = 0.003 now = datetime.datetime.utcnow() close_time = 0 # Initial close time start_balance = 1000 # self.account_data['balance'] close_balance = 0 # Initial close balance close_price = 0 # Initial close price status = 'open' # Initial status order_type = 'buystop' open_time = [datetime.datetime.now()] if signal_ > 0: side = 'BUY' price = ask sl = float(price - self.stop_loss * price) tp = float(price + self.take_profit * price) volume = mm_size(sl) status = 'open' order_id = 0 order_id = order_id + 1 open_time.append(datetime.datetime.now()) positions = [{ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side }, { 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side}] self.open_order(symbol=symbol, order_type=order_type, price=price, lots=volume, stop_loss=sl, take_profit=tp) elif signal_ < 0: price = bid side = 'SELL' status = 'open' order_id = 1 order_type = 'sellstop' sl = float(price + self.stop_loss * price) tp = float(price - self.take_profit * price) volume = mm_size(sl) open_time.append(datetime.datetime.now()) positions = [{ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side }, { 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side}] self.open_order(symbol=symbol, order_type=order_type, price=price, lots=volume, stop_loss=sl, take_profit=tp) # Close orders if close_signal_ > 0: side = 'BUY' status = 'close' order_id = order_id + 1 close_time = datetime.datetime.now() positions.append({ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side }) for ticket in self.open_orders.keys(): self.close_order(ticket, lots=mm_size(sl)) if close_signal_ < 0: side = 'BUY' start_balance = start_balance + price * volume status = 'close' order_id = order_id + 1 close_time = datetime.datetime.now() positions.append({ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side }) print(positions.__str__()) self.server_status['message'] = "On tick " + positions.__str__() + " symbol " + symbol for ticket in self.open_orders.keys(): self.close_order(ticket, lots=mm_size(tp)) self.last_modification_time = now if now > self.last_modification_time + datetime.timedelta(seconds=10): self.last_modification_time = now for ticket in self.open_orders.keys(): self.server_status['message'] = "On tick " + str(datetime.datetime.utcnow()) + " symbol " + str(symbol) self.server_status['server_time'] = datetime.datetime.utcnow() self.modify_order(ticket, lots=mm_size(sl), stop_loss=sl, take_profit=tp, expiration=0) for i in positions: if status == 'open': count = i.get('open_time').count(datetime.datetime.now()) print("Total Open orders " + str(count)) api_key = 'YOUR_BINANCE_API_KEY' api_secret = 'YOUR_BINANCE_API_SECRET' base_url = 'https://api.binance.us/api/v3' def fetch_candlestick_data(symbol, interval, limit): endpoint = f'{base_url}/klines' params = { 'symbol': symbol, 'interval': interval, 'limit': limit } response = requests.get(endpoint, params=params) data = response.json() df_ = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'num_trades', 'taker_buy_base', 'taker_buy_quote', 'ignore']) df_['timestamp'] = pd.to_datetime(df_['timestamp'], unit='ms') return df_
zones
/zones-0.0.3.tar.gz/zones-0.0.3/src/DwxClient.py
DwxClient.py
from datetime import datetime import requests import pandas as pd import tablib from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as tk from ta.trend import MACD api_key = 'YOUR_BINANCE_API_KEY' api_secret = 'YOUR_BINANCE_API_SECRET' base_url = 'https://api.binance.us/api/v3' def fetch_candlestick_data(symbol, interval, limit): endpoint = f'{base_url}/klines' params = { 'symbol': symbol, 'interval': interval, 'limit': limit } response = requests.get(endpoint, params=params) data = response.json() _df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'num_trades', 'taker_buy_base', 'taker_buy_quote', 'ignore']) _df['timestamp'] = pd.to_datetime(_df['timestamp'], unit='ms') return _df def calculate_macd(df_): series = pd.Series(df_['close'], index=df_['timestamp'], name='close', dtype='float', fastpath=False) close_prices = series macd_ = MACD(close_prices) signal_ = macd_.macd_signal() return macd_, signal_ def simulate_trading(macd_, signal_): balance_ = 1000 # Initial balance in USDT close_signal_=0 order_id = 1 # Initial order id close_time = 0 # Initial close time start_balance = balance_ # Initial start balance close_balance = 0 # Initial close balance close_price = 0 # Initial close price status = 'open' # Initial status order_type = 'limit' # Initial order type side = 'BUY' # Initial side price = 1.34 # Initial price volume = 1000 # Initial volume open_time = [datetime.now()] positions = [{ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side }] if signal_ > 0: side = 'BUY' price = price + 0.01 volume = volume + 1000 start_balance = start_balance + price * volume status = 'open' order_id = order_id + 1 open_time.append(datetime.now()) positions.append({ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side}) elif signal_ < 0: side = 'SELL' price = price + 0.01 volume = volume + 1000 start_balance = start_balance + price * volume status = 'open' order_id = order_id + 1 open_time.append(datetime.now()) positions.append({ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance, 'status': status, 'side': side}) if close_signal_ > 0: side = 'BUY' price = price + 0.01 volume = volume + 1000 start_balance = start_balance + price * volume status = 'close' order_id = order_id + 1 close_time= datetime.now() positions.append({ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance }) if close_signal_ < 0: side = 'BUY' price = price + 0.01 volume = volume + 1000 start_balance = start_balance + price * volume status = 'close' order_id = order_id + 1 close_time= datetime.now() positions.append({ 'open_time': open_time, 'close_time': close_time, 'order_id': order_id, 'price': price, 'volume': volume, 'start_balance': start_balance, 'order_type': order_type, 'close_price': close_price, 'close_balance': close_balance }) for i in positions: if status == 'open': count = i.get('open_time').count(datetime.now()) print("Total Open orders " + str(count)) return balance_ def display_chart( df_): root = tk.Tk() root.title('Cryptocurrency Chart') fig = Figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.plot(df_['timestamp'], df_['close'], label='Close Price') canvas = FigureCanvasTkAgg(fig, master=root) canvas.get_tk_widget().pack() root.mainloop() if __name__ == '__main__': df = fetch_candlestick_data('BTCUSDT', '1m', 1000) macd, signal = calculate_macd(df) balance = simulate_trading(macd, signal) print(balance) display_chart(df)
zones
/zones-0.0.3.tar.gz/zones-0.0.3/src/crypto.py
crypto.py
import json from asyncio.log import logger import urllib3 class TelegramBot(object): def __init__(self, _token: str): self.token = _token self.url = "https://api.telegram.org/bot2125623831:AAF28ssPXid819-xSoLwGwc4V-q0yrKgyzg/" self.http = urllib3.PoolManager() self.http.headers.update({'User-Agent': 'Mozilla/5.0'}) self.http.headers.update({'Content-Type': 'application/json'}) self.http.headers.update({'Accept': 'application/json'}) self.http.headers.update({'Connection': 'close'}) self.http.headers.update({'Cache-Control': 'no-cache'}) self.http.headers.update({'Pragma': 'no-cache'}) self.http.headers.update({'Cache-Control': 'no-cache'}) response = self.http.request('GET', self.url + 'getMe') self.me = json.loads(response.data.decode('utf-8')) print(self.me) response = self.http.request('GET', self.url + 'getUpdates') self.data = [json.loads(response.data.decode('utf-8'))] print(self.data) def send_chat_action(self, chat_id: int, action: str): data = { 'chat_id': chat_id, 'action': action, 'message_thread_id': None } response = self.http.request('POST', self.url + 'sendChatAction', data=json.dumps(data)) print(response.data.decode('utf-8')) def send_message(self, chat_id: int, message_text: str): data = { 'chat_id': chat_id, 'text': message_text } try: response = self.http.request("POST", self.url + 'sendMessage', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) except Exception as e: logger.error(e) return None def get_message(self, chat_id: int = None, message_id=None): data = { 'chat_id': chat_id, 'message_id': message_id } response = self.http.request('POST', self.url + 'getMessage', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def get_updates(self, offset=None, limit=None): data = { 'offset': offset, 'limit': limit } response = self.http.request('GET', self.url + 'getUpdates', body=json.dumps(data)) print(json.loads(response.data.decode('utf-8'))) return json.loads(response.data.decode('utf-8')) def get_me(self): response = self.http.request('POST', self.url + 'getMe') return json.loads(response.data.decode('utf-8')) def get_chat(self, chat_id): data = { 'chat_id': chat_id } response = self.http.request('POST', self.url + 'getChat', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def get_user(self, user_id): data = { 'user_id': user_id } response = self.http.request('POST', self.url + 'getUser', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def get_chat_administrators(self, chat_id): data = { 'chat_id': chat_id } response = self.http.request('POST', self.url + 'getChatAdministrators', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def get_chat_members_count(self, chat_id): data = { 'chat_id': chat_id } response = self.http.request('POST', self.url + 'getChatMembersCount', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def get_chat_member(self, chat_id, user_id): data = { 'chat_id': chat_id, 'user_id': user_id } response = self.http.request('POST', self.url + 'getChatMember', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def leave_chat(self, chat_id): data = { 'chat_id': chat_id } response = self.http.request('POST', self.url + 'leaveChat', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def get_user_profile_photos(self, user_id, offset=None, limit=None): data = { 'user_id': user_id, 'offset': offset, 'limit': limit } response = self.http.request('POST', self.url + '/getUserProfilePhotos', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def get_file(self, file_id): data = { 'file_id': file_id } response = self.http.request('POST', self.url + '/getFile', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def send_photo(self, chat_id, photo, caption=None, reply_markup=None, reply_to_message_id=None, reply_to_message=None, reply_to_message_text=None, reply_to_message_html=None): data = { 'chat_id': chat_id, 'photo': photo, 'caption': caption, 'reply_markup': reply_markup, 'reply_to_message_id': reply_to_message_id, 'reply_to_message': reply_to_message, 'reply_to_message_text': reply_to_message_text, 'reply_to_message_html': reply_to_message_html } response = self.http.request('POST', self.url + '/sendPhoto', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def send_audio(self, chat_id, audio, caption=None, reply_markup=None, reply_to_message_id=None, reply_to_message=None, reply_to_message_text=None, reply_to_message_html=None): data = { 'chat_id': chat_id, 'audio': audio, 'caption': caption, 'reply_markup': reply_markup, 'reply_to_message_id': reply_to_message_id, 'reply_to_message': reply_to_message, 'reply_to_message_text': reply_to_message_text, 'reply_to_message_html': reply_to_message_html} response = self.http.request('POST', self.url + '/sendAudio', body=json.dumps(data)) return json.loads(response.data.decode('utf-8')) def send_document(self, chat_id, document, caption=None, reply_markup=None, reply_to_message_id=None, reply_to_message=None, reply_to_message_text=None, reply_to_message_html=None): data = { 'chat_id': chat_id, 'document': document, 'caption': caption, 'reply_markup': reply_markup, 'reply_to_message_id': reply_to_message_id, 'reply_to_message': reply_to_message, 'reply_to_message_text': reply_to_message_text, 'reply_to_message_html': reply_to_message_html} response = self.http.request('POST', self.url + '/sendDocument', body=json.dumps(data)) return json.loads(response.data.decode('utf-8'))
zones
/zones-0.0.3.tar.gz/zones-0.0.3/src/Telegram.py
Telegram.py
import tkinter from configparser import ConfigParser from tkinter import Message import sqlalchemy class Db(object): def __init__(self): # Create mysql connection self.users: dict = { "id": 0, "email": "", "username": "", "password": "", "phone": "", "first_name": "", "last_name": "", "created_at": "", "updated_at": "" } self.config = ConfigParser() self.config.add_section('mysql') self.config.read(filenames="config.ini") self.host = self.config.get(section='mysql', option='host') self.user = self.config.get(section='mysql', option='user') self.password = self.config.get(section='mysql', option='password') self.database = self.config.get(section='mysql', option='database') self.port = self.config.get(section='mysql', option='port') self.engine = sqlalchemy.create_engine( "mysql+mysqldb://" + self.user + ":" + self.password + "@localhost:3306/zones?charset=utf8mb4", connect_args={"charset": "utf8mb4"} ) self.conn = self.engine.connect() self.cur = self.conn.engine.connect() if self.conn is None: print("Error: unable to connect to MySQL server.") tkinter.Message(text="Error: unable to connect to MySQL server.") return self.cur.exec_driver_sql("CREATE DATABASE IF NOT EXISTS " + self.database) self.cur.exec_driver_sql( 'CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255)' ',username VARCHAR(255), password VARCHAR(255), phone VARCHAR(255),' 'first_name VARCHAR(255), last_name VARCHAR(255), created_at DATETIME, updated_at DATETIME)') def verify(self, username: str = "", password: str = ""): self.cur.exec_driver_sql( 'SELECT * FROM users WHERE username=? AND password=?', (username, password) ) user = self.cur.exec_driver_sql('SELECT * FROM users WHERE username=? ', (username,)) if user: user = self.cur.exec_driver_sql( 'SELECT * FROM users WHERE username=? AND password=?', (username, password) ) if user: self.users = user return True else: message = "Wrong password" Message(text=message) else: message = "username or password incorrect" Message(text=message) return False def save(self, _bar_data_data): cursor = self.conn cursor.exec_driver_sql( "CREATE TABLE IF NOT EXISTS candles (id INT AUTO_INCREMENT PRIMARY KEY," "time datetime ,symbol VARCHAR(255) NOT NULL," "open REAL NOT NULL," "high REAL NOT NULL," "low REAL NOT NULL," "close REAL NOT NULL," "volume REAL NOT NULL)" + "") self.conn.commit() cursor.exec_driver_sql( "CREATE TABLE IF NOT EXISTS bars (id INT AUTO_INCREMENT PRIMARY KEY," "time datetime,symbol VARCHAR(255) NOT NULL," "open REAL NOT NULL," "high REAL NOT NULL," "low REAL NOT NULL," "close REAL NOT NULL," "volume REAL NOT NULL)" + "") self.conn.commit() cursor.exec_driver_sql( "INSERT INTO candles (time,symbol,open,high,low,close,volume) " "VALUES (%s,%s,%s,%s,%s,%s,%s)", (_bar_data_data['time'], _bar_data_data['symbol'], _bar_data_data['open'], _bar_data_data['high'], _bar_data_data['low'], _bar_data_data['close'], _bar_data_data['volume'])) self.conn.commit()
zones
/zones-0.0.3.tar.gz/zones-0.0.3/src/db.py
db.py
import pandas as pd import numpy as np from binance.client import Client from matplotlib import pyplot as plt # Binance API credentials (Replace with your own) API_KEY = 'odkr6pfbgl10ZM7i2D4kZ8FgOZLDjzs3iAY2IV2E67Cm316dkQs397bScVzhH4b1' API_SECRET = '3ilQvixaFv3Y1sdZ48jO0JqShoQUU6SdQkbviOAgIB2zHR9xu8J7hQSPZGqzxoTd' # Initialize Binance US client client = Client(API_KEY, API_SECRET, tld='us') print(client.get_open_orders()) print(client.get_account()) client.get_klines(symbol='ETHUSDT',interval='1m', limit=1000) def get_historical_data(symbol, interval, _limit): klines = client.get_klines(symbol=symbol, interval=interval, limit=_limit) df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'num_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore']) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') df.set_index('timestamp', inplace=True) df['open'] = pd.to_numeric(df['open']) df['high'] = pd.to_numeric(df['high']) df['low'] = pd.to_numeric(df['low']) df['close'] = pd.to_numeric(df['close']) df['volume'] = pd.to_numeric(df['volume']) df['quote_asset_volume'] = pd.to_numeric(df['quote_asset_volume']) df['num_trades'] = pd.to_numeric(df['num_trades']) df['taker_buy_base_asset_volume'] = pd.to_numeric(df['taker_buy_base_asset_volume']) df['taker_buy_quote_asset_volume'] = pd.to_numeric(df['taker_buy_quote_asset_volume']) return df def calculate_moving_averages(data, short_window=5, long_window=20): data['SMA_short'] = data['close'].rolling(window=short_window).mean() data['SMA_long'] = data['close'].rolling(window=long_window).mean() def trading_strategy(data): # Implement your trading strategy here based on the calculated indicators # For example, buy when short moving average crosses above long moving average, # and sell when the opposite happens. pass if __name__ == "__main__": trading_pair = 'ETHUSD' # Replace with the desired trading pair timeframe = Client.KLINE_INTERVAL_1HOUR # Replace with the desired timeframe limit = 1000 # Number of data points to fetch historical_data = get_historical_data(trading_pair, timeframe, limit) calculate_moving_averages(historical_data) # Implement your trading strategy here trading_strategy(historical_data) # Print the historical data and indicators print(historical_data) print(historical_data['SMA_short']) print(historical_data['SMA_long']) pd = pd.DataFrame(historical_data) plt.plot(historical_data['close'], label='C') plt.plot(historical_data['open'], label='O') plt.plot(historical_data['high'], label='H') plt.plot(historical_data['low'], label='L') plt.plot(historical_data['SMA_short'], label='S') plt.plot(historical_data['SMA_long'], label='L') plt.legend() plt.show()
zones
/zones-0.0.3.tar.gz/zones-0.0.3/src/Binance.py
Binance.py
import asyncio import random import string from datetime import datetime from typing import List, Optional import iso8601 import pytz from typing_extensions import TypedDict def date(date_time: str or float or int or datetime) -> datetime: """Parses a date string into a datetime object. :type date_time: object """ if isinstance(date_time, float) or isinstance(date_time, int): return datetime.fromtimestamp(max(date_time, 100000)).astimezone(pytz.utc) elif isinstance(date_time, datetime): return date_time else: return iso8601.parse_date(str(date_time)) def format_date(date_object: datetime or str) -> str: """Converts date to format compatible with JS""" if isinstance(date_object, datetime): return date_object.astimezone(pytz.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') else: return date_object def random_id(length: int = 32) -> str: """Generates a random id of 32 symbols.""" return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) class ValidationDetails(TypedDict): """Object to supply additional information for validation exceptions.""" parameter: str """Name of invalid parameter.""" value: Optional[str] """Entered invalid value.""" message: str """Error message.""" class ExceptionMessage(TypedDict): """A REST API response that contains an exception message""" id: int """Error id""" error: str """Error name""" numericCode: Optional[int] """Numeric error code""" stringCode: Optional[str] """String error code""" message: str """Human-readable error message""" details: Optional[List[ValidationDetails]] """Additional information about error. Used to supply validation error details.""" def convert_iso_time_to_date(data): """Converts time fields of incoming data into datetime.""" if isinstance(data, str): return for field in data: if isinstance(data, dict): value = data[field] else: value = field if not (not isinstance(value, str) or field not in ['closeAfter', 'stoppedAt', 'stoppedTill', 'startTime', 'time', 'updateTime']): data[field] = date(value) if isinstance(value, list): for item in value: convert_iso_time_to_date(item) if isinstance(value, dict): convert_iso_time_to_date(value) def format_request(data: dict or list): """Formats datetime fields of a request into iso format.""" if isinstance(data, str): return for field in data: if isinstance(data, dict): value = data[field] else: value = field if isinstance(value, datetime): data[field] = format_date(value) elif isinstance(value, list): for item in value: format_request(item) elif isinstance(value, dict): format_request(value) async def promise_any(coroutines): exception_task = None while len(coroutines): done, coroutines = await asyncio.wait(coroutines, return_when=asyncio.FIRST_COMPLETED) for task in done: if not exception_task and task.exception(): exception_task = task else: for wait_task in coroutines: wait_task.cancel() return task.result() return exception_task.result()
zones
/zones-0.0.3.tar.gz/zones-0.0.3/src/models.py
models.py
__all__ = [ "convert_from_nested_dict_to_plain_dict", "convert_from_plain_dict_to_nested_dict", ] def convert_from_nested_dict_to_plain_dict(data=None, parent_string=None): result = {} if isinstance(data, dict): for key, value in data.items(): if isinstance(value, dict) or isinstance(value, list): result.update( convert_from_nested_dict_to_plain_dict( value, parent_string + "." + str(key) if parent_string else str(key), ) ) else: pre_parent_string = parent_string + "." if parent_string else "" result[pre_parent_string + str(key)] = value elif isinstance(data, list): for key, value in enumerate(data): if isinstance(value, dict) or isinstance(value, list): result.update( convert_from_nested_dict_to_plain_dict( value, parent_string + "[" + str(key) + "]" if parent_string else "[" + str(key) + "]", ) ) else: pre_parent_string = parent_string if parent_string else "" result[pre_parent_string + "[" + str(key) + "]"] = value return result def convert_from_plain_dict_to_nested_dict(data=None): if not data: return data if list(data.keys())[0].startswith("["): result = list() else: result = dict() last_key = None ignored_keys = [] for key, value in data.items(): if key in ignored_keys: continue elif key == "": return value elif key.startswith("["): rsb_idx = key.index("]") if last_key != key[1:rsb_idx]: last_key = key[1:rsb_idx] new_data = {k[rsb_idx + 1 :]: v for k, v in data.items() if k[1 : k.index("]")] == key[1:rsb_idx]} result.insert( int(key[1:rsb_idx]), convert_from_plain_dict_to_nested_dict(new_data), ) elif key.startswith("."): if last_key != key[0]: last_key = key[0] new_data = {k[1:]: v for k, v in data.items() if k[0] == key[0]} result.update(convert_from_plain_dict_to_nested_dict(new_data)) else: for index, char in enumerate(key): if char == "[" or char == ".": if last_key != key[0:index]: last_key = key[0:index] new_data = {} for k, v in data.items(): if k[0:index] == last_key: new_data[k[index:]] = v ignored_keys.append(k) result[last_key] = convert_from_plain_dict_to_nested_dict(new_data) break else: result[key] = value return result
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/dict_converter.py
dict_converter.py
import simplejson import datetime import decimal import uuid from rest_framework.renderers import JSONRenderer from rest_framework.compat import INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS from django.db.models.query import QuerySet from django.utils import timezone from django.utils.encoding import force_str from django.utils.functional import Promise class CustomJSONEncoder(simplejson.JSONEncoder): def default(self, obj): if isinstance(obj, Exception): return getattr(obj, "message", str(obj)) # Код ниже взят из rest_framework.utils.encoders.JSONEncoder # For Date Time string spec, see ECMA 262 # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 if isinstance(obj, Promise): return force_str(obj) elif isinstance(obj, datetime.datetime): representation = obj.isoformat() # TODO: Разобраться, зачем это было нужно # if representation.endswith("+00:00"): # representation = representation[:-6] # + "Z" return representation elif isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, datetime.time): if timezone and timezone.is_aware(obj): raise ValueError("JSON can't represent timezone-aware times.") representation = obj.isoformat() return representation elif isinstance(obj, datetime.timedelta): return str(obj.total_seconds()) elif isinstance(obj, decimal.Decimal): # Serializers will coerce decimals to strings by default. return float(obj) elif isinstance(obj, uuid.UUID): return str(obj) elif isinstance(obj, QuerySet): return tuple(obj) elif isinstance(obj, bytes): # Best-effort for binary blobs. See #4187. return obj.decode() elif hasattr(obj, "tolist"): # Numpy arrays and array scalars. return obj.tolist() elif hasattr(obj, "__getitem__"): cls = list if isinstance(obj, (list, tuple)) else dict try: return cls(obj) except Exception: pass elif hasattr(obj, "__iter__"): return tuple(item for item in obj) return super().default(obj) def custom_json_dumps(obj, **kwargs): return simplejson.dumps(obj, cls=CustomJSONEncoder, **kwargs) def custom_json_loads(obj, **kwargs): return simplejson.loads(obj, **kwargs) def pretty_json(data: dict, safe: bool = True) -> str: try: return simplejson.dumps(data, indent=True, cls=CustomJSONEncoder, ensure_ascii=False) except TypeError as error: if not safe: raise error return str(data) class CustomJSONRenderer(JSONRenderer): encoder_class = CustomJSONEncoder def render(self, data, accepted_media_type=None, renderer_context=None): """ Render `data` into JSON, returning a bytestring. """ if data is None: return b"" renderer_context = renderer_context or {} indent = self.get_indent(accepted_media_type, renderer_context) if indent is None: separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS else: separators = INDENT_SEPARATORS # Замена json на simplejson ради параметра ignore_nan ret = simplejson.dumps( data, cls=self.encoder_class, indent=indent, ensure_ascii=self.ensure_ascii, separators=separators, ignore_nan=True, ) # We always fully escape \u2028 and \u2029 to ensure we output JSON # that is a strict javascript subset. # See: http://timelessrepo.com/json-isnt-a-javascript-subset ret = ret.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029") return ret.encode()
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/json_utils.py
json_utils.py
def transliterate(name: str, space_to_underscore: bool = False): mapping = { "а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e", "ж": "zh", "з": "z", "и": "i", "й": "i", "к": "k", "л": "l", "м": "m", "н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u", "ф": "f", "х": "h", "ц": "c", "ч": "ch", "ш": "sh", "щ": "sch", "ь": "", "ъ": "", "ы": "y", "э": "e", "ю": "u", "я": "ya", "А": "A", "Б": "B", "В": "V", "Г": "G", "Д": "D", "Е": "E", "Ё": "E", "Ж": "Zh", "З": "Z", "И": "I", "Й": "I", "К": "K", "Л": "L", "М": "M", "Н": "N", "О": "O", "П": "P", "Р": "R", "С": "S", "Т": "T", "У": "U", "Ф": "F", "Х": "H", "Ц": "C", "Ч": "Ch", "Ш": "Sh", "Щ": "Sch", "Ъ": "", "Ы": "Y", "Ь": "", "Э": "E", "Ю": "U", "Я": "Ya", ",": ",", "?": "?", "~": "~", "!": "!", "@": "@", "#": "#", "$": "$", "%": "%", "^": "^", "&": "&", "*": "*", "(": "(", ")": ")", "-": "-", "=": "=", "+": "+", ":": ":", ";": ";", "<": "<", ">": ">", '"': '"', '"': '"', "\\": "\\", "/": "/", "№": "#", "[": "[", "]": "]", "{": "{", "}": "}", "ґ": "r", "ї": "r", "є": "e", "Ґ": "g", "Ї": "i", "Є": "e", "—": "-", } if space_to_underscore: mapping[" "] = "_" if name: for key in mapping: name = name.replace(key, mapping[key]) return name
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/transliterate.py
transliterate.py
import requests from django.core.cache import cache from django.conf import settings from django.utils.translation import gettext as _ from zs_utils.exceptions import CustomException class CurrencyServiceError(CustomException): pass def _convert_currency_by_coinlayer(from_currency: str, to_currency: str, amount: int = 1) -> float: """ Docs: https://coinlayer.com/documentation Конвертация валют через сервис coinlayer """ token = settings.COINLAYER_API_TOKEN url = ( f"http://api.coinlayer.com/api/convert?access_key={token}&from={from_currency}&to={to_currency}&amount={amount}" ) data = requests.get(url=url).json() if not data.get("success", True): message = _("Не удалось конвертировать валюту ({from_currency}-->{to_currency}): {error}").format( from_currency=from_currency, to_currency=to_currency, error=data.get("error", {}).get("info", "System error"), ) raise CurrencyServiceError(message=message) return data["result"] def _get_exchange_rate_cache_key(from_currency: str, to_currency: str): """ Получения ключа кэша, в котором хранятся курсы валют """ sorted_currencies = sorted([from_currency, to_currency]) return f"exchange_rate_{sorted_currencies[0]}_{sorted_currencies[1]}" def _get_exchange_rate_from_cache(from_currency: str, to_currency: str) -> float: """ Получение курса валют из кэша """ value = cache.get(key=_get_exchange_rate_cache_key(from_currency=from_currency, to_currency=to_currency)) if value and (from_currency > to_currency): value = 1 / value return value def _save_exchange_rate_in_cache(from_currency: str, to_currency: str, value: float) -> None: """ Сохранение курса валют в кэш """ assert value if from_currency > to_currency: value = 1 / value timeout = 0.5 * 60 * 60 # 0.5 часов cache.set( _get_exchange_rate_cache_key(from_currency=from_currency, to_currency=to_currency), value, timeout=timeout, ) def convert_amount( from_currency: str, to_currency: str, value: float, use_cache: bool = True, ) -> float: """ Конвертация переданных валют, с возможностью использования кэша """ if from_currency == "RUR": from_currency = "RUB" if to_currency == "RUR": to_currency = "RUB" # Тривиальный случай if (from_currency == to_currency) or (value == 0): return value coef = None # Получение сохраненного в кэше курса if use_cache: coef = _get_exchange_rate_from_cache(from_currency=from_currency, to_currency=to_currency) if not coef: coef = _convert_currency_by_coinlayer( from_currency=from_currency, to_currency=to_currency, amount=1, ) # Сохранение курса в кэш _save_exchange_rate_in_cache(from_currency=from_currency, to_currency=to_currency, value=coef) return round(value * coef, 5) @classmethod def is_greater(value1: float, currency1: str, value2: float, currency2: str) -> bool: """ Метод для сравнения суммы в разных валютах """ return convert_amount(from_currency=currency1, to_currency=currency2, value=value1) > value2
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/currency_converter.py
currency_converter.py
import re import xml.etree.ElementTree as ET __all__ = [ "DictWrapper", "simplify_object_dict", "xml_to_dict", ] class ObjectDict(dict): """ Extension of dict to allow accessing keys as attributes. """ def __init__(self, initd=None): if initd is None: initd = {} dict.__init__(self, initd) def __getattr__(self, item): node = self.__getitem__(item) if isinstance(node, dict) and "value" in node and len(node) == 1: return node["value"] return node # if value is the only key in object, you can omit it def __setstate__(self, item): return False def __setattr__(self, item, value): self.__setitem__(item, value) def getvalue(self, item, value=None): """ Old Python 2-compatible getter method for default value. """ return self.get(item, {}).get("value", value) class XML2Dict: def __init__(self): pass def _parse_node(self, node): node_tree = ObjectDict() # Save attrs and text, hope there will not be a child with same name if node.text: node_tree.value = node.text for key, val in node.attrib.items(): key, val = self._namespace_split(key, ObjectDict({"value": val})) node_tree[key] = val # Save childrens for child in list(node): tag, tree = self._namespace_split(child.tag, self._parse_node(child)) if tag not in node_tree: # the first time, so store it in dict node_tree[tag] = tree continue old = node_tree[tag] if not isinstance(old, list): node_tree.pop(tag) node_tree[tag] = [old] # multi times, so change old dict to a list node_tree[tag].append(tree) # add the new one return node_tree def _namespace_split(self, tag, value): """ Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' ns = http://cs.sfsu.edu/csc867/myscheduler name = patients """ result = re.compile(r"\{(.*)\}(.*)").search(tag) if result: value.namespace, tag = result.groups() return (tag, value) def parse(self, filename): """ Parse XML file to a dict. """ file_ = open(filename, "r") return self.fromstring(file_.read()) def fromstring(self, str_): """ Parse a string """ text = ET.fromstring(str_) root_tag, root_tree = self._namespace_split(text.tag, self._parse_node(text)) return ObjectDict({root_tag: root_tree}) def remove_namespace(xml): """ Strips the namespace from XML document contained in a string. Returns the stripped string. """ regex = re.compile(' xmlns(:ns2)?="[^"]+"|(ns2:)|(xml:)') return regex.sub("", xml) class DictWrapper: def __init__(self, xml, rootkey=None): self.original = xml self.response = None self._rootkey = rootkey self._mydict = XML2Dict().fromstring(remove_namespace(xml)) self._response_dict = self._mydict.get(list(self._mydict.keys())[0], self._mydict) @property def parsed(self): if self._rootkey: return self._response_dict.get(self._rootkey) return self._response_dict def simplify_object_dict(obj): """ Упрощение структуры экземляра класса ObjectDict. """ if isinstance(obj, list): return [simplify_object_dict(obj_child) for obj_child in obj] elif obj is None: return "" else: json_obj = {} if (len(obj) == 1) and ("value" in obj): return obj.value for key, val in obj.items(): if isinstance(val, str): if (key == "value") and (not val.strip()): continue json_obj[key] = val elif isinstance(val, dict) and (len(val) == 1) and ("value" in val): json_obj[key] = val["value"] else: json_obj[key] = simplify_object_dict(val) return json_obj def xml_to_dict(xml: str, rootkey=None): return simplify_object_dict(DictWrapper(xml, rootkey=rootkey).parsed)
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/xml_parser.py
xml_parser.py
import datetime import pytils from django.utils import timezone def now(): return timezone.now() def current_date(): return now().date() def days_ago_to_dates(days_ago: int, discard_time: bool = False): datetime_now = now() dates = { "date_before": datetime_now, "date_after": datetime_now - timezone.timedelta(days=int(days_ago)), } if discard_time: for key, value in dates.items(): dates[key] = value.date() return dates def from_datetime_str(value: str): if value.endswith("Z"): value = value[:-1] + "+00:00" return timezone.datetime.fromisoformat(value) def datetime_str_to_date_str(value: str): return str(from_datetime_str(value).date()) def datetime_to_tsz(value) -> float: return timezone.datetime.timestamp(value) def tsz_to_datetime(tsz, to_str=False, isoformat=False): dtm = timezone.make_aware(timezone.datetime.utcfromtimestamp(tsz), timezone=datetime.timezone.utc) if to_str: if isoformat: dtm = dtm.isoformat() else: dtm = dtm.strftime("%Y-%m-%d %H:%M:%S") return dtm def datetime_to_words(value: timezone.timedelta, lang: str): seconds = int(value.total_seconds()) periods = [ ({"en": "year", "ru": ("год", "года", "лет")}, 60 * 60 * 24 * 365), ({"en": "month", "ru": ("месяц", "месяца", "месяцев")}, 60 * 60 * 24 * 30), ({"en": "day", "ru": ("день", "дня", "дней")}, 60 * 60 * 24), ({"en": "hour", "ru": ("час", "часа", "часов")}, 60 * 60), ({"en": "minute", "ru": ("минута", "минуты", "минут")}, 60), ({"en": "second", "ru": ("секунда", "секунды", "секунд")}, 1), ] strings = [] for period_names, period_seconds in periods: if seconds >= period_seconds: period_value, seconds = divmod(seconds, period_seconds) if lang == "ru": strings.append(pytils.numeral.get_plural(amount=period_value, variants=period_names[lang])) elif lang == "en": has_s = "s" if period_value > 1 else "" strings.append("%s %s%s" % (period_value, period_names[lang], has_s)) else: raise ValueError("Недопустимый язык 'lang'.") return ", ".join(strings)
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/time_utils.py
time_utils.py
import inspect from sys import modules from importlib import import_module __all__ = [ "get_class_by_method", "get_func_path", "get_class_method_path", "get_callable_path", "import_object", "import_object_by_path", "import_class_attr", "import_class_attr_by_path", ] def get_class_by_method(method): """ Получения класса по его методу """ return vars(modules[method.__module__])[method.__qualname__.split(".")[0]] def get_func_path(func) -> str: """ Получение пути функции. """ return ".".join([func.__module__, func.__name__]) def get_class_method_path(method) -> str: """ Получение пути метода класса. """ return ".".join([method.__module__, get_class_by_method(method).__name__, method.__name__]) def get_callable_path(obj) -> str: if inspect.isclass(obj): return get_func_path(func=obj) elif inspect.isfunction(obj): if "." in obj.__qualname__: # Статический метод класса return get_class_method_path(method=obj) else: return get_func_path(func=obj) elif inspect.ismethod(obj): return get_class_method_path(method=obj) else: raise ValueError(f"Неизвестный тип объекта: '{type(obj)}'") def import_object(module_name: str, object_name: str): # Получение модуля module = import_module(module_name) # Получение функции модуля func = getattr(module, object_name, None) if not func: raise AttributeError(f"Объект '{object_name}' не найден в модуле '{module_name}'.") return func def import_object_by_path(path: str): path_parts = path.split(".") return import_object(module_name=".".join(path_parts[:-1]), object_name=path_parts[-1]) def import_class_attr(module_name: str, class_name: str, attr_name: str): # Получение модуля module = import_module(module_name) # Получение класса class_obj = getattr(module, class_name, None) if not class_obj: raise AttributeError(f"Класс '{class_name}' не найден в модуле '{module_name}'.") # Получение метода класса try: class_method = getattr(class_obj, attr_name) except AttributeError: raise AttributeError(f"Метод '{attr_name}' не найден у класса '{class_name}'.") return class_method def import_class_attr_by_path(path: str): path_parts = path.split(".") return import_class_attr( module_name=".".join(path_parts[:-2]), class_name=path_parts[-2], attr_name=path_parts[-1], )
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/import_utils.py
import_utils.py
import uuid import datetime from zs_utils.exceptions import CustomException class DataCompareException(CustomException): pass def get_dict_field_value(field: str, data: dict): """ Получение значения поля 'field' словаря 'data'. Синтаксис аргумента 'field': -- символ '.' позволяет получить элемент из вложенного словаря или списка; -- символ ':' позволяет получить определенный элемент списка. Примеры работы: Пусть data = {'a': 1, 'b': {'d': 2}, 'c': [{'e': 3}, {'e': 4, 'f': 5}]}. Результат при 'field'='a': 1. Результат при 'field'='b': {'d': 2}. Результат при 'field'='b.d': 2. Результат при 'field'='c': [{'e': 3}, {'e': 4, 'f': 5}]. Результат при 'field'='c.e': [3, 4]. Результат при 'field'='c.f': [None, 5]. Результат при 'field'='c:0': {'e': 3}. """ exists = True for i, key in enumerate(field.split(".")): if ":" in key: key, num = key.split(":") else: num = None try: if num: data = data[key][int(num)] else: data = data[key] except (KeyError, TypeError, IndexError): exists = False data = None break if isinstance(data, list): field = ".".join(field.split(".")[i + 1 :]) if field: if data: data = [get_dict_field_value(field, item)[1] if isinstance(item, dict) else None for item in data] else: data = None exists = False break return exists, data def dict_field_exists(*, field: str, data: dict): """ Проверка, можно ли найти поле 'field' в словаре 'data' """ return get_dict_field_value(field, data)[0] def dict_fields_exist(*, fields: list, data: dict, raise_exception: bool = False): """ Проверка наличия полей 'fields' в словаре 'data' """ errors = {} for field in fields: if not dict_field_exists(field=field, data=data): errors[field] = f"Поле '{field}' не найдено." if errors and raise_exception: raise DataCompareException(message_dict=errors) return errors def compare_values(a, b) -> bool: """ Сравнение двух объектов на равенство. Допустимые типы аргументов: dict, list, str, int, float, bool, NoneType, datetime. """ for value in [a, b]: assert type(value) in [ dict, list, str, int, float, bool, type(None), datetime.datetime, uuid.UUID, ], f"Недопустимый тип {type(value)} значения '{value}'." values = [a, b] types = [type(a), type(b)] if dict in types: if isinstance(b, dict): # Делаем, так чтобы 'a' являлся словарем a, b = b, a if not isinstance(b, dict): # None и {} считаются равными return (b is None) and (not a) else: # Случай, когда оба значения -- словари if (not a) and (not b): # Два пустых словаря return True if set(list(a.keys())) == set(list(b.keys())): return all(compare_values(a[key], b[key]) for key in a.keys()) elif types == [list, list]: # Списки сравниваются поэлементно if len(a) != len(b): # Равенство списков разной длины не считается возможным return False if all([(type(x) in [str, int, float]) for x in a + b]): try: # Сортировка таким образом, чтобы массив чисел сортировался так же, # как тот же массив с элементами, приведенными к типу str a = sorted(a, key=str) b = sorted(b, key=str) except TypeError: pass # Рекурсивное сравнение пар элементов списков return all(compare_values(a_i, b_i) for a_i, b_i in zip(a, b)) elif (bool in types) or (None in values): if (int in types) or (float in types) or (str in types): # Равенство между bool или None с числами и строками не считается возможным return False elif (list in types) and (bool in types): # Равенство между bool со списком не считается возможным return False # Приведение обоих значений к bool return bool(a) == bool(b) try: # Попытка привести оба значения к типу float return float(a) == float(b) except (TypeError, ValueError): pass if set(types) == {uuid.UUID, str}: return str(a) == str(b) return a == b def compare_dicts_keys( dict_1: dict, dict_2: dict, fields_to_compare: list = None, raise_exception: bool = False, ) -> dict: """ Проверка одновременного существования полей из списка 'fields_to_compare' в словарях 'dict_1' и 'dict_2'. """ errors = {} if fields_to_compare is None: fields_to_compare = set(list(dict_1.keys()) + list(dict_2.keys())) for field in fields_to_compare: dict_1_field_exists: bool = dict_field_exists(field=field, data=dict_1) dict_2_field_exists: bool = dict_field_exists(field=field, data=dict_2) if dict_1_field_exists != dict_2_field_exists: errors[field] = { "1": f"Поле '{field}' {'не ' if not dict_1_field_exists else ''} существует", "2": f"Поле '{field}' {'не ' if not dict_2_field_exists else ''} существует", } if errors and raise_exception: raise DataCompareException(message_dict=errors) return errors def compare_dicts_values( dict_1: dict, dict_2: dict, fields_to_compare: list = None, raise_exception: bool = False, ) -> dict: """ Сравнение значений полей из списка 'fields_to_compare' словарей 'dict_1' и 'dict_2'. """ errors = {} if fields_to_compare is None: fields_to_compare = set(list(dict_1.keys()) + list(dict_2.keys())) for fields_pair in fields_to_compare: if isinstance(fields_pair, list) or isinstance(fields_pair, tuple): fields_pair = tuple(fields_pair) # для хешируемости field_1 = fields_pair[0] field_2 = fields_pair[1] else: field_1 = fields_pair field_2 = fields_pair for field in [field_1, field_2]: if not isinstance(field, str): raise ValueError(f"Недопустимый тип поля: {type(field)}") _, value_1 = get_dict_field_value(field_1, dict_1) _, value_2 = get_dict_field_value(field_2, dict_2) equal = compare_values(value_1, value_2) if not equal: errors[fields_pair] = { "1": f"Значение поля '{field_1}': {value_1}", "2": f"Значение поля '{field_2}': {value_2}", } if errors and raise_exception: raise DataCompareException(message_dict=errors) return errors
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/compare_data.py
compare_data.py
from rest_framework import status from rest_framework.response import Response from rest_framework.exceptions import ValidationError from rest_framework.views import exception_handler as drf_exception_handler from zs_utils.json_utils import pretty_json __all__ = [ "CustomException", "CaptchaException", ] class CustomException(Exception): status_code: int = status.HTTP_400_BAD_REQUEST message: str = None messages: list = None message_dict: dict = None message_dict_key_prefix: str = None response = None response_code = None reason = None def __init__( self, message: str = None, *, instance=None, messages: list = None, message_dict: dict = None, message_dict_key_prefix: str = None, status_code=None, response=None, reason=None, **kwargs, ): super().__init__(**kwargs) attrs = dict( message=message, messages=messages, message_dict=message_dict, message_dict_key_prefix=message_dict_key_prefix, status_code=status_code, response=response, reason=reason, ) if instance: if not isinstance(instance, self.__class__): raise ValueError(f"Параметр 'instance' должен быть экземпляром класса '{self.__class__.__name__}'.") for key, value in attrs.items(): if value is None: attrs[key] = getattr(instance, key) self.set_attributes(**attrs) def __str__(self): message = "" if self.message: message += str(self.message) elif self.messages: message += "; ".join(self.messages) if self.message_dict: message += "\n" + pretty_json(data=self.message_dict) return message def __repr__(self) -> str: val = "" if self.messages: val = f"messages={self.messages}" elif self.message: val = f"message={self.message}" if self.message_dict: if val: val += ", " val += f"message_dict={self.message_dict}" return f"{self.__class__.__name__}({val})" def set_attributes(self, **kwargs): for key, value in kwargs.items(): if hasattr(self, key): if key == "status_code": if not value: continue elif key == "response": if value is not None: for field in ["code", "status_code", "status"]: if getattr(value, field, None): self.response_code = getattr(value, field) break elif key == "message_dict": prefix = kwargs.get("message_dict_key_prefix") if prefix: value = self.add_key_prefix(data=value, prefix=prefix) setattr(self, key, value) def add_key_prefix(self, data: dict, prefix: str, connector: str = ".", safe: bool = True): updated_data = {} for key, value in data.items(): if (not safe) or (not key.startswith(prefix)): updated_key = f"{prefix}{connector}{key}" else: updated_key = str(key) if isinstance(value, dict): updated_data[updated_key] = self.add_key_prefix(data=value, prefix=prefix, connector=connector) else: updated_data[updated_key] = value return updated_data def to_dict(self): if self.message_dict: data = dict(self.message_dict) elif self.messages: data = {"messages": self.messages} elif self.message: data = {"message": self.message} else: data = {"message": super().__str__()} return data def message_dict_to_str(self) -> str: if self.message_dict: return "\n".join(f"{key}: {value}" for key, value in self.message_dict.items()) else: return "" def messages_to_str(self) -> str: if self.messages: if len(self.messages) == 1: return str(self.messages[0]) else: return "\n".join(f"{num}) {msg}" for num, msg in enumerate(self.messages, start=1)) else: return "" class CaptchaException(CustomException): pass def flatten_errors_dict(data=None, parent_string=None): result = {} if isinstance(data, dict): for key, value in data.items(): if isinstance(value, dict) or isinstance(value, list): result.update( flatten_errors_dict( data=value, parent_string=parent_string + "." + str(key) if parent_string else str(key), ) ) else: pre_parent_string = parent_string + "." if parent_string else "" result[pre_parent_string + str(key)] = value elif isinstance(data, list): for item in data: if isinstance(item, dict): for num, item in enumerate(data): result.update(flatten_errors_dict(data=item, parent_string=f"{parent_string}.{num}")) break else: result[parent_string] = data return result def custom_exception_handler(exc: Exception, context: dict) -> Response: """ Кастомный обработчик ошибок. """ if isinstance(exc, CustomException): if (not exc.status_code) or (not status.is_server_error(code=exc.status_code)): detail = {} if exc.message: detail["message"] = exc.message if exc.messages: detail["messages"] = exc.messages if exc.message_dict: detail["errors"] = exc.message_dict exc = ValidationError(detail=detail, code=exc.status_code) elif isinstance(exc, ValidationError) and isinstance(exc.detail, dict): exc.detail = flatten_errors_dict(data=exc.detail) if "errors" not in exc.detail: exc.detail = {"errors": exc.detail} # if settings.SENTRY_ENABLED: # capture_sentry_exception(error=exc, user=context.get("user")) return drf_exception_handler(exc, context)
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/exceptions.py
exceptions.py
from channels import layers from asgiref.sync import async_to_sync from django.conf import settings from zs_utils.json_utils import custom_json_dumps from zs_utils.websocket import consumer __all__ = [ "WebsocketService", ] class WebsocketService: """ Сервис для отправки сообщений в вебсокет. """ @classmethod def send_data_to_consumer_group(cls, *, group_name: str, content: dict) -> None: """ Отправить данные content в websocket """ layer = layers.get_channel_layer() async_to_sync(layer.group_send)( group_name, { "type": "send.message", "content": custom_json_dumps(content, ensure_ascii=True), }, ) @classmethod def send_data_to_user(cls, *, user_id: int, content: dict) -> None: """ Отправить сообщение пользователю. """ group_name = consumer.BaseChannelsConsumer.get_user_group_name(user_id=user_id) cls.send_data_to_consumer_group(group_name=group_name, content=content) @classmethod def send_page_refresh_required_message(cls, user_id: int, page_path: str) -> None: """ Отправление пользователю сообщения о необходимости обновить страницу. """ group_name = consumer.BaseChannelsConsumer.get_user_group_name(user_id=user_id) cls.send_data_to_consumer_group( group_name=group_name, content={"event_type": "page_refresh_required", "page": page_path}, ) @classmethod def send_data_to_notification_group(cls, *, user_id: int, notification: str, data: dict) -> None: """ Отправить сообщение пользователю, если он подписан на группу событий. """ if notification not in getattr(settings, "WEBSOCKET_NOTIFICATION_GROUPS", []): raise ValueError("Недопустимая группа событий.") group_name = consumer.BaseChannelsConsumer.get_user_notification_group_name( user_id=user_id, notification=notification, ) cls.send_data_to_consumer_group(group_name=group_name, content={"notification": notification, "data": data})
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/websocket/services.py
services.py
from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from django.conf import settings from django.contrib.auth import get_user_model from zs_utils.json_utils import custom_json_dumps, custom_json_loads class BaseChannelsConsumer(AsyncJsonWebsocketConsumer): @database_sync_to_async def get_user(self, user_id: int): return get_user_model().objects.get(id=user_id) async def connect(self): if self.scope["user"]: self.user = self.scope["user"] else: if self.scope["token"]: # Соединение отвергается, если был передан невалидный токен if getattr(settings, "REQUIRE_JWT_FOR_WEBSOCKET", True): await self.close(code=403) return None # В режиме отладки используется тестовый пользователь self.user = await self.get_user(user_id=1) else: self.user = None if self.user: # Для каждого пользователя создается своя группа await self.add_to_group(self.get_user_group_name(user_id=self.user.id)) elif self.scope.get("connection_id"): # Создание группы для анонимного подключения await self.add_to_group(self.get_anon_group_name(connection_id=self.scope["connection_id"])) self.pretenders = {} await self.accept() async def disconnect(self, code): for group_name in self.groups: await self.remove_from_group(group_name=group_name) await self.close(code=code) async def add_to_group(self, group_name: str): await self.channel_layer.group_add(group_name, self.channel_name) if group_name not in self.groups: self.groups.append(group_name) async def remove_from_group(self, group_name: str): await self.channel_layer.group_discard(group_name, self.channel_name) if group_name in self.groups: self.groups.remove(group_name) @staticmethod def get_user_group_name(user_id: int): return f"user_group_{user_id}" @staticmethod def get_anon_group_name(connection_id: str): return f"anon_group_{connection_id}" @staticmethod def get_user_notification_group_name(user_id: int, notification: str): return f"notification_{notification}_group_{user_id}" @classmethod async def encode_json(cls, content: dict): return custom_json_dumps(content, ensure_ascii=False) @classmethod async def decode_json(cls, text_data: str): return custom_json_loads(text_data) async def send_message(self, event: dict): await self.send(text_data=event["content"]) async def send_error_message(self, message: str = None, errors: dict = None): await self.send_json(content={"is_success": False, "message": message, "errors": errors}) async def send_success_message(self, message: str = None): await self.send_json(content={"is_success": True, "message": message}) async def ping_action_processor(self, content: dict, **kwargs): await self.send_success_message(message="pong") async def disconnect_action_processor(self, content: dict, **kwargs): await self.disconnect(None) def subscribe_action_validator(self, content: dict, **kwargs): errors = {} for key in ["notification"]: if not content.get(key): errors[key] = "Обязательное поле." return errors async def subscribe_action_processor(self, content: dict, **kwargs): if self.user: if self.user.id in self.pretenders: user_id = self.pretenders[self.user.id] else: user_id = self.user.id group_name = self.get_user_notification_group_name( user_id=user_id, notification=content["notification"], ) else: group_name = content["notification"] await self.add_to_group(group_name=group_name) await self.send_success_message(message="Подписка создана.") def unsubscribe_action_validator(self, content: dict, **kwargs): return self.subscribe_action_validator(content=content, **kwargs) async def unsubscribe_action_processor(self, content: dict, **kwargs): if self.user: if self.user.id in self.pretenders: user_id = self.pretenders[self.user.id] else: user_id = self.user.id group_name = self.get_user_notification_group_name( user_id=user_id, notification=content["notification"], ) else: group_name = content["notification"] await self.remove_from_group(group_name=group_name) await self.send_success_message(message="Подписка удалена.") def pretend_on_action_validator(self, content: dict, **kwargs): errors = {} for key in ["user_id"]: if not content.get(key): errors[key] = "Обязательное поле." return errors async def pretend_on_action_processor(self, content: dict, **kwargs): if self.user and self.user.is_staff: await self.add_to_group(group_name=self.get_user_group_name(user_id=content["user_id"])) await self.remove_from_group(group_name=self.get_user_group_name(user_id=self.user.id)) self.pretenders[self.user.id] = content["user_id"] await self.send_success_message(message="Режим получения сообщений другого пользователя включен.") def pretend_off_action_validator(self, content: dict, **kwargs): return self.pretend_on_action_validator(content=content, **kwargs) async def pretend_off_action_processor(self, content: dict, **kwargs): if self.user and self.user.is_staff: await self.add_to_group(group_name=self.get_user_group_name(user_id=self.user.id)) await self.remove_from_group(group_name=self.get_user_group_name(user_id=content["user_id"])) if self.user.id in self.pretenders: self.pretenders.pop(self.user.id) await self.send_success_message(message="Режим получения сообщений другого пользователя отключен.") async def receive_json(self, content: dict, **kwargs): action: str = content.get("action") if action and getattr(settings, "WEBSOCKET_ACTIONS", None): if action not in settings.WEBSOCKET_ACTIONS: return await self.send_error_message(message="Недопустимое действие.") validator = getattr(self, f"{action}_action_validator", None) if validator: errors: dict = validator(content=content) if errors: return await self.send_error_message(message="Ошибка валидации", errors=errors) processor = getattr(self, f"{action}_action_processor") if processor: await processor(content=content, **kwargs)
zonesmart-utils
/zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/websocket/consumer.py
consumer.py