def Phrase(about): "Phrase({'TYPE' : 'type_from_phrases'})" global p if 'p' not in globals(): p = CONFIGURATION() if hasattr(p, 'SPEAK'): # if not in the config - skip checks if not p.SPEAK: return def PhraseDict(): try: INI_file = open(os.path.join(Dirs()['DATA'], 'phrases.ini'), 'r').read().splitlines() #TODO: fix path except: print("can't open phrases ini file") 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 try: options = PhraseDict()[about['TYPE']] choice = options[int(random.random() * len(options))] for k, v in [(a, b) for (a, b) in about.items() if a != 'TYPE']: choice = choice.replace('%' + k, v) Speak(choice) except: print('cant find phrase') return
def PingBT(MAC=CONFIGURATION().BT.MAC, BT_METHOD=CONFIGURATION().BT.METHOD): "BT_METHOD : self, ssh_shrimp [alike], bluetooth" # pairing https://www.cnet.com/how-to/how-to-setup-bluetooth-on-a-raspberry-pi-3/ com = "sudo l2ping -s 1 -c 1 -t 4 " + MAC #if socket.gethostname() != 'RaspPI': com.insert(0,'sudo') if BT_METHOD.lower() == 'self': com = com.split(' ') return RunCMD_BT(com) elif BT_METHOD.lower().startswith('ssh'): bt = BT_METHOD.lower().replace('ssh_', '') com = ('ssh -i /home/pi/.ssh/{} pi@{}.local '.format(bt, bt) + com).split(' ') return RunCMD_BT(com) elif BT_METHOD.lower() == 'bluetooth': start = datetime.now() result = bluetooth.lookup_name(MAC) is not None return [result, (datetime.now() - start).microseconds / 10 ] # status, milliseconds else: print('BT_METHOD not recognized') return [None, None]
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)
def Speak(text, device='octopus'): 'simple speaking function integration to use gTTS on another PI' global p if 'p' not in globals(): p = CONFIGURATION() for k, v in Substitutons(): text = text.replace('%' + k, v) keys = { 'octopus': '192.168.1.154:2227', 'hornet': '192.168.1.153:2226' } #TODO: hardcoding out os.system("ssh -p {} -i /home/pi/.ssh/{} pi@{} nohup sudo python /home/pi/PYTHON/GPIO/modules/talk.py '\"".\ format(keys[device].split(':')[1], device, keys[device].split(':')[0]) +text+"\"' &") return
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 Substitutons(): global p if 'p' not in globals(): p = CONFIGURATION() return { 'H': str(datetime.datetime.now().hour), 'M': str(datetime.datetime.now().minute), 'DT': [ t for (n, t) in enumerate( ['night', 'morning', 'day', 'evening', 'night']) if n == int(datetime.datetime.now().hour / 5) ][0], 'NAME': p.NAME }.items()
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}
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)