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: Speak('commit security check not passed') logger.error('commit security check not passed') return 'commit security check not passed' process = Popen('git pull'.split(' '), stdout=PIPE, stderr=PIPE, cwd=Dirs()['REPO']) reply = ' : '.join([str(i) for i in process.communicate() ]) logger.info(reply) if p.GIT_CI.report_speak: Speak('git pull done on the machine {}'.format(socket.gethostname())) if p.GIT_CI.report_pull_email: sent = sendMail([p.email.address], [p.email.address, p.email.login, p.email.password], 'CI - git pull from ' + socket.gethostname(), reply ,[]) logger.info(str(sent)) return reply except Exception as e: logger.error(e) return 'error ' + str(e)
def files_to_backup(config): files = [ i for i in [ config['FILENAME'], os.path.join(Dirs()['LOG'], 'crontab.txt'), '/home/pi/.bash_aliases', '/home/pi/.bashrc', '/home/pi/.profile', '/home/pi/git/config.ini', '/home/pi/pgpass.conf' ] if os.path.exists(i) ] return files
def Alert(distance): global alert_time, iss if distance <= alert_distance: if (datetime.datetime.now() - alert_time).seconds > 5 * 60 : alert_time = datetime.datetime.now() if alert_type == 'speak' and alert_time.hour > alert_time_window[0] and alert_time.hour < alert_time_window[1]: Speak("international space station approaching, distance is {0} kilometers".format(str(distance))) alert_message = '\t'.join([str(i) for i in [str(datetime.datetime.now()).split('.')[0], distance, iss.latitude, iss.longitude]]) print (alert_message, file=open(os.path.join(Dirs()['LOG'], 'iss_alert'),'a')) logger.info(alert_message) logger.info('sending email ... ' + sendMail([p.email.address], [p.email.address, p.email.login, p.email.password], 'ISS approaching alert ', alert_message ,[]))
def AcquireResult(allowed_delay_min=5): """using SSH, returns 1 / 0 / None if iphone is around (not directly pinging > only reading last logs) if more time passed than allowed_delay_min since last ping > returns None *too old log ** to be run from another device with SSH / RSA keys on it""" com = "tail -1 " + os.path.join(Dirs()['LOG'], 'log_ping_iPhone.txt') stdout, stderr = Popen(com.split(' '), stdout=PIPE, stderr=PIPE).communicate() if type(stdout) != str: stdout = stdout.decode( "utf-8") #for python3 > return is Byte like object #return LAST False / True return stdout.replace('\n', '').split('\t')[-1] != 'False'
def PhraseDict(): try: INI_file = open(os.path.join(Dirs()['DATA'], 'phrases.ini'), 'r').read().splitlines() except: return False INI_file = [i for i in INI_file if len(i) != 0] # empty strings INI_file = [i for i in INI_file if i[0] != '#'] param, GROUP = {}, '' for p_item in INI_file: if p_item.isupper(): GROUP = p_item.replace(' ', '') param[GROUP] = [] else: param[GROUP].append(p_item) return param
def dump_db(connection='hornet_pi_db'): config = getattr(CONFIGURATION(), connection).__dict__ config['FILENAME'] = os.path.join( Dirs()['LOG'], connection + '_dmp_' + str(datetime.datetime.now()).split(' ')[0].replace('-', '') + '.txt') cmd = "pg_dump -h {HOST} -p {PORT} -d {DB} -U {USER} -s -f {FILENAME}".format( **config) logger.info(cmd) os.system(cmd) #check file created dmp_check = 'dump file {} - {}'.format( config['FILENAME'], 'exists' if os.path.exists(config['FILENAME']) else 'NOT created!') logger.info(dmp_check) return (config, dmp_check)
def __init__(self, text, lang='en', store=True): self.text, self.lang, self.store = text, lang, store self.mp3 = os.path.join(Dirs()['SPEAK'], name_from_text(self.text) + '.mp3') #testing for zero file size if os.path.exists(self.mp3): if os.path.getsize(self.mp3) == 0: m.logger.info('file {} has ZERO size >> deleting'.format( self.mp3)) self.Del() if not os.path.exists( self.mp3): # no file > need to TRANSLATE and DOWNLOAD m.logger.debug('no file stored > need to download') if self.lang != 'en' and not self.Detect_Russian( ): # translate if need RU and text not RU self.translate() self.Get_GTTS() self.Speak() if not self.store: self.Del()
def NextFerry(): "reyturns the time of the next ferry. timetable lives in 'data' directory" data = Dirs()['DATA'] DAY = [ '' if datetime.datetime.today().weekday() < 5 else ['_SAT' if datetime.datetime.today().weekday() else '_SUN'][0] ][0] timetable = open(os.path.join(data, 'ferry' + DAY + '.txt'), 'r').read().split('\n') lst = [] for a in timetable: lst.append(datetime.time(int(a.split(':')[0]), int(a.split(':')[1]))) cut_off = datetime.datetime.now() + datetime.timedelta(minutes=5) nxt = [i for i in lst if i > datetime.time(cut_off.hour, cut_off.minute)] if nxt == []: return 'F--' else: min_to_next = (datetime.datetime.combine(datetime.date.today(), nxt[0]) - datetime.datetime.now()).seconds / 60 if min_to_next > 99: return 'F--' else: return 'F' + str(min_to_next).zfill(2)
def Sun(date, filename='sunrise2014.txt'): "gets the date, returns tuple with [sunrise,sunset,window_light,total_dark]" shift_hours = [6, 9] # for window light and sun has gone file_path = os.path.join(Dirs()['DATA'], filename) dates = open(file_path, 'r').read().split('\n')[1:] string = [ i for i in dates if int(i.split(' ')[0]) == date.month and int(i.split(' ')[1]) == date.day ][0] twilight = [ string.split(' ')[5], string.split(' ')[6], string.split(' ')[7] ] today = datetime.date.today() sunrise = datetime.datetime(today.year, today.month, today.day, int(twilight[0].split(':')[0]), int(twilight[0].split(':')[1]), 0) sunset = datetime.datetime(today.year, today.month, today.day, int(twilight[1].split(':')[0]), int(twilight[1].split(':')[1]), 0) window_light = datetime.datetime( today.year, today.month, today.day, int(twilight[0].split(':')[0]) + shift_hours[0], int(twilight[0].split(':')[1]), 0) total_dark = datetime.datetime(today.year, today.month, today.day, int(twilight[2].split(':')[0]), int(twilight[2].split(':')[1]), 0) sun_has_gone = datetime.datetime( today.year, today.month, today.day, int(twilight[0].split(':')[0]) + shift_hours[1], int(twilight[0].split(':')[1]), 0) dawn = datetime.datetime(today.year, today.month, today.day, int(string.split(' ')[4].split(':')[0]), int(string.split(' ')[4].split(':')[1]), 0) return [sunrise, sunset, window_light, total_dark, sun_has_gone, dawn]
def dump_crontab(file='/var/spool/cron/crontabs/pi'): cmd = 'sudo cat {} > {}'.format(file, os.path.join(Dirs()['LOG'], 'crontab.txt')) logger.info(cmd) os.system(cmd)
def Log(result): log = os.path.join(Dirs()['LOG'], 'log_ping_iPhone.txt') print(str(datetime.now()).split('.')[0] + '\t' + str(result), file=open(log, 'a'))