def write_song_queue(json_data): try: _dir = os.path.join(plugin_data_dir(), 'json') if not os.path.exists(_dir): os.makedirs(_dir) with open(os.path.join(plugin_data_dir(), 'json', 'song_queue.json'), 'w') as song_queue: json.dump(json_data, song_queue) except Exception: log.error(NAME, _(u'Voice Station plug-in') + ':\n' + traceback.format_exc())
def read_log(): """Read pcf log from json file.""" try: with open(os.path.join(plugin_data_dir(), 'log.json')) as logf: return json.load(logf) except IOError: return []
def GET(self): log_file = read_log() name1 = plugin_options['label_ds0'] name2 = plugin_options['label_ds1'] name3 = plugin_options['label_ds2'] name4 = plugin_options['label_ds3'] name5 = plugin_options['label_ds4'] name6 = plugin_options['label_ds5'] data = "Date/Time; Date; Time; DHT Temperature C; DHT Humidity %; DHT Output; " + name1 + "; " + name2 + "; " + name3 + "; " + name4 + "; " + name5 + "; " + name6 + "\n" for interval in log_file: data += '; '.join([ interval['datetime'], interval['date'], interval['time'], u'{}'.format(interval['temp']), u'{}'.format(interval['humi']), u'{}'.format(interval['outp']), u'{}'.format(interval['ds0']), u'{}'.format(interval['ds1']), u'{}'.format(interval['ds2']), u'{}'.format(interval['ds3']), u'{}'.format(interval['ds4']), u'{}'.format(interval['ds5']), ]) + '\n' content = mimetypes.guess_type( os.path.join(plugin_data_dir(), 'log.json')[0]) web.header('Access-Control-Allow-Origin', '*') web.header('Content-type', content) web.header('Content-Disposition', 'attachment; filename="log.csv"') return data
def GET(self): qdict = web.input() errorCode = qdict.get('errorCode', 'none') if 'delete' in qdict: delete = qdict['delete'] if len(plugin_options['sounds']) > 0: del_file = os.path.join(plugin_data_dir(), plugin_options['sounds'][int(delete)]) if os.path.isfile(del_file): os.remove(del_file) errorCode = qdict.get('errorCode', 'DelOK') read_folder() log.debug( NAME, datetime_string() + ': ' + _(u'Deleting file has sucesfully.')) else: errorCode = qdict.get('errorCode', 'DelNex') log.error( NAME, datetime_string() + ': ' + _(u'File for deleting not found!')) return self.plugin_render.voice_station_sounds(plugin_options, errorCode)
def GET(self): log_file = read_log() minimum = _(u'Minimum') maximum = _(u'Maximum') actual = _(u'Actual') volume = _(u'Volume') data = "Date/Time" data += "; Date" data += "; Time" data += "; %s cm" % minimum data += "; %s cm" % maximum data += "; %s cm" % actual if tank_options['check_liters']: data += "; %s liters" % volume else: data += "; %s m3" % volume data += '\n' for interval in log_file: data += '; '.join([ interval['datetime'], interval['date'], interval['time'], u'{}'.format(interval['minimum']), u'{}'.format(interval['maximum']), u'{}'.format(interval['actual']), u'{}'.format(interval['volume']), ]) + '\n' content = mimetypes.guess_type( os.path.join(plugin_data_dir(), 'log.json')[0]) web.header('Access-Control-Allow-Origin', '*') web.header('Content-type', content) web.header('Content-Disposition', 'attachment; filename="log.csv"') return data
def GET(self): global must_stop qdict = web.input() if checker is not None: stop = helpers.get_input(qdict, 'stop', False, lambda x: True) clear = helpers.get_input(qdict, 'clear', False, lambda x: True) if 'test' in qdict: command = -1 data = {} if 'state' in qdict and int(qdict['state']) == 1: command = plugin_options['on'][int(qdict['test'])] if 'state' in qdict and int(qdict['state']) == 0: command = plugin_options['off'][int(qdict['test'])] if len(plugin_options['sounds']) > 0 and command != -1: data['song'] = plugin_options['sounds'][command] path = os.path.join(plugin_data_dir(), data['song']) if os.path.isfile(path): log.info( NAME, datetime_string() + u': ' + _(u'Button test, song {}.').format(data['song'])) update_song_queue(data) # save song name to song queue else: log.info( NAME, datetime_string() + u': ' + _(u'File not exists!')) else: log.info( NAME, datetime_string() + u': ' + _(u'File not exists!')) if stop: must_stop = True log.info(NAME, datetime_string() + u': ' + _(u'Button Stop.')) if clear: must_stop = True song_queue = read_song_queue() while len(song_queue) > 0: song_queue = read_song_queue() del song_queue[0] write_song_queue(song_queue) log.clear(NAME) log.info( NAME, datetime_string() + u': ' + _(u'Button clear playlist.')) try: return self.plugin_render.voice_station(plugin_options, log.events(NAME)) except Exception: log.error( NAME, _(u'Voice Station plug-in') + ':\n' + traceback.format_exc()) set_to_default() return self.plugin_render.voice_station(plugin_options, log.events(NAME))
def GET(self): log_file = read_debug_log() data = "Date/Time" data += "; Byte 0" data += "; Byte 1" data += "; Value" data += "; Byte 2 FW" data += "; Byte 3 CRC" data += '\n' for interval in log_file: data += '; '.join([ interval['datetime'], u'{}'.format(interval['b0']), u'{}'.format(interval['b1']), u'{}'.format(interval['val']), u'{}'.format(interval['b2']), u'{}'.format(interval['b3']), ]) + '\n' content = mimetypes.guess_type( os.path.join(plugin_data_dir(), 'debug_log.json')[0]) web.header('Access-Control-Allow-Origin', '*') web.header('Content-type', content) web.header('Content-Disposition', 'attachment; filename="tank_i2c_debug_log.csv"') return data
def notify_station_off(name, **kw): if plugin_options['enabled']: current_time = datetime.datetime.now() try: if int(current_time.hour) >= int( plugin_options['start_hour']) and int( current_time.hour) <= int(plugin_options['stop_hour']): st_nr = int(kw[u"txt"]) log.clear(NAME) log.info( NAME, datetime_string() + u': ' + _(u'Stations {} OFF').format(str(st_nr + 1))) data = {} if len(plugin_options['sounds']) > 0: data['song'] = plugin_options['sounds'][int( plugin_options['off'][st_nr])] path = os.path.join(plugin_data_dir(), data['song']) if os.path.isfile(path): update_song_queue(data) # save song name to song queue else: log.info( NAME, datetime_string() + u': ' + _(u'File not exists!')) except Exception: log.error( NAME, _(u'Voice Station plug-in') + ':\n' + traceback.format_exc())
def read_song_queue(): try: with open(os.path.join(plugin_data_dir(), 'json', 'song_queue.json')) as song_queue: return json.load(song_queue) except IOError: return []
def GET(self): log_file = read_log() maximum = _(u'Maximum') actual = _(u'Actual') data = "Date/Time; Date; Time" if wind_options['use_kmh']: data += "; %s km/h" % maximum data += "; %s km/h" % actual else: data += "; %s m/sec" % maximum data += "; %s m/sec" % actual data += '\n' for interval in log_file: data += '; '.join([ interval['datetime'], interval['date'], interval['time'], u'{}'.format(interval['maximum']), u'{}'.format(interval['actual']), ]) + '\n' content = mimetypes.guess_type( os.path.join(plugin_data_dir(), 'log.json')[0]) web.header('Access-Control-Allow-Origin', '*') web.header('Content-type', content) web.header('Content-Disposition', 'attachment; filename="log.csv"') return data
def GET(self): log_file = read_log() down = _(u'Downloading') up = _(u'Uploading') ping = _(u'Ping Time') data = "Date/Time" data += "; Date" data += "; Time" data += "; %s (Mb/s)" % down data += "; %s (Mb/s)" % up data += "; %s (msec)" % ping data += '\n' for interval in log_file: data += '; '.join([ interval['datetime'], interval['date'], interval['time'], u'{}'.format(interval['down']), u'{}'.format(interval['up']), u'{}'.format(interval['ping']), ]) + '\n' content = mimetypes.guess_type( os.path.join(plugin_data_dir(), 'log.json')[0]) web.header('Access-Control-Allow-Origin', '*') web.header('Content-type', content) web.header('Content-Disposition', 'attachment; filename="log.csv"') return data
def read_saved_emails(): ### Read saved emails from json file ### try: with open(os.path.join(plugin_data_dir(), 'saved_emails.json')) as saved_emails: return json.load(saved_emails) except IOError: return []
def update_song_queue(data): try: # exists file: saved_song_queue.json? song_queue = read_song_queue() except: # no! create empty file _dir = os.path.join(plugin_data_dir(), 'json') if not os.path.exists(_dir): os.makedirs(_dir) write_song_queue([]) song_queue = read_song_queue() song_queue.insert(0, data) write_song_queue(song_queue)
def GET(self): data = "Date/Time; Command; State \n" log_file = read_log() for interval in log_file: data += '; '.join([ interval['datetime'], u'{}'.format(interval['cmd']), u'{}'.format(interval['status']), ]) + '\n' content = mimetypes.guess_type( os.path.join(plugin_data_dir(), 'log.json')[0]) web.header('Access-Control-Allow-Origin', '*') web.header('Content-type', content) web.header('Content-Disposition', 'attachment; filename="log.csv"') return data
def POST(self): qdict = web.input(myfile={}) errorCode = qdict.get('errorCode', 'none') #web.debug(qdict['myfile'].filename) # This is the filename #web.debug(qdict['myfile'].value) # This is the file contents #web.debug(qdict['myfile'].file.read()) # Or use a file(-like) object try: fname = qdict['myfile'].filename upload_type = fname[-4:len(fname)] types = ['.mp3', '.wav'] if upload_type not in types: # check file type is ok log.info( NAME, datetime_string() + ': ' + _(u'Error. File must be in mp3 or wav format!')) errorCode = qdict.get('errorCode', 'Etype') return self.plugin_render.voice_station_sounds( plugin_options, errorCode) else: fout = open(os.path.join(plugin_data_dir(), fname), 'wb') # ASCI_convert(fname) fout.write(qdict['myfile'].file.read()) fout.close() log.info( NAME, datetime_string() + ': ' + _(u'Uploading file sucesfully.')) errorCode = qdict.get('errorCode', 'UplOK') read_folder() return self.plugin_render.voice_station_sounds( plugin_options, errorCode) except Exception: log.error( NAME, _(u'Voice Station plug-in') + ':\n' + traceback.format_exc()) errorCode = qdict.get('errorCode', 'Eupl') return self.plugin_render.voice_station_sounds( plugin_options, errorCode) raise web.seeother(plugin_url(sound_page), True)
def read_folder(): try: import os import time dir_name = plugin_data_dir() + '/' # Get list of all files only in the given directory list_of_files = filter( lambda x: os.path.isfile(os.path.join(dir_name, x)), os.listdir(dir_name)) # Sort list of files based on last modification time in ascending order list_of_files = sorted( list_of_files, key=lambda x: os.path.getmtime(os.path.join(dir_name, x))) # Along with last modification time of file e = [] f = [] g = [] for file_name in list_of_files: file_path = os.path.join(dir_name, file_name) timestamp_str = time.strftime( '%d/%m/%Y - %H:%M:%S', time.gmtime(os.path.getmtime(file_path))) size = os.path.getsize(file_path) e.append(timestamp_str) f.append(file_name) g.append(round(size, 2)) plugin_options.__setitem__('sounds_inserted', e) plugin_options.__setitem__('sounds', f) plugin_options.__setitem__('sounds_size', g) except Exception: log.error( NAME, _(u'Voice Notification plug-in') + ':\n' + traceback.format_exc())
def write_graph_log(json_data): """Write data to graph json file.""" with open(os.path.join(plugin_data_dir(), 'graph.json'), 'w') as outfile: json.dump(json_data, outfile)
def get_image_location(): return os.path.join(plugin_data_dir(), 'image.jpg')
def write_debug_log(json_data): """Write data to debug log json file.""" with open(os.path.join(plugin_data_dir(), 'debug_log.json'), 'w') as outfile: json.dump(json_data, outfile)
def play_voice(): global must_stop try: from pygame import mixer try: # exists file: song_queue.json? song_queue = read_song_queue() # read from file except: # no! create empty file write_song_queue([]) # create file song_queue = read_song_queue() # read from file song = '' if len(song_queue) > 0: # if there is something in json song = song_queue[0]['song'] path = os.path.join(plugin_data_dir(), song) mixer.init() if os.path.isfile(path): if mixer.music.get_busy() == False: log.info( NAME, datetime_string() + u': ' + _(u'Songs in queue {}').format(len(song_queue))) for i in range(0, len(song_queue)): log.info( NAME, _(u'Nr. {} -> {}').format(str(i + 1), song_queue[i]['song'])) log.info( NAME, datetime_string() + u': ' + _(u'Loading: {}').format(song)) mixer.music.load(path) mixer.music.set_volume(1.0) # 0.0 min to 1.0 max log.info( NAME, datetime_string() + u': ' + _(u'Set master volume to {}%').format( str(plugin_options['volume']))) try: cmd = [ "amixer", "sset", "PCM,0", "{}%".format(plugin_options['volume']) ] run_command(cmd) except: cmd = [ "amixer", "sset", "Master", "{}%".format(plugin_options['volume']) ] run_command(cmd) mixer.music.play() log.info(NAME, datetime_string() + u': ' + _(u'Playing.')) else: del song_queue[0] write_song_queue(song_queue) while mixer.music.get_busy() == True and not must_stop: continue mixer.music.stop() log.info(NAME, datetime_string() + u': ' + _(u'Stopping.')) del song_queue[0] # delete song queue in file write_song_queue(song_queue) # save to file after deleting an item must_stop = False except Exception: log.error(NAME, _(u'Voice Station plug-in') + ':\n' + traceback.format_exc())
def run(self): log.clear(NAME) if not plugin_options['enabled']: log.info(NAME, _(u'Voice notification is disabled.')) else: log.info(NAME, _(u'Voice notification is enabled.')) read_folder( ) # read name from file in data folder and add to plugin_options "sound" once_test = True # for test installing pygame is_installed = True # if pygame is installed last_station_on = -1 while not self._stop_event.is_set(): try: if plugin_options['enabled']: # plugin is enabled try: from pygame import mixer # https://www.pygame.org/docs/ref/music.html except ImportError: if once_test: # only once instalation log.clear(NAME) log.info(NAME, _(u'Pygame is not installed.')) log.info(NAME, _(u'Please wait installing pygame...')) cmd = "sudo apt-get install python-pygame -y" run_command(cmd) once_test = False log.info(NAME, _(u'Pygame is now installed.')) is_installed = False current_time = datetime.datetime.now() user_pre_time = current_time + datetime.timedelta( seconds=int(plugin_options['pre_time'])) check_start = current_time - datetime.timedelta(days=1) check_end = current_time + datetime.timedelta(days=1) if int(current_time.hour) >= int( plugin_options['start_hour'] ) and int(current_time.hour) <= int( plugin_options['stop_hour'] ) and is_installed: # play notifications only from xx hour to yy hour schedule = predicted_schedule(check_start, check_end) for entry in schedule: if entry['start'] <= user_pre_time < entry[ 'end']: # is possible program in this interval? if not entry['blocked']: for station_num in plugin_options[ 'skip_stations']: if entry[ 'station'] == station_num: # station skiping log.clear(NAME) log.info( NAME, _(u'Skiping playing on station' ) + ': ' + str(entry['station'] + 1) + '.') self._sleep(1) return # not playing skipping rain = not options.manual_mode and ( rain_blocks.block_end() > datetime.datetime.now() or inputs.rain_sensed()) ignore_rain = stations.get( entry['station']).ignore_rain if not rain or ignore_rain: # if station has ignore rain or not rain stat_num = int(entry['station']) if len(plugin_options['sounds']) > 0: log.clear(NAME) data = {} data['song'] = plugin_options[ 'sounds'][int( plugin_options['on'] [stat_num])] path = os.path.join( plugin_data_dir(), data['song']) if os.path.isfile(path): if last_station_on != stat_num: last_station_on = stat_num log.info( NAME, _(u'Add song {} to queue.' ).format( data['song'])) update_song_queue( data ) # save song name to song queue if plugin_options[ 'repeating'] == 2 or plugin_options[ 'repeating'] == 3: log.info( NAME, _(u'Add 2. repeating for song.' )) song_queue = read_song_queue( ) song_queue.insert( 1, data) write_song_queue( song_queue) if plugin_options[ 'repeating'] == 3: log.info( NAME, _(u'Add 3. repeating for song.' )) song_queue = read_song_queue( ) song_queue.insert( 2, data) write_song_queue( song_queue) if is_installed: play_voice() self._sleep(1) except Exception: log.error( NAME, _(u'Voice Notification plug-in') + ':\n' + traceback.format_exc()) self._sleep(60)
def write_email(json_data): ###Write e-mail data to json file ### with open(os.path.join(plugin_data_dir(), 'saved_emails.json'), 'w') as saved_emails: json.dump(json_data, saved_emails)
def write_log(json_data): """Write json to log file.""" with open(os.path.join(plugin_data_dir(), 'log.json'), 'w') as outfile: json.dump(json_data, outfile)