prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): <|fim_middle|> def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost'
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): <|fim_middle|> def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
""" Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m)
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): <|fim_middle|> def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
""" Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): <|fim_middle|> def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
""" Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None)
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): <|fim_middle|> <|fim▁end|>
""" Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape)
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: <|fim_middle|> elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost'
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': <|fim_middle|> else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: <|fim_middle|> def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost'
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': <|fim_middle|> def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None)
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: <|fim_middle|> else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
X_all = x costs_all = cost_evals
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: <|fim_middle|> self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals))
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def <|fim_middle|>(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
__init__
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def <|fim_middle|>(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
_cost_gp
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def <|fim_middle|>(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
_cost_gp_withGradients
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def <|fim_middle|>(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
update_cost_model
<|file_name|>cost.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """ def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def <|fim_middle|>(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape) <|fim▁end|>
constant_cost_withGradients
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys<|fim▁hole|>from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG))<|fim▁end|>
import datetime from invoke import task from invoke.util import cd
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): <|fim_middle|> @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path'])
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): <|fim_middle|> @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""Build local version of site""" c.run('pelican -s pelicanconf.py')
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): <|fim_middle|> @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py')
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): <|fim_middle|> @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py')
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): <|fim_middle|> @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever()
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): <|fim_middle|> server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
allow_reuse_address = True
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): <|fim_middle|> @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""`build`, then `serve`""" build(c) serve(c)
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): <|fim_middle|> @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""Build production version of site""" c.run('pelican -s publishconf.py')
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): <|fim_middle|> @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
"""Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG))
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): <|fim_middle|> <|fim▁end|>
"""Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG))
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): <|fim_middle|> @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path'])
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def <|fim_middle|>(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
clean
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def <|fim_middle|>(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
build
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def <|fim_middle|>(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
rebuild
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def <|fim_middle|>(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
regenerate
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def <|fim_middle|>(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
serve
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def <|fim_middle|>(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
reserve
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def <|fim_middle|>(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
preview
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def <|fim_middle|>(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def gh_pages(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
publish
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Github Pages configuration 'github_pages_branch': 'gh-pages', 'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()), # Port for `serve` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def rebuild(c): """`build` with the delete switch""" c.run('pelican -d -s pelicanconf.py') @task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer( CONFIG['deploy_path'], ('', CONFIG['port']), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG)) server.serve_forever() @task def reserve(c): """`build`, then `serve`""" build(c) serve(c) @task def preview(c): """Build production version of site""" c.run('pelican -s publishconf.py') @task def publish(c): """Publish to production via rsync""" c.run('pelican -s publishconf.py') c.run( 'rsync --delete --exclude ".DS_Store" -pthrvz -c ' '{} {production}:{dest_path}'.format( CONFIG['deploy_path'].rstrip('/') + '/', **CONFIG)) @task def <|fim_middle|>(c): """Publish to GitHub Pages""" preview(c) c.run('ghp-import -b {github_pages_branch} ' '-m {commit_message} ' '{deploy_path} -p'.format(**CONFIG)) <|fim▁end|>
gh_pages
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
from errors import * from manager import SchemaManager
<|file_name|>test_MatplotlibTimelines.py<|end_file_name|><|fim▁begin|>import unittest <|fim▁hole|> theSuite=unittest.TestSuite()<|fim▁end|>
from PyFoam.Basics.MatplotlibTimelines import MatplotlibTimelines
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] <|fim▁hole|> if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow<|fim▁end|>
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): <|fim_middle|> class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): <|fim_middle|> <|fim▁end|>
"""An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): <|fim_middle|> @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): <|fim_middle|> @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Return the name of this camera.""" return self._name
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): <|fim_middle|> @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Return a unique ID.""" return self._camera.id
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): <|fim_middle|> async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, }
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): <|fim_middle|> async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): <|fim_middle|> @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close()
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): <|fim_middle|> def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
"""Update the image periodically.""" return True
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): <|fim_middle|> <|fim▁end|>
"""Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: <|fim_middle|> else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
cams.append(RingCam(hass, camera, config))
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: <|fim_middle|> for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
cams_no_plan.append(camera)
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: <|fim_middle|> else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
cams.append(RingCam(hass, camera, config))
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: <|fim_middle|> # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
cams_no_plan.append(camera)
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: <|fim_middle|> add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: <|fim_middle|> image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
return
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: <|fim_middle|> stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
return
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): <|fim_middle|> <|fim▁end|>
video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: <|fim_middle|> <|fim▁end|>
_LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def <|fim_middle|>(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
setup_platform
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def <|fim_middle|>(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
__init__
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def <|fim_middle|>(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
name
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def <|fim_middle|>(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
unique_id
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def <|fim_middle|>(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
device_state_attributes
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def <|fim_middle|>(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
async_camera_image
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def <|fim_middle|>(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
handle_async_mjpeg_stream
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def <|fim_middle|>(self): """Update the image periodically.""" return True def update(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
should_poll
<|file_name|>camera.py<|end_file_name|><|fim▁begin|>"""This component provides support to the Ring Door Bell camera.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Ring Door Bell and StickUp Camera.""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """An implementation of a Ring Door Bell camera.""" def __init__(self, hass, camera, device_info): """Initialize a Ring Door Bell camera.""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """Return the name of this camera.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._camera.id @property def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """Update the image periodically.""" return True def <|fim_middle|>(self): """Update camera entity and refresh attributes.""" _LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info("Ring DoorBell properties refreshed") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow <|fim▁end|>
update
<|file_name|>0004_auto_20160525_1032.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0003_remove_userprofile_is_check'), ] <|fim▁hole|> model_name='userprofile', name='is_create', ), migrations.RemoveField( model_name='userprofile', name='is_delete', ), migrations.RemoveField( model_name='userprofile', name='is_modify', ), ]<|fim▁end|>
operations = [ migrations.RemoveField(
<|file_name|>0004_auto_20160525_1032.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('account', '0003_remove_userprofile_is_check'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='is_create', ), migrations.RemoveField( model_name='userprofile', name='is_delete', ), migrations.RemoveField( model_name='userprofile', name='is_modify', ), ]
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|>from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem):<|fim▁hole|> er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText())<|fim▁end|>
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): <|fim_middle|> class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar)
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): <|fim_middle|> class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar)
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): <|fim_middle|> class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er)
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): <|fim_middle|> def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
self._c = c
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): <|fim_middle|> class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
er = ExternalResource('http://www.google.com') self._c.getWindow().open(er)
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): <|fim_middle|> <|fim▁end|>
def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText())
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): <|fim_middle|> def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
self._c = c
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): <|fim_middle|> <|fim▁end|>
self._c.getWindow().showNotification('Action ' + selectedItem.getText())
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def <|fim_middle|>(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
__init__
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def <|fim_middle|>(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
__init__
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def <|fim_middle|>(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
menuSelected
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def <|fim_middle|>(self, c): self._c = c def menuSelected(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
__init__
<|file_name|>MenuBarItemStylesExample.py<|end_file_name|><|fim▁begin|> from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menubar = MenuBar() menuCommand = MenuCommand(self) # Save reference to individual items so we can add sub-menu items to # them f = self._menubar.addItem('File', None) newItem = f.addItem('New', None) f.addItem('Open f...', menuCommand) f.addSeparator() # Add a style name for a menu item, then use CSS to alter the visuals f.setStyleName('file') newItem.addItem('File', menuCommand) newItem.addItem('Folder', menuCommand) newItem.addItem('Project...', menuCommand) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) edit.addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menuCommand) # Actions can be added inline as well, of course find.addItem('Google Search', SearchCommand(self)) find.addSeparator() find.addItem('Find/Replace...', menuCommand) find.addItem('Find Next', menuCommand) find.addItem('Find Previous', menuCommand) view = self._menubar.addItem('View', None) view.addItem('Show/Hide Status Bar', menuCommand) view.addItem('Customize Toolbar...', menuCommand) view.addSeparator() view.addItem('Actual Size', menuCommand) view.addItem('Zoom In', menuCommand) view.addItem('Zoom Out', menuCommand) self.addComponent(self._menubar) class SearchCommand(ICommand): def __init__(self, c): self._c = c def menuSelected(self, selectedItem): er = ExternalResource('http://www.google.com') self._c.getWindow().open(er) class MenuCommand(ICommand): def __init__(self, c): self._c = c def <|fim_middle|>(self, selectedItem): self._c.getWindow().showNotification('Action ' + selectedItem.getText()) <|fim▁end|>
menuSelected
<|file_name|>switch_subdesign.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Written by Daniel M. Aukes and CONTRIBUTORS Email: danaukes<at>asu.edu. Please see LICENSE for full license. """ import sys import popupcad import qt.QtCore as qc import qt.QtGui as qg if __name__=='__main__':<|fim▁hole|> app = qg.QApplication(sys.argv[0]) filename_from = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R08.cad' filename_to = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R09.cad' d = popupcad.filetypes.design.Design.load_yaml(filename_from) widget = qg.QDialog() layout = qg.QVBoxLayout() layout1 = qg.QHBoxLayout() layout2 = qg.QHBoxLayout() list1 = qg.QListWidget() list2 = qg.QListWidget() button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') subdesign_list = list(d.subdesigns.values()) for item in subdesign_list: list1.addItem(str(item)) list2.addItem(str(item)) layout1.addWidget(list1) layout1.addWidget(list2) layout2.addWidget(button_ok) layout2.addWidget(button_cancel) layout.addLayout(layout1) layout.addLayout(layout2) widget.setLayout(layout) button_ok.pressed.connect(widget.accept) button_cancel.pressed.connect(widget.reject) if widget.exec_(): if len(list1.selectedIndexes())==1 and len(list2.selectedIndexes())==1: ii_from = list1.selectedIndexes()[0].row() ii_to = list2.selectedIndexes()[0].row() print(ii_from,ii_to) d.replace_subdesign_refs(subdesign_list[ii_from].id,subdesign_list[ii_to].id) d.subdesigns.pop(subdesign_list[ii_from].id) d.save_yaml(filename_to) sys.exit(app.exec_())<|fim▁end|>
<|file_name|>switch_subdesign.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Written by Daniel M. Aukes and CONTRIBUTORS Email: danaukes<at>asu.edu. Please see LICENSE for full license. """ import sys import popupcad import qt.QtCore as qc import qt.QtGui as qg if __name__=='__main__': <|fim_middle|> <|fim▁end|>
app = qg.QApplication(sys.argv[0]) filename_from = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R08.cad' filename_to = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R09.cad' d = popupcad.filetypes.design.Design.load_yaml(filename_from) widget = qg.QDialog() layout = qg.QVBoxLayout() layout1 = qg.QHBoxLayout() layout2 = qg.QHBoxLayout() list1 = qg.QListWidget() list2 = qg.QListWidget() button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') subdesign_list = list(d.subdesigns.values()) for item in subdesign_list: list1.addItem(str(item)) list2.addItem(str(item)) layout1.addWidget(list1) layout1.addWidget(list2) layout2.addWidget(button_ok) layout2.addWidget(button_cancel) layout.addLayout(layout1) layout.addLayout(layout2) widget.setLayout(layout) button_ok.pressed.connect(widget.accept) button_cancel.pressed.connect(widget.reject) if widget.exec_(): if len(list1.selectedIndexes())==1 and len(list2.selectedIndexes())==1: ii_from = list1.selectedIndexes()[0].row() ii_to = list2.selectedIndexes()[0].row() print(ii_from,ii_to) d.replace_subdesign_refs(subdesign_list[ii_from].id,subdesign_list[ii_to].id) d.subdesigns.pop(subdesign_list[ii_from].id) d.save_yaml(filename_to) sys.exit(app.exec_())
<|file_name|>switch_subdesign.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Written by Daniel M. Aukes and CONTRIBUTORS Email: danaukes<at>asu.edu. Please see LICENSE for full license. """ import sys import popupcad import qt.QtCore as qc import qt.QtGui as qg if __name__=='__main__': app = qg.QApplication(sys.argv[0]) filename_from = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R08.cad' filename_to = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R09.cad' d = popupcad.filetypes.design.Design.load_yaml(filename_from) widget = qg.QDialog() layout = qg.QVBoxLayout() layout1 = qg.QHBoxLayout() layout2 = qg.QHBoxLayout() list1 = qg.QListWidget() list2 = qg.QListWidget() button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') subdesign_list = list(d.subdesigns.values()) for item in subdesign_list: list1.addItem(str(item)) list2.addItem(str(item)) layout1.addWidget(list1) layout1.addWidget(list2) layout2.addWidget(button_ok) layout2.addWidget(button_cancel) layout.addLayout(layout1) layout.addLayout(layout2) widget.setLayout(layout) button_ok.pressed.connect(widget.accept) button_cancel.pressed.connect(widget.reject) if widget.exec_(): <|fim_middle|> sys.exit(app.exec_())<|fim▁end|>
if len(list1.selectedIndexes())==1 and len(list2.selectedIndexes())==1: ii_from = list1.selectedIndexes()[0].row() ii_to = list2.selectedIndexes()[0].row() print(ii_from,ii_to) d.replace_subdesign_refs(subdesign_list[ii_from].id,subdesign_list[ii_to].id) d.subdesigns.pop(subdesign_list[ii_from].id) d.save_yaml(filename_to)
<|file_name|>switch_subdesign.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Written by Daniel M. Aukes and CONTRIBUTORS Email: danaukes<at>asu.edu. Please see LICENSE for full license. """ import sys import popupcad import qt.QtCore as qc import qt.QtGui as qg if __name__=='__main__': app = qg.QApplication(sys.argv[0]) filename_from = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R08.cad' filename_to = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R09.cad' d = popupcad.filetypes.design.Design.load_yaml(filename_from) widget = qg.QDialog() layout = qg.QVBoxLayout() layout1 = qg.QHBoxLayout() layout2 = qg.QHBoxLayout() list1 = qg.QListWidget() list2 = qg.QListWidget() button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') subdesign_list = list(d.subdesigns.values()) for item in subdesign_list: list1.addItem(str(item)) list2.addItem(str(item)) layout1.addWidget(list1) layout1.addWidget(list2) layout2.addWidget(button_ok) layout2.addWidget(button_cancel) layout.addLayout(layout1) layout.addLayout(layout2) widget.setLayout(layout) button_ok.pressed.connect(widget.accept) button_cancel.pressed.connect(widget.reject) if widget.exec_(): if len(list1.selectedIndexes())==1 and len(list2.selectedIndexes())==1: <|fim_middle|> sys.exit(app.exec_())<|fim▁end|>
ii_from = list1.selectedIndexes()[0].row() ii_to = list2.selectedIndexes()[0].row() print(ii_from,ii_to) d.replace_subdesign_refs(subdesign_list[ii_from].id,subdesign_list[ii_to].id) d.subdesigns.pop(subdesign_list[ii_from].id) d.save_yaml(filename_to)
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config <|fim▁hole|> """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers<|fim▁end|>
async def async_attach_trigger(hass, config, action, automation_info):
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): <|fim_middle|> async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
"""Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def async_attach_trigger(hass, config, action, automation_info): <|fim_middle|> async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
"""Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" )
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): <|fim_middle|> <|fim▁end|>
"""List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: <|fim_middle|> return config async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): <|fim_middle|> return config async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
raise InvalidDeviceAutomationConfig
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: <|fim_middle|> trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
return None
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: <|fim_middle|> triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
return
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def <|fim_middle|>(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
async_validate_trigger_config
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def <|fim_middle|>(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def async_get_triggers(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
async_attach_trigger
<|file_name|>device_trigger.py<|end_file_name|><|fim▁begin|>"""Provides device automations for ZHA devices that emit events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = "subtype" DEVICE = "device" DEVICE_IEEE = "device_ieee" ZHA_EVENT = "zha_event" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) if "zha" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type="device" ) async def <|fim_middle|>(hass, device_id): """List device triggers. Make sure the device supports device automations and if it does return the trigger list. """ zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers <|fim▁end|>
async_get_triggers
<|file_name|>FiredriveCom.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from pyload.plugin.internal.DeadCrypter import DeadCrypter <|fim▁hole|> __name = "FiredriveCom" __type = "crypter" __version = "0.03" __pattern = r'https?://(?:www\.)?(firedrive|putlocker)\.com/share/.+' __config = [] #@TODO: Remove in 0.4.10 __description = """Firedrive.com folder decrypter plugin""" __license = "GPLv3" __authors = [("Walter Purcaro", "[email protected]")]<|fim▁end|>
class FiredriveCom(DeadCrypter):