def get_first_active_mpd(): port_config = get_param(Constant.P_MPD_PORT_ZONE).split(',') first_port = None alt_port = None alt_zone = None client = _get_client() # get the zone playing, only if one is active port_list_play = [] for pair in port_config: port_val = int(pair.split('=')[1]) if first_port is None: first_port = port_val zone_val = pair.split('=')[0] client.connect(get_param(Constant.P_MPD_SERVER), port_val) if client.status()['state'] == 'play': port_list_play.append(port_val) alt_zone = zone_val client.close() client.disconnect() if len(port_list_play) == 1: alt_port = port_list_play[0] zone = alt_zone if alt_port is not None: client.connect(get_param(Constant.P_MPD_SERVER), alt_port) return client else: client.connect(get_param(Constant.P_MPD_SERVER), first_port) return client
def init(): L.l.info('Openhab module initialising') rules.P.openhab_topic = str(model_helper.get_param(Constant.P_MQTT_TOPIC_OPENHAB_SEND)) P.mqtt_topic_receive = str(model_helper.get_param(Constant.P_MQTT_TOPIC_OPENHAB_RECEIVE)) P.mqtt_topic_receive_prefix = P.mqtt_topic_receive.replace('#', '') mqtt_io.P.mqtt_client.message_callback_add(P.mqtt_topic_receive, mqtt_on_message) __load_rules() thread_pool.add_interval_callable(thread_run, run_interval_second=1) dispatcher.connect(parse_rules, signal=Constant.SIGNAL_DB_CHANGE_FOR_RULES, sender=dispatcher.Any) P.initialised = True
def connect_socket(): host = get_param(Constant.P_AMP_SERIAL_HOST) port = int(get_param(Constant.P_AMP_SERIAL_PORT)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) L.l.debug("Connecting socket") s.settimeout(2) s.connect((host, port)) s.settimeout(None) L.l.debug("Connected socket") return s
def init(): L.l.debug('Email module initialising') dispatcher.connect(send_notification, signal=Constant.SIGNAL_EMAIL_NOTIFICATION, sender=dispatcher.Any) global __notif_from, __notif_pass, __notif_dest __notif_from = model_helper.get_param(Constant.P_GMAIL_NOTIFY_FROM_EMAIL) __notif_dest = model_helper.get_param(Constant.P_NOTIFY_EMAIL_RECIPIENT) __notif_pass = _get_pass(__notif_from) #if send_notification("Starting haiot", "Host is {}".format(Constant.HOST_NAME)): # Log.logger.info("Init email sent OK") global initialised initialised = True
def __init__(self, listener, pooller, port, index, root_url, server_version, persistent_uuid, other_headers=None, ip_address=None): self.listener = listener self.poller = pooller self.port = port self.root_url = root_url self.server_version = server_version self.persistent_uuid = persistent_uuid self.uuid = uuid.uuid4() self.other_headers = other_headers if ip_address: self.ip_address = ip_address else: self.ip_address = upnp_device.local_ip_address() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.port == 0: self.port = (int)(get_param( Constant.P_ALEXA_WEMO_LISTEN_PORT)) + index #self.port = self.socket.getsockname()[1] self.socket.bind((self.ip_address, self.port)) self.socket.listen(5) self.poller.add(self) self.client_sockets = {} self.listener.add_device(self)
def _init_comm(): ohost = "none" oport = "none" try: ohost = model_helper.get_param(Constant.P_OWSERVER_HOST_1) oport = str(model_helper.get_param(Constant.P_OWSERVER_PORT_1)) _get_bus_list(ohost, oport) P.initialised = True P.warning_issued = False except Exception as ex: if not P.warning_issued: L.l.info( '1-wire owserver not initialised on host {} port {}, ex={}'. format(ohost, oport, ex)) P.initialised = False P.warning_issued = True return P.initialised
def thread_run(): prctl.set_name("heat") threading.current_thread().name = "heat" global progress_status L.l.debug('Processing heat') progress_status = 'Looping zones' if P.threshold is None: P.threshold = float(get_param(Constant.P_TEMPERATURE_THRESHOLD)) P.temp_limit = float(get_param(Constant.P_HEAT_SOURCE_MIN_TEMP)) P.MAX_DELTA_TEMP_KEEP_WARM = float( get_param(Constant.P_MAX_DELTA_TEMP_KEEP_WARM)) set_main_heat_source() loop_zones() # loop_heat_relay() prctl.set_name("idle") threading.current_thread().name = "idle" return 'Heat ok'
def init(): L.l.debug('Hipchat module initialising') dispatcher.connect(hipchat_notify, signal=Constant.SIGNAL_CHAT_NOTIFICATION, sender=dispatcher.Any) global _token, _room _token = model_helper.get_param(Constant.P_HIPCHAT_TOKEN) _room = model_helper.get_param(Constant.P_HIPCHAT_ROOM_API_ID) try: pass # hipchat_notify(message='Module initialising', notify=True, color='red') # send_message(title="Initialised", message="Module initialised") # send_message(title="Initialised 2", message="Module initialised 2") except Exception as ex: L.l.error("Unable tp init hipchat %s" % ex) # thread_pool.add_interval_callable(_send_queue, run_interval_second=60) global initialised initialised = True
def loop_zones(): try: heat_is_on = False zone_list = models.Zone().query_all() global progress_status for zone in zone_list: progress_status = 'do zone {}'.format(zone.name) heat_schedule = models.HeatSchedule.query.filter_by( zone_id=zone.id).first() zonesensor_list = models.ZoneSensor.query.filter_by( zone_id=zone.id).all() for zonesensor in zonesensor_list: if heat_schedule is not None and zonesensor is not None: sensor = models.Sensor.query.filter_by( address=zonesensor.sensor_address).first() if heat_schedule.active and sensor is not None: # sensor_last_update_seconds = (utils.get_base_location_now_date() - sensor.updated_on).total_seconds() # if sensor_last_update_seconds > 120 * 60: # Log.logger.warning('Sensor {} not updated in last 120 minutes, unusual'.format( # sensor.sensor_name)) heat_state, main_source_needed = __update_zone_heat( zone, heat_schedule, sensor) if not heat_is_on: heat_is_on = main_source_needed and heat_state # turn on/off the main heating system based on zone heat needs # check first to find alternate valid heat sources heatrelay_main_source = models.ZoneHeatRelay.query.filter_by( is_alternate_heat_source=1).first() if heatrelay_main_source is None: heatrelay_main_source = models.ZoneHeatRelay.query.filter_by( is_main_heat_source=1).first() if heatrelay_main_source is not None: L.l.info("Main heat relay={}".format(heatrelay_main_source)) main_source_zone = models.Zone.query.filter_by( id=heatrelay_main_source.zone_id).first() if main_source_zone is not None: update_age_mins = ( utils.get_base_location_now_date() - P.last_main_heat_update).total_seconds() / 60 # # avoid setting relay state too often but do periodic refreshes every x minutes if main_source_zone.heat_is_on != heat_is_on or update_age_mins >= int( get_param(Constant.P_HEAT_STATE_REFRESH_PERIOD)): L.l.info("Setting main heat on={}, zone={}".format( heat_is_on, main_source_zone)) __save_heat_state_db(zone=main_source_zone, heat_is_on=heat_is_on) P.last_main_heat_update = utils.get_base_location_now_date( ) else: L.l.critical('No heat main_src found using zone id {}'.format( heatrelay_main_source.zone_id)) else: L.l.critical('No heat main source is defined in db') except Exception as ex: L.l.error('Error loop_zones, err={}'.format(ex, exc_info=True))
def _get_pass(email=None): config_file = model_helper.get_param(Constant.P_GMAIL_CREDENTIAL_FILE) try: with open(config_file, 'r') as f: config_list = json.load(f) if email in config_list.keys(): record = config_list[email] return record['password'] except Exception, ex: L.l.warning( "Could not read credential email file {}".format(config_file))
def init_solar_aps(): try: production = utils.parse_http( model_helper.get_param(Constant.P_SOLAR_APS_LOCAL_URL), P.start_keyword, P.end_keyword) if production is not None and production is not '': P.initialised = True else: P.initialised = False return P.initialised except Exception as ex: L.l.warning("Unable to connect to aps solar server, ex={}".format(ex))
def init(): global initialised, __CLIENT_SECRETS_FILE, __youtube try: __CLIENT_SECRETS_FILE = utils.get_app_root_path() + model_helper.get_param(Constant.P_YOUTUBE_CREDENTIAL_FILE) L.l.info('Initialising youtube with credential from {}'.format(__CLIENT_SECRETS_FILE)) __youtube = get_authenticated_service([]) dispatcher.connect(file_watcher_event, signal=Constant.SIGNAL_FILE_WATCH, sender=dispatcher.Any) thread_pool.add_interval_callable(thread_run, run_interval_second=10) initialised = True # upload_file('c:\\temp\\01-20150512215655-alert.avi') except Exception as ex: L.l.warning('Unable to initialise youtube uploader, err={}'.format(ex))
def __read_hddparm(disk_dev=''): output = cStringIO.StringIO() hddparm_out = "None" global ERR_TEXT_NO_DEV try: if import_module_psutil_exist: try: use_sudo = bool( model_helper.get_param(Constant.P_USESUDO_DISKTOOLS)) if Constant.OS in Constant.OS_LINUX and use_sudo: hddparm_out = subprocess.check_output( ['sudo', 'hdparm', '-C', disk_dev], stderr=subprocess.STDOUT) else: hddparm_out = subprocess.check_output( ['hdparm', '-C', disk_dev], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as ex1: hddparm_out = ex1.output if ERR_TEXT_NO_DEV in hddparm_out or ERR_TEXT_NO_DEV_2 in hddparm_out: raise ex1 except Exception as ex: L.l.warning("Error running process, err={}".format(ex)) hddparm_out = None if hddparm_out: output.reset() output.write(hddparm_out) output.seek(0) pos = -1 while pos != output.tell(): pos = output.tell() line = output.readline() if Constant.HDPARM_STATUS in line: words = line.split(': ') power_status = words[1].replace('\r', '').replace( '\n', '').replace('/', '-').lstrip() if power_status == 'active-idle': power_status = 1 + Constant.HOST_PRIORITY elif power_status == 'standby': power_status = 0 else: power_status = -1 - Constant.HOST_PRIORITY return power_status else: power_status = 'not available' return power_status except subprocess.CalledProcessError as ex: L.l.debug('Invalid disk {} err {}'.format(disk_dev, ex)) except Exception as exc: L.l.exception('Disk read error disk was {} err {}'.format( disk_dev, exc)) raise subprocess.CalledProcessError( 1, 'No power status obtained on hdparm, output={}'.format(hddparm_out))
def init(): L.l.debug('Newtifry module initialising') global _source_key _source_key = model_helper.get_param(Constant.P_NEWTIFY_KEY) dispatcher.connect(send_message, signal=Constant.SIGNAL_PUSH_NOTIFICATION, sender=dispatcher.Any) # send_message(title="Initialising", message="Module initialising", priority=1) # send_message(title="Initialised", message="Module initialised") # send_message(title="Initialised 2", message="Module initialised 2") thread_pool.add_interval_callable(_send_queue, run_interval_second=60) global initialised initialised = True
def get_song_id(artist, title): url = get_param(Constant.P_GMUSICPROXY_URL) title = urllib.quote(title.encode('utf-8'), safe='') artist = urllib.quote(artist.encode('utf-8'), safe='') param = '/search_id?type=song&title={}&artist={}&exact=yes'.format(title, artist) try: result = requests.get('{}{}'.format(url, param), timeout=7).text if result == '': return None else: return result except Exception, ex: L.l.critical("Error on get song from google proxy: {}".format(ex)) return None
def _read_port_config(): port_config = get_param(Constant.P_MPD_PORT_ZONE).split(',') for pair in port_config: split = pair.split('=') names = split[0] port = split[1] if ':' in names: name_list = names.split(':') for name in name_list: P.zone_port[name] = int(port) P.unique_ports[int(port)] = name else: P.zone_port[names] = int(port) P.unique_ports[int(port)] = names
def init(): config_file = get_param(Constant.P_LASTFM_CONFIG_FILE) with open(config_file, 'r') as f: config_list = json.load(f) global _network, USERNAME API_KEY = config_list['lastfm_api'] API_SECRET = config_list['lastfm_secret'] USERNAME = config_list['lastfm_user'] PASSWORD = config_list['lastfm_pass'] # In order to perform a write operation you need to authenticate yourself password_hash = pylast.md5(PASSWORD) _network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=USERNAME, password_hash=password_hash)
def init(): global __observer, initialised, __inotify_import_ok if __inotify_import_ok: path = model_helper.get_param(Constant.P_MOTION_VIDEO_PATH) L.l.info('Initialising file watchdog for folder={}'.format(path)) if os.path.exists(path): event_handler = EventHandler() __observer = Observer() __observer.schedule(event_handler, path, recursive=True) initialised = True __observer.start() else: L.l.warning( 'Filewatch not initialised watch path={} not found'.format( path)) else: L.l.info( 'Inotify observer not available, not initialising file watch')
def init(): L.l.debug('WebUI module initialising') # thread_pool.add_callable(webui.thread_run, run_interval_second=60) from crud import admin, user crud.init_crud() app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(user, url_prefix='/user') global initialised, flask_thread if BIND_IP is not None and BIND_PORT is not None: host = BIND_IP port = BIND_PORT else: # otherwise listen on all interfaces host = '0.0.0.0' port = int(model_helper.get_param(Constant.P_FLASK_WEB_PORT)) app.wsgi_app = ReverseProxied(app.wsgi_app) app.config['STATIC_FOLDER'] = os.path.join(os.path.dirname(__file__), 'static') flask_thread = helpers.FlaskInThread(app, host=host, port=port, debug=True, use_reloader=False) initialised = True flask_thread.start() from webui.api import api_v1
def init(): # use auto setup as described here: https://plot.ly/python/getting-started/ to avoid passwords in code # or less secure sign_in code below # py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME),model_helper.get_param(constant.P_PLOTLY_APIKEY)) username = "" if py.get_credentials()['username'] == '' or py.get_credentials()['api_key'] == '': env_var = 'PLOTLY_CREDENTIALS_PATH' alt_path = os.environ.get(env_var) if not alt_path: L.l.info('Plotly config not in environment var: {}'.format(env_var)) env_var = 'OPENSHIFT_REPO_DIR' alt_path = os.environ.get(env_var) if alt_path is None: L.l.info('Plotly config not in environment var: {}'.format(env_var)) credential_file = model_helper.get_param(Constant.P_PLOTLY_ALTERNATE_CONFIG) alt_path = os.getcwd() + '/' + credential_file else: L.l.info('Plotly config found in environment var: {}, path={}'.format(env_var, alt_path)) alt_path = str(alt_path) + '/../data/.plotly.credentials' L.l.info("Plotly standard config empty, trying alt_path={}".format(alt_path)) try: with open(alt_path, 'r') as cred_file: data = cred_file.read().replace('\n', '') if len(data) > 0: cred_obj = utils.json2obj(data) username = cred_obj['username'] api_key = cred_obj['api_key'] if username and api_key: py.sign_in(username, api_key) global initialised initialised = True # else: # Log.logger.info("Plotly init from db folder config {}{} not ok, trying with db data".format(os.getcwd(), # credential_file)) # #alternate way if reading data from DB # py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME), # model_helper.get_param(constant.P_PLOTLY_APIKEY)) except Exception, ex: L.l.warning("error reading plotly credentials {}".format(ex))
def thread_run(): if not P.initialised: init_solar_aps() if P.initialised: try: production = utils.parse_http( model_helper.get_param(Constant.P_SOLAR_APS_LOCAL_URL), P.start_keyword, P.end_keyword) last_power = utils.parse_http( model_helper.get_param(Constant.P_SOLAR_APS_LOCAL_URL), P.start_keyword_now, P.end_keyword_now) temperature = utils.parse_http(model_helper.get_param( Constant.P_SOLAR_APS_LOCAL_REALTIME_URL), P.start_key_temp, P.end_key_temp, end_first=True) panel_id = utils.parse_http(model_helper.get_param( Constant.P_SOLAR_APS_LOCAL_REALTIME_URL), P.start_key_panel, P.end_key_panel, end_first=True) utility_name = model_helper.get_param( Constant.P_SOLAR_UTILITY_NAME) if temperature is not None: zone_sensor = models.ZoneSensor.query.filter_by( sensor_address=panel_id).first() if zone_sensor is None: L.l.warning( 'Solar panel id {} is not defined in zone sensor list'. format(panel_id)) record = models.Sensor(address=panel_id) current_record = models.Sensor.query.filter_by( address=panel_id).first() record.type = 'solar' if current_record is not None: record.sensor_name = current_record.sensor_name else: if zone_sensor: record.sensor_name = zone_sensor.sensor_name else: record.sensor_name = record.type + panel_id record.temperature = temperature record.updated_on = utils.get_base_location_now_date() # fixme: keeps saving same temp even when panels are off. stop during night. record.save_changed_fields(current_record=current_record, new_record=record, notify_transport_enabled=True, save_to_graph=True, debug=False) if production is not None: production = float(production) record = models.Utility() record.utility_name = utility_name current_record = models.Utility.query.filter_by( utility_name=utility_name).first() if current_record is not None: if current_record.units_total is None: record.units_delta = 0 else: record.units_delta = production - current_record.units_total if record.units_delta == 0: # do not waste db space if no power generated return record.units_total = production record.unit_name = current_record.unit_name record.units_2_delta = last_power record.unit_2_name = current_record.unit_2_name else: record.units_delta = production record.units_total = production if current_record.unit_cost is None: current_record.unit_cost = 0.0 record.cost = 1.0 * record.units_delta * current_record.unit_cost record.save_changed_fields(current_record=current_record, new_record=record, debug=False, notify_transport_enabled=True, save_to_graph=True, save_all_fields=False) except Exception as ex: L.l.warning("Got exception on solar thread run, ex={}".format(ex))
def __update_ddns_rackspace(): try: ConfigFile = model_helper.get_param(Constant.P_DDNS_RACKSPACE_CONFIG_FILE) with open(ConfigFile, 'r') as f: config_list = json.load(f) global cache if cache == {} or cache is None: cache = {} cache['auth'] = {} cache['auth']['expires'] = str(utils.get_base_location_now_date()) config = {} ip_json_test = '' try: #ip_json_test = requests.get('http://ip-api.com/json').text ip_json_test = requests.get('http://ipinfo.io').text ip_json_obj = utils.json2obj(ip_json_test) #public_ip = ip_json_obj['query'] #public_isp = ip_json_obj['isp'] public_ip = ip_json_obj['ip'] public_isp = ip_json_obj['org'] except Exception as ex: L.l.warning('Unable to get my ip, err={} text={}'.format(ex, ip_json_test)) return for config in config_list.values(): # check if public address is for this config dns entry isp = config['isp'] if isp != public_isp: continue # get IP address try: cache['ip:'+isp] = socket.gethostbyname(config['record_name']) except Exception as ex: cache['ip:'+isp] = None L.l.warning('Unable to get ip for host {}, err={}'.format(config['record_name'], ex)) if public_ip == '' or public_ip is None or public_ip == cache['ip:'+isp]: L.l.debug('IP address for ' + isp + ' is still ' + public_ip + '; nothing to update.') return else: L.l.info('IP address was changed for {}, old was {} new is {}'.format( isp, cache['ip:'+isp], public_ip)) cache['ip:'+isp] = public_ip now = utils.get_base_location_now_date() expires = dateutil.parser.parse(cache['auth']['expires']) now = pytz.utc.localize(now) expires = pytz.utc.localize(expires) if expires <= now: L.l.info('Expired rackspace authentication token; reauthenticating...') # authenticate with Rackspace authUrl = 'https://identity.api.rackspacecloud.com/v2.0/tokens' authData = {'auth': {'RAX-KSKEY:apiKeyCredentials': {'username': config['username'], 'apiKey': config['api_key']}}} authHeaders = {'Accept': 'application/json','Content-type': 'application/json'} auth = requests.post(authUrl, data=json.dumps(authData), headers=authHeaders) auth = utils.json2obj(auth.text) cache['auth']['expires'] = auth['access']['token']['expires'] cache['auth']['token'] = auth['access']['token']['id'] # update DNS record url = 'https://dns.api.rackspacecloud.com/v1.0/' + config['account_id'] + \ '/domains/' + config['domain_id'] + '/records/' + config['record_id'] data = {'ttl': config['record_ttl'], 'name': config['record_name'], 'data': public_ip} headers = {'Accept': 'application/json', 'Content-type': 'application/json', 'X-Auth-Token': cache['auth']['token']} result = requests.put(url, data=json.dumps(data), headers=headers) if result.ok: L.l.info('Updated IP address for {} to {}'.format(config['record_name'], public_ip)) else: L.l.warning('Unable to update IP, response={}'.format(result)) except Exception as ex: L.l.warning('Unable to check and update dns, err={}'.format(ex))
def init(): L.l.info('Sonoff module initialising') P.sonoff_topic = str(model_helper.get_param(Constant.P_MQTT_TOPIC_SONOFF_1)) mqtt_io.P.mqtt_client.message_callback_add(P.sonoff_topic, mqtt_on_message) thread_pool.add_interval_callable(thread_run, P.check_period)
def mpd(request): if request.json is not None: L.l.info('ALEXA request request={}'.format(request.json['request'])) if 'intent' in request.json['request']: intent = request.json['request']['intent'] if intent is not None: cmd = None zone = None if intent['name'] == 'AMAZON.PauseIntent': cmd = 'pause' elif intent['name'] == 'AMAZON.ResumeIntent': cmd = 'resume' elif intent['name'] == 'AMAZON.NextIntent': cmd = 'next' elif intent['name'] == 'AMAZON.PreviousIntent': cmd = 'previous' if 'slots' in intent.keys(): slots = intent['slots'] for name, value in slots.iteritems(): if name == 'Action': if 'value' in value.keys(): cmd = value['value'] elif name == 'Zone': if 'value' in value.keys(): zone = value['value'] port_config = get_param(Constant.P_MPD_PORT_ZONE).split(',') alt_port = None client = MPDClient() client.timeout = 5 if zone is None: # get the zone playing, only if one is active port_list_play = [] alt_zone = None for pair in port_config: port_val = int(pair.split('=')[1]) zone_val = pair.split('=')[0] client.connect(get_param(Constant.P_MPD_SERVER), port_val) if client.status()['state'] == 'play': port_list_play.append(port_val) alt_zone = zone_val client.close() client.disconnect() if len(port_list_play) == 1: alt_port = port_list_play[0] zone = alt_zone if cmd is not None and zone is not None: L.l.info('ALEXA executes {} in {}'.format(cmd, zone)) port = None for pair in port_config: if zone in pair: port = int(pair.split('=')[1]) break if port is None: port = alt_port if port is not None: client.connect(get_param(Constant.P_MPD_SERVER), port) status = client.status() outcome = 'not available' if cmd == 'next': client.next() outcome = client.currentsong()['title'] elif cmd == 'previous': client.previous() outcome = client.currentsong()['title'] elif cmd == 'pause' or cmd == 'stop': client.pause(1) outcome = client.status()['state'] elif cmd == 'resume' or cmd == 'play': client.pause(0) outcome = client.status()['state'] elif cmd == 'volumeup' or cmd == 'louder': client.setvol(int(status['volume']) + 5) outcome = client.status()['volume'] elif cmd == 'volumedown' or cmd == 'quiet': client.setvol(int(status['volume']) - 5) outcome = client.status()['volume'] client.close() client.disconnect() response = 'Action done, {} in zone {}, result is {}'.format( cmd, zone, outcome) else: response = 'Could not connect to MPD server, port not found' else: response = 'Warning, action not done, was {} in zone {}'.format( cmd, zone) else: response = 'Warning, incomplete action' else: response = 'Warning, intent not found' else: response = 'Invalid command' return '{ "version": "1.0", "sessionAttributes": {}, ' \ '"response": { "outputSpeech": {"type": "PlainText", "text": " ' + response + ' "}, ' \ '"shouldEndSession": true }}'
def _read_all_hdd_smart(): output = cStringIO.StringIO() current_disk_valid = True disk_letter = 'a' disk_count = 1 global ERR_TEXT_NO_DEV if import_module_psutil_exist: while current_disk_valid and disk_count < 64: try: record = models.SystemDisk() record.system_name = Constant.HOST_NAME assert isinstance(record, models.SystemDisk) record.hdd_disk_dev = Constant.DISK_DEV_MAIN + disk_letter L.l.debug('Processing disk {}'.format(record.hdd_disk_dev)) try: record.power_status = __read_hddparm( disk_dev=record.hdd_disk_dev) except Exception as ex1: record.power_status = None try: use_sudo = bool( model_helper.get_param(Constant.P_USESUDO_DISKTOOLS)) if Constant.OS in Constant.OS_LINUX and use_sudo: smart_out = subprocess.check_output( [ 'sudo', 'smartctl', '-a', record.hdd_disk_dev, '-n', 'sleep' ], stderr=subprocess.STDOUT) else: # in windows smart_out = subprocess.check_output( [ 'smartctl', '-a', record.hdd_disk_dev, '-n', 'sleep' ], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: smart_out = exc.output if ERR_TEXT_NO_DEV in smart_out or ERR_TEXT_NO_DEV_3 in smart_out: raise exc except Exception as ex: smart_out = None current_disk_valid = False L.l.warning("Error checking smart status {}".format(ex)) if smart_out: output.reset() output.write(smart_out) output.seek(0) pos = -1 while pos != output.tell() and current_disk_valid: pos = output.tell() line = output.readline() if Constant.SMARTCTL_ERROR_NO_DISK in line: current_disk_valid = False L.l.debug( 'First disk that cannot be read is {}'.format( record.hdd_disk_dev)) if Constant.SMARTCTL_TEMP_ID in line: words = line.split(None) record.temperature = utils.round_sensor_value( words[9]) # print 'Temp is {}'.format(temp) if Constant.SMARTCTL_ERROR_SECTORS in line: words = line.split(None) record.sector_error_count = words[9] # print 'Offline sectors with error is {}'.format(errcount) if Constant.SMARTCTL_START_STOP_COUNT in line: words = line.split(None) record.start_stop_count = words[9] if Constant.SMARTCTL_LOAD_CYCLE_COUNT in line: words = line.split(None) record.load_cycle_count = words[9] if Constant.SMARTCTL_STATUS in line: words = line.split(': ') record.smart_status = words[1].replace( '\r', '').replace('\n', '').strip() # print 'SMART Status is {}'.format(status) if Constant.SMARTCTL_MODEL_DEVICE in line: words = line.split(': ') record.device = words[1].replace('\r', '').replace( '\n', '').lstrip() # print 'Device is {}'.format(device) if Constant.SMARTCTL_MODEL_FAMILY in line: words = line.split(': ') record.family = words[1].replace('\r', '').replace( '\n', '').lstrip() # print 'Family is {}'.format(family) if Constant.SMARTCTL_SERIAL_NUMBER in line: words = line.split(': ') record.serial = words[1].replace('\r', '').replace( '\n', '').lstrip() # print 'Serial is {}'.format(serial) # print ('Disk dev is {}'.format(disk_dev)) record.updated_on = utils.get_base_location_now_date() if record.serial is None or record.serial == '': L.l.debug( 'This hdd will be skipped, probably does not exist if serial not retrieved' ) record.serial = 'serial not available {} {}'.format( Constant.HOST_NAME, record.hdd_disk_dev) else: record.hdd_name = '{} {} {}'.format( record.system_name, record.hdd_device, record.hdd_disk_dev) current_record = models.SystemDisk.query.filter_by( hdd_disk_dev=record.hdd_disk_dev, system_name=record.system_name).first() record.save_changed_fields(current_record=current_record, new_record=record, notify_transport_enabled=True, save_to_graph=True) disk_letter = chr(ord(disk_letter) + 1) disk_count += 1 except subprocess.CalledProcessError as ex1: L.l.debug('Invalid disk {} err {}'.format( record.hdd_disk_dev, ex1)) current_disk_valid = False except Exception as exc: if disk_count > 10: L.l.warning( 'Too many disks iterated {}, missing or wrong sudo rights for smartctl' .format(disk_count)) L.l.exception('Disk read error={} dev={}'.format( exc, record.hdd_disk_dev)) current_disk_valid = False else: L.l.debug('Unable to read smart status')
def get_song_url(song_id): url = get_param(Constant.P_GMUSICPROXY_URL) param = '/get_song?id={}'.format(song_id) return '{}{}'.format(url, param)
def _get_client(port=None): client = MPDClient() client.timeout = 5 if port is not None: client.connect(get_param(Constant.P_MPD_SERVER), port) return client
def init(): if mqtt_mosquitto_exists: L.l.info("INIT, Using mosquitto as mqtt client") elif mqtt_paho_exists: L.l.info("INIT, Using paho as mqtt client") else: L.l.critical("No mqtt client enabled via import") raise Exception("No mqtt client enabled via import") # not a good ideea to set a timeout as it will crash pigpio_gpio callback # socket.setdefaulttimeout(10) try: global client_connecting if client_connecting: L.l.warning( 'Mqtt client already in connection process, skipping attempt to connect until done' ) return host_list = [ #[model_helper.get_param(Constant.P_MQTT_HOST_3), int(model_helper.get_param(Constant.P_MQTT_PORT_3))], [ model_helper.get_param(Constant.P_MQTT_HOST_1), int(model_helper.get_param(Constant.P_MQTT_PORT_1)) ], #[model_helper.get_param(Constant.P_MQTT_HOST_2), int(model_helper.get_param(Constant.P_MQTT_PORT_2))] #[model_helper.get_param(constant.P_MQTT_HOST_3), int(model_helper.get_param(constant.P_MQTT_PORT_3))] ] P.topic = str(model_helper.get_param(Constant.P_MQTT_TOPIC)) P.topic_main = str(model_helper.get_param(Constant.P_MQTT_TOPIC_MAIN)) if mqtt_paho_exists: P.mqtt_client = mqtt.Client() elif mqtt_mosquitto_exists: P.mqtt_client = mqtt.Mosquitto() global client_connected global initialised for host_port in host_list: client_connecting = True host = host_port[0] port = host_port[1] L.l.info( 'MQTT publisher module initialising, host={} port={}'.format( host, port)) client_connected = False retry_count = 0 while (not client_connected) and ( retry_count < Constant.ERROR_CONNECT_MAX_RETRY_COUNT): try: if mqtt_mosquitto_exists: P.mqtt_client.on_connect = on_connect_mosquitto if mqtt_paho_exists: P.mqtt_client.on_connect = on_connect_paho P.mqtt_client.on_subscribe = on_subscribe P.mqtt_client.on_unsubscribe = on_unsubscribe # mqtt_client.username_pw_set('user', 'pass') P.mqtt_client.loop_start() P.mqtt_client.connect(host=host, port=port, keepalive=60) seconds_lapsed = 0 while not client_connected and seconds_lapsed < 10: time.sleep(1) seconds_lapsed += 1 if client_connected: # mqtt_client.on_message = receiver.on_message P.mqtt_client.message_callback_add( P.topic_main, receiver.on_message) P.mqtt_client.on_disconnect = on_disconnect thread_pool.add_interval_callable( receiver.thread_run, run_interval_second=10) # mqtt_client.loop_start() initialised = True client_connecting = False else: L.l.warning('Timeout connecting to mqtt') retry_count += 1 except socket.error as ex: L.l.error( 'mqtt client not connected, err {}, pause and retry {}' .format(ex, retry_count)) retry_count += 1 time.sleep(Constant.ERROR_CONNECT_PAUSE_SECOND) finally: client_connecting = False global last_connect_attempt last_connect_attempt = utils.get_base_location_now_date() if client_connected: break else: L.l.warning('Unable to connect to mqtt server {}:{}'.format( host, port)) if not client_connected: L.l.critical( 'MQTT connection not available, all connect attempts failed') except Exception as ex: L.l.error('Exception on mqtt init, err={}'.format(ex))