示例#1
0
def get_the_week(current_day):
    # Checks the number of the week per entered day
    year, month, day = current_day.strftime('%Y %-m %-d').split(' ')
    week_number = date(int(year), int(month), int(day) + 1).isocalendar()[1]
    msg = '{} {} {}'.format(current_day, 'is on week number', week_number)
    logging_handler(msg)
    return week_number
示例#2
0
文件: main.py 项目: pavelzag/RaspGen
def off_command(time_args=None):
    """"Processes the Off Command"""
    generator_cmd(cmd='off')
    if check_internet_connection():
        set_gen_state(state=False, time_stamp=get_current_time())
    if time_args:
        timeout_frame, time_left = time_args
        on_time = chop_microseconds(
            datetime.timedelta(0, 0, 0, 0, timeout_frame) -
            time_left).seconds + 120
        usage_time = str(datetime.timedelta(seconds=on_time))
        mail_msg = '{} {} {}'.format('Generator is going down after',
                                     usage_time, 'minutes')
    elif start_time:
        # Adding 2 minutes compensation for going down
        # TODO fix scenario of shutting down when going offline
        on_time = int(
            (datetime.datetime.now() - start_time).total_seconds()) + 120
        how_long, units = calculate_time_span(on_time)
        msg_to_log = '{} {} {}'.format('The generator was up for:', how_long,
                                       units)
        logging_handler(msg_to_log)
        mail_msg = '{} {}'.format(down_msg, msg_to_log)
    if check_internet_connection():
        set_time_spent(time_stamp=get_current_time(date=True,
                                                   datetime_format=True),
                       time_span=on_time)
        send_mail(send_to=from_address,
                  subject='Generator Control Message',
                  text=mail_msg)
    else:
        logging_handler('Shutting down the generator')
示例#3
0
def send_mail(send_from='*****@*****.**',
              send_to='',
              subject='hi',
              text='text',
              file=None,
              server="smtp.gmail.com"):
    logging_handler('{} {} {} {}'.format('Sending', text, 'mail to:', send_to))
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))
    if file is not None:
        with open(file, "rb") as fil:
            part = MIMEApplication(fil.read(), Name=basename(file))
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(
            file)
        msg.attach(part)

    smtp = smtplib.SMTP(server, 587)
    smtp.ehlo()
    smtp.starttls()
    sender_email = get_config('email')
    sender_password = get_config('password')
    result = smtp.login(sender_email, sender_password)[1]
    logging_handler('{} {}'.format('Connection to SMTP result:', result))
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
示例#4
0
def get_db_creds(parameter_name):
    if is_heroku:
        logging_handler(os.environ.get(parameter_name))
        return os.environ.get(parameter_name, 'Theres\'s nothing here')
    else:
        with open("config.yml", 'r') as ymlfile:
            cfg = yaml.load(ymlfile)
            return cfg['db-params'][parameter_name]
示例#5
0
文件: main.py 项目: pavelzag/RaspGen
def log_command():
    """"Processes the Log Command"""
    msg = '{} {}'.format('Sending logs to', from_address)
    logging_handler(msg)
    send_mail(send_to=from_address,
              subject='Log Message',
              text='Logs attached',
              file=file_logging_path)
    delete_messages()
示例#6
0
文件: main.py 项目: pavelzag/RaspGen
def usage_command():
    """"Processes the Usage Command"""
    usage_seconds = calculate_monthly_usage(datetime.datetime.now().month)
    usage_time = str(datetime.timedelta(seconds=usage_seconds))
    msg = '{} {} {}'.format('Generator has been working for', usage_time,
                            'this month')
    logging_handler(msg)
    send_mail(send_to=from_address,
              subject='Generator Usage Message',
              text=msg)
    delete_messages()
示例#7
0
文件: main.py 项目: pavelzag/RaspGen
def delete_messages():
    """Deletes messages in Mail Inbox"""
    logging_handler('Deleting messages')
    msrvr = imaplib.IMAP4_SSL(imap_addr, imap_port)
    msrvr.login(receiver_email, receiver_password)
    msrvr.select('Inbox')
    typ, data = msrvr.search(None, 'ALL')
    for num in data[0].split():
        msrvr.store(num, '+FLAGS', '\\Deleted')
    msrvr.expunge()
    logging_handler('Messages were deleted successfully')
示例#8
0
def set_initial_db_state():
    """"Sets the state entry in DB to off on boot"""
    msg = 'Setting db state on boot on off'
    logging_handler(msg)
    try:
        db.generator_state.update_one({'_id': 'gen_state'}, {"$set": {"state": False}}, upsert=True)
        success_msg = 'status set successfully'
        logging.info(success_msg)
    except (AttributeError, errors.OperationFailure):
        error_msg = 'There was a problem setting up db initial status'
        logging_handler(error_msg)
示例#9
0
文件: main.py 项目: pavelzag/RaspGen
def status_command():
    """"Processes the Status Command"""
    if start_time:
        time_span = (datetime.datetime.now() - start_time).total_seconds()
        how_long, units = calculate_time_span(time_span)
        msg = '{} {} {} {} {}'.format('Generator is', get_gen_state(), 'for',
                                      how_long, units)
    else:
        msg = '{} {}'.format('Generator is', get_gen_state())
    logging_handler(msg)
    send_mail(send_to=from_address, subject='Status Message', text=msg)
    delete_messages()
示例#10
0
def get_gen_state():
    """"Gets generator's status"""
    msg = 'Getting generator status'
    logging_handler(msg)
    cursor = db.generator_state.find({})
    for document in cursor:
        if document['state'] is False:
            gen_state = 'down'
        else:
            gen_state = 'up'
        msg = '{} {}'.format('Generator status is:', gen_state)
        logging_handler(msg)
        return str(gen_state)
示例#11
0
文件: main.py 项目: pavelzag/RaspGen
def generator_cmd(cmd):
    """"Sending the generator command"""
    if uname()[1] == 'DietPi':
        import RPi.GPIO as GPIO
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.HIGH)
        if cmd == 'on':
            GPIO.output(pin, False)
        elif cmd == 'off':
            GPIO.output(pin, True)
    else:
        logging_handler('test mode. generator is not going up')
示例#12
0
def main():
    last_update_id = None
    while True:
        updates = get_updates(last_update_id)
        if len(updates["result"]) > 0:
            last_update_id = get_last_update_id(updates) + 1
            if is_voice(updates):
                chat_id, voice_id = get_last_chat_id_and_text(updates)
                msg = '{} {}'.format('tok was received from', chat_id)
                logging_handler(msg)
                save_query(voice_id)
                send_message('Tok saved', chat_id)
            else:
                chat_id = get_last_chat_id_and_text(updates, text=True)
                voice_id = get_random_tok()
                msg = '{} {} {}'.format(voice_id, 'tok was sent to', chat_id)
                logging_handler(msg)
                send_voice(voice_id, chat_id)
        time.sleep(0.5)
示例#13
0
文件: main.py 项目: pavelzag/RaspGen
def poll_mail():
    """Returns a key command that is being received from the mail and the sender"""
    msrvr = imaplib.IMAP4_SSL(imap_addr, imap_port)
    msrvr.login(receiver_email, receiver_password)
    stat, cnt = msrvr.select('Inbox')
    for i in cnt:
        typ, msg_data = msrvr.fetch(str(i), '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
    if msg:
        from_message = msg['From']
        if '<' in from_message:
            sender = re.findall(r'<(.*?)>', from_message)[0]
        else:
            sender = from_message
        try:
            key_command = msg['subject'].lower()
            logging_handler('{} {}'.format('The request subject is:',
                                           key_command))
        except:
            msg = '{} {}'.format('There\'s a problem with the', key_command)
            logging_handler(msg)
    return key_command, sender
示例#14
0
def set_gen_state(state, time_stamp):
    """"Sets generator state with a timestamp and adds an entry to the log"""
    if state:
        state_print = "up"
    else:
        state_print = "down"
    msg = '{} {}'.format('Setting state to:', state_print)
    success_msg = '{} {} {}'.format('Setting state to:', state_print, 'was successful')
    error_msg = '{} {} {}'.format('Setting state to:', state_print, 'was not successful')
    logging_handler(msg)
    try:
        db.generator_state.update_one({'_id':'gen_state'}, {"$set": {"state": state}}, upsert=True)
        db.generator_log.insert_one({"state": state_print, "time_stamp": time_stamp})
        logging_handler(success_msg)
    except (AttributeError, errors.OperationFailure):
        logging_handler(error_msg)
示例#15
0
文件: main.py 项目: pavelzag/RaspGen
def pic_command():
    """"Processes the Pic Command"""
    url = get_cam_url()
    try:
        r = requests.get(url)
        with open(image_file_path, 'wb') as fout:
            fout.write(r.content)
        logging_handler('{} {}'.format(image_file_path,
                                       'was saved successfully'))
        msg = '{} {}'.format('Sending pic to', from_address)
        logging_handler(msg)
        send_mail(send_to=from_address,
                  subject='Picture Message',
                  text='Pics attached',
                  file=image_file_path)
        delete_messages()

    except:
        logging_handler('Failed to retrieve the image')
        delete_messages()
示例#16
0
文件: app.py 项目: pavelzag/raspcam
import os
import platform
import socket
from logger import logging_handler
from configuration import get_owner
from bottle import Bottle, run, static_file, route, BaseRequest, template
from PIL import Image
from send_mail import send_mail
from GoogleOCR import detect_text

creds_path = os.path.join(os.getcwd(), "googlecreds.json")
owner = get_owner()
logging_handler(creds_path)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = creds_path
logging_handler(os.environ["GOOGLE_APPLICATION_CREDENTIALS"])
app = Bottle()
BaseRequest.MEMFILE_MAX = 1000000
image_file = "image.jpeg"
post_crop = "image_post_crop.jpeg"
local_envs = ['Darwin', 'fedora']
current_platform = platform.platform()
msg = '{} {}'.format('Current platform is:', current_platform)
logging_handler(msg)


def capture():
    import picamera
    camera = picamera.PiCamera()
    print('capturing the image')
    camera.capture(image_file, format='jpeg')
    camera.close()
示例#17
0
    # Calculates amount of Saturdays per relevant month
    return len([1 for i in calendar.monthcalendar(year, month) if i[6] != 0])


if __name__ == '__main__':
    # Looping through every month per tab
    for worksheet_tab in worksheet_list:
        worksheet_tab_title = worksheet_tab._title
        selected_worksheet = worksheet.worksheet(worksheet_tab_title)
        month_number = strptime(worksheet_tab_title, '%B').tm_mon
        start_date, end_date = get_start_date_and_end_date(year=2018,
                                                           month=month_number)
        for single_date in daterange(start_date, end_date):
            msg = '{} {}'.format('Acquiring time spent for',
                                 worksheet_tab_title)
            logging_handler(msg)
            time_spent = get_time_spent(single_date)
            msg = '{} {}'.format('Acquiring time spent for', single_date)
            logging_handler(msg)
            time_spent_dict[single_date] = time_spent
        first_sheet_number = 'B1'
        first_day_of_month = 1
        last_day_of_month = get_last_day(2018, month_number)
        last_sheet_number = '{}{}'.format('B', last_day_of_month + 1)
        saturdays_amt = get_saturdays_amt(year=start_date.year,
                                          month=start_date.month)
        cells_number = len(range(first_day_of_month,
                                 last_day_of_month)) + saturdays_amt + 1
        days_number = len(range(first_day_of_month, last_day_of_month))
        cell_num = 1
        day_num = 0
示例#18
0
import datetime
import requests
import time
from logger import logging_handler

url = 'https://generator-keep-alive.herokuapp.com:5000/keep_alive'


def get_current_time():
    ts = time.time()
    time_stamp = datetime.datetime.fromtimestamp(ts).strftime(
        '%Y-%m-%d %H:%M:%S')
    return time_stamp


def get_request(url):
    r = requests.get(url)
    return r.status_code


if __name__ == '__main__':
    status_code = get_request(url)
    if '200' in status_code:
        logging_handler('{} {}'.format('something', 'something else'))
示例#19
0
文件: main.py 项目: pavelzag/RaspGen
    send_mail(send_to=from_address, text=msg)
    delete_messages()


if __name__ == '__main__':
    ip_address = get_machine_ip()
    startup_msg = '{} {}'.format('Machine runs on', ip_address)
    print(startup_msg)
    logging.info(startup_msg)
    send_mail(send_to=owner, subject='Start up Message', text=startup_msg)
    set_initial_db_state()
    start_time = None
    while check_internet_connection():
        try:
            key_command, from_address = poll_mail()
            logging_handler('{} {}'.format('The key command is', key_command))
            if is_in_white_list(from_address):
                current_state = get_gen_state()
                logging_handler('{} {}'.format(from_address, white_list))
                if 'off' in key_command:
                    if get_gen_state() is not 'down':
                        off_command()
                    else:
                        logging_handler(already_down_msg)
                elif 'on' in key_command:
                    if get_gen_state() is not 'up':
                        current_time_stamp = get_current_time()
                        start_time = datetime.datetime.now()
                        if not any(char.isdigit() for char in key_command):
                            generator_cmd(cmd='on')
                            logging_handler(up_msg)
示例#20
0
文件: main.py 项目: pavelzag/RaspGen
def unknown_command():
    """"Processes the Unknown Command"""
    msg = '{} {}'.format(''.join(key_command), 'is an unknown command')
    logging_handler(msg)
    send_mail(send_to=from_address, text=msg)
    delete_messages()
示例#21
0
def get_request(url):
    r = requests.get(url)
    return r.status_code


if __name__ == '__main__':
    while 1 == 1:
        try:
            status_code = get_request(url)
            if status_code == 200:
                msg1 = '{} {}'.format('Keep alive success. Status code is',
                                      status_code)
                msg2 = '{} {} {}'.format('Going to sleep for', time_sleep,
                                         'seconds')
                logging_handler(msg1)
                logging_handler(msg2)
                time.sleep(time_sleep)
            else:
                msg1 = '{} {}'.format('Keep alive failure. Status code is',
                                      status_code)
                msg2 = '{} {} {}'.format('Going to sleep for', time_sleep,
                                         'seconds')
                logging_handler(msg1)
                logging_handler(msg2)
                time.sleep(time_sleep)
        except requests.ConnectionError as err:
            msg = '{} {}'.format('Request failure with the following error:',
                                 err.message.message)
            time.sleep(time_sleep)
            logging_handler(msg)
示例#22
0
mail_address = get_config('email')
mail_user = get_config('user')
mail_password = get_config('password')


def check_time_delta(keep_alive_ts):
    s2 = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    time_format = "%Y-%m-%d %H:%M:%S"
    return datetime.strptime(s2, time_format) - datetime.strptime(
        keep_alive_ts, time_format)


if __name__ == '__main__':
    msg = 'app is going up!'
    print(mail_address, mail_user, mail_password)
    logging_handler(msg)
    send_mail(send_to=owner,
              subject='Start up Message',
              text='Cloud checker app is going up')
    while 1 == 1:
        keep_alive_ts = get_keep_alive()['time_stamp']
        time_delta = check_time_delta(keep_alive_ts)
        logging_handler(str(time_delta))
        if time_delta > timedelta(minutes=keep_alive_threshold):
            failure = True
            msg = '{} {} {}'.format('No keep alive for over',
                                    keep_alive_threshold, 'minutes')
            logging_handler(msg)
            send_mail(send_to=owner, subject='Start up Message', text=msg)
            time.sleep(fail_sleep_time)
        else: