Beispiel #1
0
def Speak(text, store=True):
    #DONE: if p has attr talk > pass it via ssh
    #TODO: avoid errors
    # AttributeError: 'NoneType' object has no attribute 'group'
    if not hasattr(m, 'p'): m.p = CONFIGURATION()
    if not hasattr(m, 'logger'): m.logger = LOGGER('TALK', 'INFO')
    for k, v in Substitutons():
        text = text.replace('%' + k, v)
    m.logger.info('SPEAKING ' + text)
    if hasattr(m.p, 'talk'):  # talk over ssh
        m.logger.debug('passing to ' + str(m.p.talk.ip))
        config = m.p.talk.__dict__
        config['text'] = text
        cmd = "ssh -p {port} -i {ssh} {user}@{ip} nohup python /home/pi/git/pi/modules/talk.py '\"{text}\"'".format(
            **config)  # was with &
        os.system(cmd)
    else:  # direct
        lock = Lock('speak')
        lock.Lock()
        Google_speak(text, m.p.LANGUAGE, store)
        lock.Unlock()
    m.logger.debug('---')
    return {'status': True, 'text': text}
Beispiel #2
0
"""
Created on Sun Apr 22 07:14:48 2018

@author: s84004
"""

from __future__ import print_function
import __main__ as m
import os
from time import sleep

from common import LOGGER
from PingIPhone import PingIP


def RebootOnLostConnection():
    "reboot pi on loosing connection to router"
    for attempt in range(0, 5):
        if PingIP(1)[0] == False:
            m.logger.info('no connection found, attempt ' + str(attempt))
        else:
            m.logger.info('router ping : OK')
            return
        sleep(60)
    m.logger.error('REBOOTING PI')
    os.system('sudo reboot')


if __name__ == '__main__':
    logger = LOGGER('RebootOnLostConnection')
    RebootOnLostConnection()
Beispiel #3
0
#        while True:
#            self.Light_Sensor()
#            try:
#                m.logger.debug( '\tsensor\t' + str(self.result[-1]))
#            except:
#                pass
#            time.sleep(loop_delay)

#    def Plot(self):
#        self.df = pd.read_csv(self.sensor_log,sep = '\t', names=['date','val'], index_col='date', parse_dates=True)
#
#

if __name__ == '__main__':
    from common import LOGGER  #, FAKE as OBJECT
    #    m = OBJECT()
    #    m.logger = LOGGER('esp.txt', level = 'INFO')
    logger = LOGGER('esp.txt', level='LOG')

    e = ESP()
    if len(sys.argv) > 1:
        if sys.argv[1] == 'sensor':
            #            e.Sensor_Loop(loop_delay = 5)
            pass
#    e.Go_parallel( )
#    e.Light_Sensor( )
#e.Go(['6','rf433','all','off'])
##
# 1. integrate into plot
# 2. clean logic
# on off logic > if its morning and light > ... >> off
Beispiel #4
0

def name_from_text(text):
    return re.sub(r""",- !@#$%^&*;:."(')//\\""", '',
                  text).replace(' ', '').lower()[:250]


def random_name(x=10):
    try:
        return "".join([random.choice(string.letters) for i in range(x)])
    except:
        return "".join([random.choice(string.ascii_letters) for i in range(x)])


if __name__ == "__main__":
    logger = LOGGER('TALK', 'INFO')
    p = CONFIGURATION()
    logger.debug('config read')

    # versions
    try:
        m.logger.info('gtts version: ' + str(gtts.__version__))
    except:
        pass

    if len(sys.argv) > 1:
        text = ' '.join([i for i in sys.argv[1:] if i != '-d'])
        if text == '': text = 'Hello world'
    else:
        text = "hello world"
    Speak(text)
Beispiel #5
0
            '/home/pi/git/config.ini', '/home/pi/pgpass.conf'
        ] if os.path.exists(i)
    ]
    return files


def send(config, dmp_check):
    logger.info('attaching files:\n' + '\n'.join(files_to_backup(config)))
    logger.info('sending email ... ' + \
                sendMail([p.email.address], \
                         [p.email.address, p.email.login, p.email.password],\
                         'archive from ' + socket.gethostname(), \
                         str(files_to_backup(config)) + '\n' + dmp_check, \
                         files_to_backup(config)))


if __name__ == '__main__':
    "syntax: python archiving.py {hornet_pi_db}"
    if len(sys.argv) > 1:
        arg = sys.argv[1]
    else:
        arg = ''
    p = CONFIGURATION()
    logger = LOGGER('archiving', level='INFO')
    logger.info('\n')
    dump_crontab()
    if arg != '':
        config, dmp_check = dump_db(arg)
    else:
        config, dmp_check = {'FILENAME': ''}, ''
    send(config, dmp_check)
Beispiel #6
0

def _pa(args):
    "subtask pa"
    """call common PA methods via api or local or on remote using ssh
    - pa = direct|yes
    - pa = ip|192.168.1.154,user|pi,ssh|/home/pi/.ssh/octopus,port|2227
    - pa = api|,host|localhost,port|8083
    pa([RUN,{options}])
    """

    config = CONFIGURATION().pa.__dict__
    config['RUN'] = args[0].upper() if type(
        args) == list else args.upper()  # 1st param is MODULE

    if 'ssh' in config.keys():
        cmd = "ssh -p {port} -i {ssh} {user}@{ip} nohup python /home/pi/git/pi/PA.py '{RUN}'".format(
            **config)
    elif 'api' in config.keys():
        config['params'] = '' if len(args) == 1 else '\&args=' + ';'.join(
            args[1:])
        cmd = "curl {host}:{port}/cmnd?RUN={RUN}{params}".format(**config)
    else:
        cmd = "python3 /home/pi/git/pi/PA.py '{RUN}'".format(**config)  #was &
    m.logger.info(cmd)
    os.system(cmd)


if __name__ == '__main__':
    logger = LOGGER('pa')
    pa([i for i in sys.argv[1:] if i != '-d'])  #pass args as list
Beispiel #7
0
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 06:41:02 2018

@author: Alexander Ignatov
"""
import sys
sys.path.append('/home/pi/git/pi/modules')
from common import LOGGER
import time

if __name__ == '__main__':
    logger = LOGGER('service_test', 'INFO')
    while True:
        logger.info('service ping ')
        time.sleep(10)
Beispiel #8
0
Datei: iss.py Projekt: ignalex/pi
def Start():
    global iss, delay
    last_time_stamp = None
    iss = ISS()
    while True:
        try:
            iss.Scan()
            if iss.timestamp != last_time_stamp: iss.Log()
            last_time_stamp =  iss.timestamp
        except:
            logger.error('iss scan error')
        time.sleep(delay)

if __name__ == '__main__':

    logger = LOGGER('iss', 'INFO')
    p = CONFIGURATION()

    con, cur = PG_Connect(getattr(p,p.ISS.db).__dict__)

    delay = int(p.ISS.delay) # secs
    location = (151.2, -33.85)
    alert, alert_type, alert_distance, alert_time, alert_time_window = True, 'speak', int(p.ISS.alert_distance), datetime.datetime.now() - datetime.timedelta(hours = 12), (6,21) # initital time > setting to yesterday
    proxies = {}
    time.sleep(delay) # to manage SSL entropy on reboot
    try:
        Speak('I monitor ISS position, will let you know if it is within {} km'.format(alert_distance))
        logger.info('starting')
        Start()
    except:
        MainException()
Beispiel #9
0
from pyhap.accessory import Bridge
from pyhap.accessory_driver import AccessoryDriver
#import pyhap.loader as loader

# The below package can be found in the HAP-python github repo under accessories/

from accessories_ai.sensors import TemperatureSensor, LightSensor
from accessories_ai.switches import AllSwitches, EspStatusCollector
# from accessories_ai.windows import WindowCovering
from accessories_ai.computers import SYSTEM

from accessories_ai.MotionSensor import MotionSensor

from common import LOGGER, CONFIGURATION
p = CONFIGURATION()
logger = LOGGER('HAP_server', 'INFO')

from talk import Speak
Speak('starting HAP server')

st = EspStatusCollector(
    ips=[p.devices.esp],
    sleep=10)  # starting threaded status collector, must have name 'st'


def get_bridge(driver):
    """Call this method to get a Bridge instead of a standalone accessory."""
    bridge = Bridge(driver, 'Bridge')

    temp_sensor = TemperatureSensor(driver, 'temperature')
    light = AllSwitches(driver, 'light')
Beispiel #10
0
                    if IR in XBMC_dic.keys():
                        kodi(XBMC_dic[IR])
                    elif codeIR[0] in extra_esp_keys:
                        e = ESP()
                        e.Go_parallel(extra_esp_keys[IR])
                    else:
                        logger.info('speaking only ' + IR)
                        Speak(IR)
                last = [IR, datetime.datetime.now()]
        except:
            logger.error('error : ' + str(sys.exc_info()))
            Speak('error in lirc module')
            sleep(2)
        sleep(0.3)


if __name__ == '__main__':
    #    with daemon.DaemonContext():
    try:
        from common import LOGGER, PID
        logger = LOGGER('lirc')
        #            logger = log # compatibility
        logger.info('starting lirc')
        from time import sleep
        from KODI_control import kodi
        PID()
        import lirc
        sockid = lirc.init("test", blocking=False)
        Start()
    except:
        logger.error('error on initiation: ' + str(sys.exc_info()))
Beispiel #11
0
#DONE: email feedback > after secured config
#TODO: restart particular apps
#DONE: speak commit message
#TODO: secure path
#DONE: port > to params

from __future__ import print_function
from flask import Flask, request
from common import LOGGER, Dirs, CONFIGURATION#, MainException
from send_email import sendMail
from talk import Speak
import pickle, os, datetime
from subprocess import Popen, PIPE
import daemon, socket

logger = LOGGER('git_hook')
p = CONFIGURATION()

app = Flask(__name__)

@app.route("/git_pull", methods=['POST'])
def git_pull():
    try:
        global logger, p
        j = request.json # payload
        if p.GIT_CI.save_payload:
            with open(os.path.join(Dirs()['LOG'],'git_payload_{}.pcl'.format(str(datetime.datetime.now()))), 'wb') as f:
                pickle.dump(j, f)

        #checking payload
        if j['head_commit']['committer']['email'] != p.GIT_CI.check_committer: