def start(): """Starts a thread which reads from RFM69Pi and publishes using MQTT.""" global logger logger = LoggerClient.open("OpenEnergyMonitor") logger.info("Opening connection") global client client = Utils.getpahoclient(logger) global iface iface = __try_open(logger) # config is a dictionary with: # devices : [ { id, desc, name } ] # keys : [ { nodeId, key, desc, name } ] config = Utils.getconfig("open_energy_monitor", logger) nodes = config["nodes"] node2keys = config["node2keys"] for n in nodes: # We add data field to check relative difference between two consecutive # readings, if the difference is not enough the message is not published, # reducing this way the overhead and database size. for conf in node2keys[str(n["id"])]: conf["data"] = -10000.0 conf["when"] = 0.0 global is_running is_running = True thread = threading.Thread(target=__process, args=(logger, client, iface, nodes, node2keys)) thread.setDaemon(True) thread.start()
def start(): """Opens connections with logger, InfluxDB and MQTT broker.""" global logger global mqtt_client global house_data global config global influx_client logger = LoggerClient.open("InfluxDBHub") mqtt_client = Utils.getpahoclient(logger, __configure_mqtt) config = Utils.getconfig("influxdb", logger) influx_client = InfluxDBClient(config["host"], config["port"], config["user"], config["password"], config["database"]) if not {"name": config["database"]} in influx_client.get_list_database(): influx_client.create_database(config["database"]) if not any([ x["name"] == "raspimon_policy" for x in influx_client.get_list_retention_policies() ]): influx_client.create_retention_policy('raspimon_policy', config["retention_policy"], 1, default=True) else: influx_client.alter_retention_policy( 'raspimon_policy', duration=config["retention_policy"], replication=1, default=True)
def publish(): global tz tz = pytz.timezone("Europe/Madrid") try: client = Utils.getpahoclient(logger) __publish_daily_forecast(client) __publish_hourly_forecast(client) __publish_current_weather_status(client) client.disconnect() except: print "Unexpected error:", traceback.format_exc() logger.error("Unexpected error: %s", traceback.format_exc())
def start(): """Opens connections with logger, MongoDB and MQTT broker.""" global logger global mqtt_client global house_data logger = LoggerClient.open("MongoDBHub") mqtt_client = Utils.getpahoclient(logger, __configure_mqtt) mongo_client = Utils.getmongoclient(logger) db = mongo_client["raspimon"] col = db["GVA2015_houses"] house_data = col.find_one({"raspi": raspi_mac}) assert house_data is not None mongo_client.close()
def __publish_data_of_day(day_str, ref_time): try: client = Utils.getpahoclient(logger, __configure) except: logger.error("Unable to connecto to MQTT broker") raise tomorrow_url = url.format(day_str) try: # http request response_string = urllib2.urlopen(tomorrow_url) except: logger.error("Unable to retrieve electricity prices") client.disconnect() raise try: response = json.load(response_string) pvpc = response['PVPC'] # PVPC is an array of dictionaries where every dictionary is: # {"Dia":"13/11/2015","Hora":"00-01", # "GEN":"126,08","NOC":"75,81","VHC":"79,94", # "COFGEN":"0,000075326953000000","COFNOC":"0,000158674625000000", # "COFVHC":"0,000134974129000000","PMHGEN":"66,35","PMHNOC":"63,98", # "PMHVHC":"66,63","SAHGEN":"6,14","SAHNOC":"5,92","SAHVHC":"6,17", # "FOMGEN":"0,03","FOMNOC":"0,03","FOMVHC":"0,03","FOSGEN":"0,13", # "FOSNOC":"0,12","FOSVHC":"0,13","INTGEN":"2,46","INTNOC":"2,37", # "INTVHC":"2,47","PCAPGEN":"6,94","PCAPNOC":"1,16","PCAPVHC":"1,64", # "TEUGEN":"44,03","TEUNOC":"2,22","TEUVHC":"2,88"} # Looking here: http://tarifaluzhora.es/ it seems that GEN is the main # electricity price, and it comes in thousandth of an euro. # It will send 25 hours at CEST to CET transition day. keys = [ 'GEN', 'NOC', 'VHC' ] # for every hour data in pvpc for res in pvpc: # TODO: check day value hour_offset = int( res['Hora'].split('-')[0] ) * 3600 for k in keys: v = float( res[k].replace(',','.') ) # replace commas by dots message = { 'timestamp' : ref_time + hour_offset, 'data' : v } client.publish(topic.format(k), json.dumps(message)) logger.info("Electricity price published") except: logger.info("Unable to publish electricity prices") client.disconnect() raise else: client.disconnect()
def __publish_data_of_day(day_str, ref_time): try: client = Utils.getpahoclient(logger, __configure) except: logger.error("Unable to connecto to MQTT broker") raise tomorrow_url = url.format(day_str) try: # http request response_string = urllib2.urlopen(tomorrow_url) except: logger.error("Unable to retrieve electricity prices") client.disconnect() raise try: response = json.load(response_string) pvpc = response['PVPC'] # PVPC is an array of dictionaries where every dictionary is: # {"Dia":"13/11/2015","Hora":"00-01", # "GEN":"126,08","NOC":"75,81","VHC":"79,94", # "COFGEN":"0,000075326953000000","COFNOC":"0,000158674625000000", # "COFVHC":"0,000134974129000000","PMHGEN":"66,35","PMHNOC":"63,98", # "PMHVHC":"66,63","SAHGEN":"6,14","SAHNOC":"5,92","SAHVHC":"6,17", # "FOMGEN":"0,03","FOMNOC":"0,03","FOMVHC":"0,03","FOSGEN":"0,13", # "FOSNOC":"0,12","FOSVHC":"0,13","INTGEN":"2,46","INTNOC":"2,37", # "INTVHC":"2,47","PCAPGEN":"6,94","PCAPNOC":"1,16","PCAPVHC":"1,64", # "TEUGEN":"44,03","TEUNOC":"2,22","TEUVHC":"2,88"} # Looking here: http://tarifaluzhora.es/ it seems that GEN is the main # electricity price, and it comes in thousandth of an euro. # It will send 25 hours at CEST to CET transition day. keys = ['GEN', 'NOC', 'VHC'] # for every hour data in pvpc for res in pvpc: # TODO: check day value hour_offset = int(res['Hora'].split('-')[0]) * 3600 for k in keys: v = float(res[k].replace(',', '.')) # replace commas by dots message = {'timestamp': ref_time + hour_offset, 'data': v} client.publish(topic.format(k), json.dumps(message)) logger.info("Electricity price published") except: logger.info("Unable to publish electricity prices") client.disconnect() raise else: client.disconnect()
def start(): """Connects with logging server, loads plugwise network configuration and connects with MQTT broker.""" global logger global client global config global device global circles_config global circles global mac2circle logger = LoggerClient.open("PlugwiseMonitor") if not verbose: logger.config(logger.levels.WARNING, logger.schedules.DAILY) config = Utils.getconfig("plugwise", logger) assert config is not None device = plugwise_api.Stick(logger, DEFAULT_SERIAL_PORT) # circles_config is a list of dictionaries: name, mac, desc. state field is # added in next loop to track its value so it can be used to only send # messages in state transitions. power1s and power8s field is used to check # the relative difference in power in order to reduce the network overhead. circles_config = config["circles"] circles = [] mac2circle = {} for circle_data in circles_config: mac = circle_data["mac"] circles.append( plugwise_api.Circle( logger, mac, device, { "name": circle_data["name"], "location": circle_data["desc"], "always_on": "False", "production": "True" })) mac2circle[mac] = circles[-1] circle_data["state"] = "NA" for v in OUTPUT_LIST: circle_data["power" + v["suffix"]] = -10000.0 circle_data["when" + v["suffix"]] = 0.0 client = Utils.getpahoclient(logger, __configure) client.loop_start()
def start(): """Opens connections with logger, InfluxDB and MQTT broker.""" global logger global mqtt_client global house_data global config global influx_client logger = LoggerClient.open("InfluxDBHub") mqtt_client = Utils.getpahoclient(logger, __configure_mqtt) config = Utils.getconfig("influxdb", logger) influx_client = InfluxDBClient(config["host"], config["port"], config["user"], config["password"], config["database"]) if not {"name":config["database"]} in influx_client.get_list_database(): influx_client.create_database(config["database"]) if not any([ x["name"]=="raspimon_policy" for x in influx_client.get_list_retention_policies()]): influx_client.create_retention_policy('raspimon_policy', config["retention_policy"], 1, default=True) else: influx_client.alter_retention_policy('raspimon_policy', duration=config["retention_policy"], replication=1, default=True)