SET FOREIGN_KEY_CHECKS=0;
INSERT INTO iotronic.boards (created_at, updated_at, id, uuid, code, status, name, type, agent, owner, project, mobile, config, extra) VALUES ('2017-12-07 14:09:35', '2018-01-31 11:52:27', 193, '96b69f1f-0188-48cc-abdc-d10674144c68', '567', 'offline', 'yun-30', 'yun', 'wagent2', '13ae14174aa1424688a75253ef814261', '3c1e2e2c4bac40da9b4b1d694da6e2a1', 0, '{"iotronic": {"extra": {}, "board": {"status": "registered", "code": "567", "name": "yun-30", "extra": {}, "mobile": false, "type": "yun", "created_at": "2017-12-07T14:09:35Z", "updated_at": "2017-12-07T15:39:20Z", "agent": "wagent2", "project": "3c1e2e2c4bac40da9b4b1d694da6e2a1", "location": {"latitude": "38.259486", "altitude": "18.0", "updated_at": "2017-12-07T14:09:35Z", "longitude": "15.5948288"}, "owner": "13ae14174aa1424688a75253ef814261", "id": 193, "uuid": "96b69f1f-0188-48cc-abdc-d10674144c68"}, "wamp": {"main-agent": {"url": "ws://192.168.17.103:8181/", "realm": "s4t"}, "registration-agent": {"url": "ws://192.168.17.103:8181/", "realm": "s4t"}}}}', '{}');
INSERT INTO iotronic.boards (created_at, updated_at, id, uuid, code, status, name, type, agent, owner, project, mobile, config, extra) VALUES ('2018-02-01 13:12:38', '2018-07-10 08:52:18', 196, '56403f3e-bec2-42e1-be18-915e4f86a520', '141414', 'offline', 'laptop-14', 'server', 'wagent1', '13ae14174aa1424688a75253ef814261', '3c1e2e2c4bac40da9b4b1d694da6e2a1', 0, '{"iotronic": {"wamp": {"main-agent": {"url": "ws://192.168.17.103:8181/", "realm": "s4t"}, "registration-agent": {"url": "ws://192.168.17.103:8181/", "realm": "s4t"}}, "extra": {}, "board": {"project": "3c1e2e2c4bac40da9b4b1d694da6e2a1", "code": "141414", "owner": "13ae14174aa1424688a75253ef814261", "type": "server", "id": 196, "status": "registered", "agent": "wagent1", "mobile": false, "name": "laptop-14", "created_at": "2018-02-01T13:12:38+00:00", "uuid": "56403f3e-bec2-42e1-be18-915e4f86a520", "updated_at": "2018-02-01T13:13:35+00:00", "extra": {}, "location": {"altitude": "70.0", "updated_at": "2018-02-01T13:12:38+00:00", "longitude": "15.59545", "latitude": "38.25966"}}}}', '{}');
INSERT INTO iotronic.boards (created_at, updated_at, id, uuid, code, status, name, type, agent, owner, project, mobile, config, extra) VALUES ('2018-07-10 09:42:54', '2018-07-26 12:37:24', 219, '325c5e84-0ae0-40ad-9eed-1541fdd30f5d', 'ciao', 'online', 'rasp-14', 'server', 'wagent2', '13ae14174aa1424688a75253ef814261', '3c1e2e2c4bac40da9b4b1d694da6e2a1', 0, '{"iotronic": {"wamp": {"main-agent": {"realm": "s4t", "url": "wss://192.168.17.104:8181/"}, "registration-agent": {"realm": "s4t", "url": "wss://192.168.17.103:8181/"}}, "extra": {}, "board": {"created_at": "2018-07-10T09:42:54+00:00", "project": "3c1e2e2c4bac40da9b4b1d694da6e2a1", "location": {"altitude": "0.0", "latitude": "38.0", "updated_at": "2018-07-10T09:42:54+00:00", "longitude": "15.0"}, "type": "server", "uuid": "325c5e84-0ae0-40ad-9eed-1541fdd30f5d", "owner": "13ae14174aa1424688a75253ef814261", "mobile": false, "status": "registered", "agent": "wagent2", "name": "rasp-14", "extra": {}, "updated_at": null, "code": "ciao", "id": 219}}}', '{}');
INSERT INTO iotronic.boards (created_at, updated_at, id, uuid, code, status, name, type, agent, owner, project, mobile, config, extra) VALUES ('2018-07-31 09:18:32', '2018-08-07 07:54:18', 222, '054d5be1-48a1-4698-ae4a-7fb4b4d61a1d', 'fbnotebook', 'online', 'fbnotebook', 'server', 'wagent2', '13ae14174aa1424688a75253ef814261', '3c1e2e2c4bac40da9b4b1d694da6e2a1', 0, '{"iotronic": {"wamp": {"main-agent": {"realm": "s4t", "url": "wss://192.168.17.104:8181/"}, "registration-agent": {"realm": "s4t", "url": "wss://192.168.17.103:8181/"}}, "extra": {}, "board": {"created_at": "2018-07-31T09:18:32+00:00", "project": "3c1e2e2c4bac40da9b4b1d694da6e2a1", "location": {"altitude": "1.0", "latitude": "1.0", "updated_at": "2018-07-31T09:18:32+00:00", "longitude": "1.0"}, "type": "server", "uuid": "054d5be1-48a1-4698-ae4a-7fb4b4d61a1d", "owner": "13ae14174aa1424688a75253ef814261", "mobile": false, "status": "registered", "agent": "wagent2", "name": "fbnotebook", "extra": {}, "updated_at": null, "code": "fbnotebook", "id": 222}}}', '{}');
INSERT INTO iotronic.boards (created_at, updated_at, id, uuid, code, status, name, type, agent, owner, project, mobile, config, extra) VALUES ('2018-08-03 10:06:26', '2018-08-03 16:34:03', 223, 'a1b4f154-6248-42b7-b510-cf4cd122a763', 'fb2', 'offline', 'fbnotebook2', 'server', 'wagent2', '13ae14174aa1424688a75253ef814261', '3c1e2e2c4bac40da9b4b1d694da6e2a1', 0, '{"iotronic": {"wamp": {"main-agent": {"realm": "s4t", "url": "wss://192.168.17.104:8181/"}, "registration-agent": {"realm": "s4t", "url": "wss://192.168.17.103:8181/"}}, "extra": {}, "board": {"created_at": "2018-08-03T10:06:26+00:00", "project": "3c1e2e2c4bac40da9b4b1d694da6e2a1", "location": {"altitude": "1.0", "latitude": "1.0", "updated_at": "2018-08-03T10:06:26+00:00", "longitude": "1.0"}, "type": "server", "uuid": "a1b4f154-6248-42b7-b510-cf4cd122a763", "owner": "13ae14174aa1424688a75253ef814261", "mobile": false, "status": "registered", "agent": "wagent2", "name": "fbnotebook2", "extra": {}, "updated_at": null, "code": "fb2", "id": 223}}}', '{}');
INSERT INTO iotronic.conductors (created_at, updated_at, id, hostname, online) VALUES ('2018-07-02 16:23:48', '2018-07-06 10:19:06', 6, 'conductor', 1);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-07-04 11:20:00', null, 140, '56403f3e-bec2-42e1-be18-915e4f86a520', 'bf3b1dc4-01b5-4b7e-9731-025c1e2ab285', 6222);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-07-10 10:12:26', null, 143, '325c5e84-0ae0-40ad-9eed-1541fdd30f5d', '436db267-95a7-4563-8538-bd67f32dcaa4', 6591);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-07-10 10:21:22', null, 144, '325c5e84-0ae0-40ad-9eed-1541fdd30f5d', '3914d4ce-c60a-4c51-8e1c-3859e815f540', 6512);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-07-10 11:22:52', null, 145, '325c5e84-0ae0-40ad-9eed-1541fdd30f5d', 'bf3b1dc4-01b5-4b7e-9731-025c1e2ab285', 6278);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-07-26 10:50:42', null, 147, '325c5e84-0ae0-40ad-9eed-1541fdd30f5d', 'bd0c8361-e158-4e9a-a2be-386934c16cbd', 6083);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-07-31 10:13:39', null, 149, '054d5be1-48a1-4698-ae4a-7fb4b4d61a1d', 'bd0c8361-e158-4e9a-a2be-386934c16cbd', 6772);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-07-31 10:13:51', null, 150, '054d5be1-48a1-4698-ae4a-7fb4b4d61a1d', '436db267-95a7-4563-8538-bd67f32dcaa4', 6639);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-08-03 10:56:14', null, 153, 'a1b4f154-6248-42b7-b510-cf4cd122a763', 'bd0c8361-e158-4e9a-a2be-386934c16cbd', 6248);
INSERT INTO iotronic.exposed_services (created_at, updated_at, id, board_uuid, service_uuid, public_port) VALUES ('2018-08-03 10:56:25', null, 154, 'a1b4f154-6248-42b7-b510-cf4cd122a763', '436db267-95a7-4563-8538-bd67f32dcaa4', 6381);
INSERT INTO iotronic.injection_plugins (created_at, updated_at, id, board_uuid, plugin_uuid, status, onboot) VALUES ('2017-12-07 15:03:16', null, 189, '96b69f1f-0188-48cc-abdc-d10674144c68', 'bd4f53ec-caa4-45d9-8161-f3af10739d9a', 'injected', 0);
INSERT INTO iotronic.injection_plugins (created_at, updated_at, id, board_uuid, plugin_uuid, status, onboot) VALUES ('2017-12-07 15:04:28', null, 190, '96b69f1f-0188-48cc-abdc-d10674144c68', '09b9f21a-fc4d-4bd5-91a0-728a1003e691', 'injected', 0);
INSERT INTO iotronic.injection_plugins (created_at, updated_at, id, board_uuid, plugin_uuid, status, onboot) VALUES ('2017-12-07 15:31:43', null, 191, '96b69f1f-0188-48cc-abdc-d10674144c68', 'd5227441-6602-449f-8a66-a9e95269ca07', 'injected', 1);INSERT INTO iotronic.locations (created_at, updated_at, id, longitude, latitude, altitude, board_id) VALUES ('2017-12-07 14:09:35', null, 32, '15.5948288', '38.259486', '18.0', 193);
INSERT INTO iotronic.locations (created_at, updated_at, id, longitude, latitude, altitude, board_id) VALUES ('2018-02-01 13:12:38', null, 35, '15.59545', '38.25966', '70.0', 196);
INSERT INTO iotronic.locations (created_at, updated_at, id, longitude, latitude, altitude, board_id) VALUES ('2018-07-10 09:42:54', null, 40, '15.0', '38.0', '0.0', 219);
INSERT INTO iotronic.locations (created_at, updated_at, id, longitude, latitude, altitude, board_id) VALUES ('2018-07-31 09:18:32', null, 43, '1.0', '1.0', '1.0', 222);
INSERT INTO iotronic.locations (created_at, updated_at, id, longitude, latitude, altitude, board_id) VALUES ('2018-08-03 10:06:26', null, 44, '1.0', '1.0', '1.0', 223);
INSERT INTO iotronic.plugins (created_at, updated_at, id, uuid, name, public, code, callable, parameters, extra, owner) VALUES ('2017-05-02 09:32:56', '2017-05-05 13:08:53', 168, '6c810ee0-28ff-43cb-a22f-9be0bbe6ed0f', 'monasca', 1, 'S''# Copyright 2017 MDSLAB - University of Messina\\r\\n#    All Rights Reserved.\\r\\n#\\r\\n#    Licensed under the Apache License, Version 2.0 (the "License"); you may\\r\\n#    not use this file except in compliance with the License. You may obtain\\r\\n#    a copy of the License at\\r\\n#\\r\\n#         http://www.apache.org/licenses/LICENSE-2.0\\r\\n#\\r\\n#    Unless required by applicable law or agreed to in writing, software\\r\\n#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\\r\\n#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\\r\\n#    License for the specific language governing permissions and limitations\\r\\n#    under the License.\\r\\n\\r\\nfrom iotronic_lightningrod.plugins import Plugin\\r\\nfrom iotronic_lightningrod.plugins import pluginApis as API\\r\\n\\r\\n\\r\\n\\r\\n\\r\\nfrom oslo_log import log as logging\\r\\nLOG = logging.getLogger(__name__)\\r\\n\\r\\n# User imports\\r\\nimport json\\r\\nimport math\\r\\nimport time\\r\\nimport threading\\r\\n\\r\\n\\r\\n# MONASCA imports and global variables\\r\\nimport monasca_agent.forwarder.api.monasca_api as mon\\r\\nmessage_batch = []\\r\\nimport os\\r\\n\\r\\n\\r\\n\\r\\n# User global variables\\r\\n\\r\\nsensors_list = [\\r\\n    \\''temperature\\'',\\r\\n    \\''brightness\\''\\r\\n]\\r\\nposition = None\\r\\nSENSORS = {}\\r\\nlocation = {}\\r\\nTHR_KILL = None\\r\\niotronic_ip = "212.189.207.225"\\r\\nhostname = os.uname()[1]\\r\\ndevice = API.getBoardGpio()\\r\\n\\r\\n# IoTronic client management\\r\\nfrom iotronicclient import client\\r\\nfrom keystoneauth1.identity import v3\\r\\nfrom keystoneauth1 import session\\r\\nauth = v3.Password(auth_url=\\''http://\\''+iotronic_ip+\\'':35357/v3\\'',\\r\\n                   username=\\''admin\\'',\\r\\n                   password=\\''B0st0nc3rb3rus!\\'',\\r\\n                   project_name=\\''boston\\'',\\r\\n                   user_domain_id="default", project_domain_id="default"\\r\\n                   )\\r\\nsess = session.Session(auth=auth)\\r\\niotronic = client.get_client("1",session=sess)\\r\\n\\r\\nALERT = False\\r\\n\\r\\n\\r\\n\\r\\n# Sensors global parameters\\r\\n# - Temperature Parameters\\r\\nADCres = 1023.0\\r\\nBeta = 3950\\r\\nKelvin = 273.15\\r\\nRb = 10000\\r\\nGinf = 120.6685\\r\\nlatest_temp = None\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\ndef getMonascaMetric(metric, worker):\\r\\n\\r\\n    # Call Sensors Metrics: Temperature(), etc...\\r\\n    #m_value = str(globals()[metric.capitalize()]())\\r\\n    #print globals()[metric.capitalize()]\\r\\n\\r\\n    m_value = getattr(worker, metric.capitalize())()\\r\\n\\r\\n    #m_timestamp = datetime.datetime.now().strftime(\\''%Y-%m-%dT%H:%M:%S.%f\\'')\\r\\n    m_timestamp = int(time.time()*1000)\\r\\n\\r\\n    if metric == \\''temperature\\'':\\r\\n        LOG.info("Monasca Temperature " + str(m_value) + u" \\\\u2103")\\r\\n\\r\\n    data = {}\\r\\n    data[metric.capitalize()] = m_value\\r\\n    data["Date"] = str(m_timestamp)\\r\\n    data = json.dumps(data)\\r\\n\\r\\n    return data\\r\\n\\r\\n\\r\\ndef setSensorsLayout(params):\\r\\n    for sensor in sensors_list:\\r\\n        SENSORS[sensor] = {}\\r\\n        SENSORS[sensor][\\''pin\\''] = params[sensor][\\''pin\\'']\\r\\n        SENSORS[sensor][\\''enabled\\''] = params[sensor][\\''enabled\\'']\\r\\n\\r\\n\\r\\ndef InitSmartMeBoard(params):\\r\\n    """This function init the SmartME board.\\r\\n\\r\\n    In the SmartME Arduino YUN board this function enables the needed\\r\\n    devices and set the needed parameters about sensors and location.\\r\\n\\r\\n    :param params: plugin parameters to configure the board.\\r\\n\\r\\n    """\\r\\n\\r\\n    # get location\\r\\n    global location\\r\\n    location = API.getLocation()\\r\\n    LOG.info(\\r\\n        "Board location: \\\\n"\\r\\n        + json.dumps(location, indent=4, separators=(\\'',\\'', \\'': \\''))\\r\\n    )\\r\\n\\r\\n    # set devices\\r\\n    try:\\r\\n\\r\\n        global ALERT\\r\\n        if not ALERT:\\r\\n            device.EnableGPIO()\\r\\n\\r\\n    except Exception as err:\\r\\n        LOG.error("Error configuring devices: " + str(err))\\r\\n        global THR_KILL\\r\\n        THR_KILL = False\\r\\n\\r\\n\\r\\n    # set up sensors\\r\\n    setSensorsLayout(params)\\r\\n\\r\\n\\r\\ndef iotronicCall(board, params):\\r\\n    """thread worker function"""\\r\\n    try:\\r\\n        iotronic.plugin_injection.plugin_action(board.uuid, \\''6c810ee0-28ff-43cb-a22f-9be0bbe6ed0f\\'', \\''PluginReboot\\'', params)\\r\\n    except Exception as err:\\r\\n        LOG.error("RPC request error for board "+board.uuid+": " + str(err))\\r\\n\\r\\n    return\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\nclass Worker(Plugin.Plugin):\\r\\n\\r\\n    def __init__(self, uuid, name, q_result=None, params=None):\\r\\n        super(Worker, self).__init__(\\r\\n            uuid, name,\\r\\n            q_result=q_result,\\r\\n            params=params\\r\\n        )\\r\\n\\r\\n    def Brightness(self):\\r\\n\\r\\n        try:\\r\\n            voltage = float(device._readVoltage(SENSORS[\\''brightness\\''][\\''pin\\'']))\\r\\n\\r\\n            ldr = (2500 / (5 - voltage * float(0.004887)) - 500) / float(3.3)\\r\\n\\r\\n            LOG.info("Monasca Brightness: " + str(ldr) + " (lux)")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting Monasca brightness: " + str(err))\\r\\n\\r\\n        return ldr\\r\\n\\r\\n    def Temperature(self):\\r\\n\\r\\n        try:\\r\\n            voltage = device._readVoltage(SENSORS[\\''temperature\\''][\\''pin\\''])\\r\\n\\r\\n            Rthermistor = float(Rb) * (float(ADCres) / float(voltage) - 1)\\r\\n            rel_temp = float(Beta) / (\\r\\n            math.log(float(Rthermistor) * float(Ginf)))\\r\\n            temp = rel_temp - Kelvin\\r\\n\\r\\n            # LOG.info("Temperature " + str(temp) + u" \\\\u2103")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting Monasca temperature: " + str(err))\\r\\n\\r\\n        return temp\\r\\n\\r\\n    def run(self):\\r\\n\\r\\n        LOG.info("Monasca plugin starting...")\\r\\n\\r\\n        global ALERT\\r\\n\\r\\n        global THR_KILL\\r\\n        THR_KILL = self._is_running\\r\\n\\r\\n        # Board initialization\\r\\n        LOG.info("PARAMS list: " + str(self.params.keys()))\\r\\n\\r\\n        LOG.debug("Monasca API loading....")\\r\\n        global message_batch\\r\\n\\r\\n        agent_config = {\\r\\n            \\''is_enabled\\'': False,\\r\\n            \\''max_measurement_buffer_size\\'': -1,\\r\\n            \\''disable_file_logging\\'': False,\\r\\n            \\''additional_checksd\\'': \\''/usr/lib/monasca/agent/custom_checks.d\\'',\\r\\n            \\''user_domain_name\\'': \\''Default\\'',\\r\\n            \\''use_keystone\\'': True,\\r\\n            \\''num_collector_threads\\'': 1,\\r\\n            \\''statsd_log_file\\'': \\''/var/log/monasca/agent/statsd.log\\'',\\r\\n            \\''syslog_host\\'': None,\\r\\n            \\''keystone_timeout\\'': 20,\\r\\n            \\''max_buffer_size\\'': 1000,\\r\\n            \\''syslog_port\\'': None,\\r\\n            \\''limit_memory_consumption\\'': None,\\r\\n            \\''backlog_send_rate\\'': 1000,\\r\\n            \\''project_domain_id\\'': None,\\r\\n            \\''autorestart\\'': True,\\r\\n            \\''log_level\\'': \\''DEBUG\\'',\\r\\n            \\''collector_restart_interval\\'': 24,\\r\\n            \\''listen_port\\'': None,\\r\\n            \\''check_freq\\'': 30,\\r\\n            \\''hostname\\'': str(hostname),\\r\\n            \\''log_to_syslog\\'': False,\\r\\n            \\''non_local_traffic\\'': False,\\r\\n            \\''version\\'': \\''1.7.0\\'',\\r\\n            \\''service_type\\'': None,\\r\\n            \\''jmxfetch_log_file\\'': \\''/var/log/monasca/agent/jmxfetch.log\\'',\\r\\n            \\''pool_full_max_retries\\'': 4,\\r\\n            \\''project_domain_name\\'': \\''Default\\'',\\r\\n            \\''username\\'': \\''cmm-agent\\'',\\r\\n            \\''password\\'': \\''admin\\'',\\r\\n            \\''project_name\\'': \\''boston\\'',\\r\\n            \\''project_id\\'': None,\\r\\n            \\''collector_log_file\\'': \\''/var/log/monasca/agent/collector.log\\'',\\r\\n            \\''region_name\\'': None,\\r\\n            \\''skip_ssl_validation\\'': False,\\r\\n            \\''forwarder_url\\'': \\''http://localhost:17123\\'',\\r\\n            \\''amplifier\\'': 0,\\r\\n            \\''insecure\\'': False,\\r\\n            \\''dimensions\\'': {},\\r\\n            \\''endpoint_type\\'': None,\\r\\n            \\''ca_file\\'': None,\\r\\n            \\''sub_collection_warn\\'': 6,\\r\\n            \\''user_domain_id\\'': None,\\r\\n            \\''url\\'': \\''http://\\''+ iotronic_ip +\\'':8070/v2.0\\'',\\r\\n            \\''keystone_url\\'': \\''http://\\''+ iotronic_ip +\\'':35357/v3\\'',\\r\\n            \\''forwarder_log_file\\'': \\''/var/log/monasca/agent/forwarder.log\\'',\\r\\n            \\''write_timeout\\'': 10,\\r\\n            \\''log_to_event_viewer\\'': False\\r\\n        }\\r\\n\\r\\n        endpoint = mon.MonascaAPI(agent_config)\\r\\n\\r\\n\\r\\n        if len(self.params.keys()) != 0:\\r\\n\\r\\n            InitSmartMeBoard(self.params)\\r\\n            \\r\\n            # Get trigger measure\\r\\n            trigger = str(self.params[\\''trigger\\''])\\r\\n            LOG.info("Trigger measure: " + str(trigger))\\r\\n\\r\\n            # Get polling time\\r\\n            polling_time = float(self.params[\\''polling\\''])\\r\\n            LOG.info("Polling time: " + str(polling_time))\\r\\n\\r\\n            # Get threshold\\r\\n            threshold = float(self.params[\\''threshold\\''])\\r\\n            \\r\\n            if trigger == "temperature":\\r\\n                LOG.info("Threshold: " + str(threshold) + u" \\\\u2103")\\r\\n            elif trigger == "brightness":\\r\\n                LOG.info("Threshold: " + str(threshold) + " lux")\\r\\n            else:\\r\\n                LOG.error("WRONG metric specified!")\\r\\n                self._is_running = False\\r\\n                THR_KILL = self._is_running\\r\\n                \\r\\n            \\r\\n\\r\\n\\r\\n            LOG.info(\\r\\n                "SENSORS: \\\\n"\\r\\n                + json.dumps(SENSORS, indent=4, separators=(\\'',\\'', \\'': \\''))\\r\\n            )\\r\\n\\r\\n            counter = 0\\r\\n\\r\\n\\r\\n\\r\\n            while (self._is_running and THR_KILL):\\r\\n\\r\\n                # TURN OFF notification LED\\r\\n                device._setGPIOs("D13", "out", "1")\\r\\n\\r\\n                if sensors_list.__len__() != 0:\\r\\n\\r\\n                    # Get metrics\\r\\n                    for sensor in sensors_list:\\r\\n\\r\\n                        if SENSORS[sensor][\\''enabled\\'']:\\r\\n\\r\\n                            try:\\r\\n\\r\\n                                measure = json.loads(getMonascaMetric(sensor, self))\\r\\n\\r\\n                                if sensor == trigger:\\r\\n\\r\\n                                    value = measure[trigger.capitalize()]\\r\\n\\r\\n                                    # Check threshold\\r\\n                                    if float(value) >= float(threshold):\\r\\n\\r\\n                                        LOG.warning("ALERT - "+trigger.capitalize()+" over threshold!")\\r\\n\\r\\n                                        polling_time = 5\\r\\n\\r\\n                                        if not ALERT:\\r\\n\\r\\n                                            ALERT = True\\r\\n\\r\\n                                            boards_list = iotronic.board.list()\\r\\n                                            #print boards_list\\r\\n\\r\\n                                            for board in boards_list:\\r\\n\\r\\n                                                if board.uuid != API.getBoardID():\\r\\n\\r\\n                                                    if str(board.status) == "online":\\r\\n\\r\\n                                                        params = {\\r\\n                                                            "polling": polling_time,\\r\\n                                                            "threshold": threshold,\\r\\n                                                            "trigger": trigger,\\r\\n                                                            "ckan_enabled": False,\\r\\n                                                            "temperature": {\\r\\n                                                                "pin": "A0",\\r\\n                                                                "enabled": True\\r\\n                                                            },\\r\\n                                                            "brightness": {\\r\\n                                                                "pin": "A1",\\r\\n                                                                "enabled": True\\r\\n                                                            }\\r\\n                                                        }\\r\\n\\r\\n                                                        try:\\r\\n                                                            LOG.info("Rebooting Monasca plugin for board " + board.uuid)\\r\\n\\r\\n                                                            t = threading.Thread(\\r\\n                                                                target=iotronicCall,\\r\\n                                                                args=(board, params, ))\\r\\n                                                            t.start()\\r\\n\\r\\n                                                        except Exception as err:\\r\\n                                                            message = "RPC request expired for board " + board.uuid\\r\\n                                                            LOG.warning(" - " + message)\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n                                    else:\\r\\n\\r\\n                                        polling_time = float(self.params[\\''polling\\''])\\r\\n\\r\\n                                        if ALERT is True:\\r\\n\\r\\n                                            LOG.warning("ALERT - "+trigger.capitalize()+" under threshold!")\\r\\n\\r\\n                                            ALERT = False\\r\\n\\r\\n                                            try:\\r\\n\\r\\n                                                boards_list = iotronic.board.list()\\r\\n\\r\\n                                                for board in boards_list:\\r\\n\\r\\n                                                    if board.uuid != API.getBoardID():\\r\\n\\r\\n                                                        if str(board.status) == "online":\\r\\n\\r\\n                                                            params = {\\r\\n                                                                "polling": polling_time,\\r\\n                                                                "threshold": threshold,\\r\\n                                                                "trigger": trigger,\\r\\n                                                                "ckan_enabled": False,\\r\\n                                                                "temperature": {\\r\\n                                                                    "pin": "A0",\\r\\n                                                                    "enabled": True\\r\\n                                                                },\\r\\n                                                                "brightness": {\\r\\n                                                                    "pin": "A1",\\r\\n                                                                    "enabled": True\\r\\n                                                                }\\r\\n                                                            }\\r\\n\\r\\n                                                            try:\\r\\n                                                                LOG.info("Rebooting Monasca plugin for board " + board.uuid)\\r\\n\\r\\n                                                                t = threading.Thread(\\r\\n                                                                    target=iotronicCall,\\r\\n                                                                    args=(board,params,))\\r\\n                                                                t.start()\\r\\n\\r\\n                                                            except Exception as err:\\r\\n                                                                message = "Error executing Iotronic Client for board: " + board.uuid\\r\\n                                                                LOG.warning(" - " + message)\\r\\n\\r\\n                                            except Exception as err:\\r\\n                                                message = "Error resetting alarms: " + str(err)\\r\\n                                                LOG.warning(" - " + message)\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n                                else:\\r\\n                                    value = measure[sensor.capitalize()]\\r\\n\\r\\n\\r\\n                                timestamp = measure[\\''Date\\'']\\r\\n\\r\\n                                LOG.debug(" - " + sensor + ": " + str(value) + " -  time: " + timestamp)\\r\\n\\r\\n                                # SEND TO MONASCA\\r\\n                                """\\r\\n                                \\''location\\'':{\\r\\n                                   "key": str(hostname),\\r\\n                                   "latitude": location[\\''latitude\\''],\\r\\n                                   "longitude": location[\\''longitude\\''],\\r\\n                                   "name": str(hostname)\\r\\n                                }\\r\\n                                """\\r\\n                                LOG.debug("Sending metrics to Monasca...")\\r\\n                                try:\\r\\n\\r\\n                                    msg = [{\\r\\n                                        \\''tenant_id\\'': None,\\r\\n                                        \\''measurement\\'':\\r\\n                                            {\\r\\n                                                \\''timestamp\\'': timestamp,\\r\\n                                                \\''dimensions\\'': {\\''hostname\\'': str(hostname), },\\r\\n                                                \\''name\\'': \\''s4t-\\'' + sensor,\\r\\n                                                \\''value\\'': value,\\r\\n                                                \\''value_meta\\'': None\\r\\n\\r\\n                                            }\\r\\n                                    }]\\r\\n\\r\\n                                    message_batch.extend(msg)\\r\\n\\r\\n                                    endpoint.post_metrics(message_batch)\\r\\n\\r\\n                                    message_batch = []\\r\\n\\r\\n\\r\\n                                except Exception as e :\\r\\n                                    LOG.error(\\''Error sending metrics to Monasca: \\'' + str(e))\\r\\n\\r\\n\\r\\n\\r\\n                            except Exception as err:\\r\\n                                message = "Error reading metrics: " + str(err)\\r\\n                                LOG.warning(" - " + message)\\r\\n\\r\\n\\r\\n                    counter = counter + 1\\r\\n                    LOG.info("Monasca Sample number: " + str(counter) + "\\\\n\\\\n")\\r\\n\\r\\n                    # TURN ON notification LED\\r\\n                    device._setGPIOs("D13", "out", "0")\\r\\n\\r\\n                    time.sleep(polling_time)\\r\\n\\r\\n\\r\\n\\r\\n                else:\\r\\n                    LOG.warning("No sensors!")\\r\\n                    self._is_running = False\\r\\n                    THR_KILL = self._is_running\\r\\n\\r\\n            # Update the thread status: at this stage THR_KILL will be False\\r\\n            THR_KILL = self._is_running\\r\\n\\r\\n        else:\\r\\n            LOG.error("No parameters provided!")\\r\\n''
.', 0, '{"ckan_enabled": false, "temperature": {"enabled": true, "pin": "A0"}, "polling": "10", "brightness": {"enabled": true, "pin": "A1"}}', '{}', '13ae14174aa1424688a75253ef814261');
INSERT INTO iotronic.plugins (created_at, updated_at, id, uuid, name, public, code, callable, parameters, extra, owner) VALUES ('2017-05-03 10:06:43', '2017-05-05 07:46:04', 169, 'd5227441-6602-449f-8a66-a9e95269ca07', 'smartme', 1, 'S''# Copyright 2017 MDSLAB - University of Messina\\r\\n#    All Rights Reserved.\\r\\n#\\r\\n#    Licensed under the Apache License, Version 2.0 (the "License"); you may\\r\\n#    not use this file except in compliance with the License. You may obtain\\r\\n#    a copy of the License at\\r\\n#\\r\\n#         http://www.apache.org/licenses/LICENSE-2.0\\r\\n#\\r\\n#    Unless required by applicable law or agreed to in writing, software\\r\\n#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\\r\\n#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\\r\\n#    License for the specific language governing permissions and limitations\\r\\n#    under the License.\\r\\n\\r\\nfrom iotronic_lightningrod.plugins import Plugin\\r\\nfrom iotronic_lightningrod.plugins import pluginApis as API\\r\\n\\r\\nfrom oslo_log import log as logging\\r\\nLOG = logging.getLogger(__name__)\\r\\n\\r\\n# User imports\\r\\nimport datetime\\r\\nimport json\\r\\nimport math\\r\\nimport threading\\r\\nimport time\\r\\n\\r\\n# User global variables\\r\\nckan_addr = \\''smartme-data.unime.it\\''\\r\\naction_URL = "http://" + ckan_addr + "/api/3/action/datastore_upsert"\\r\\napi_key = \\''22c5cfa7-9dea-4dd9-9f9d-eedf296852ae\\''\\r\\nheaders = {\\r\\n    "Content-Type": "application/json",\\r\\n    \\''Authorization\\'': "" + api_key + ""\\r\\n}\\r\\n\\r\\nsensors_list = [\\r\\n    \\''temperature\\'',\\r\\n    \\''brightness\\'',\\r\\n    \\''humidity\\'',\\r\\n    \\''pressure\\'',\\r\\n    \\''noise\\''\\r\\n    # , \\''gas\\''\\r\\n]\\r\\nposition = None\\r\\n\\r\\nSENSORS = {}\\r\\n\\r\\nlocation = {}\\r\\n\\r\\ndevice = API.getBoardGpio()\\r\\n\\r\\nTHR_KILL = None\\r\\n\\r\\n\\r\\n# Sensors global parameters\\r\\n\\r\\n# Temperature Parameters\\r\\nADCres = 1023.0\\r\\nBeta = 3950\\r\\nKelvin = 273.15\\r\\nRb = 10000\\r\\nGinf = 120.6685\\r\\nlatest_temp = None\\r\\n\\r\\n# Noise Parameters\\r\\nsamples_number = 1000\\r\\namplitudes_sum = 0\\r\\namplitudes_count = 0\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\ndef noise_listner():\\r\\n    """Each two seconds collect a Noise sample.\\r\\n\\r\\n    """\\r\\n\\r\\n    global THR_KILL\\r\\n\\r\\n    vect = []\\r\\n\\r\\n    if THR_KILL:\\r\\n\\r\\n        # LOG.info("listening noise..." + str(THR_KILL))\\r\\n\\r\\n        for x in range(samples_number):\\r\\n\\r\\n            read = float(device._readVoltage(SENSORS[\\''noise\\''][\\''pin\\'']))\\r\\n            vect.append(read)\\r\\n\\r\\n        sorted_vect = sorted(vect)\\r\\n\\r\\n        minimum = float(sorted_vect[50])\\r\\n        maximum = float(sorted_vect[samples_number - 51])\\r\\n        tmp_amplitude = float(maximum - minimum)\\r\\n\\r\\n        global amplitudes_sum, amplitudes_count\\r\\n        amplitudes_sum = float(amplitudes_sum + tmp_amplitude)\\r\\n        amplitudes_count = float(amplitudes_count + 1)\\r\\n        # LOG.info("amplitudes_sum = " + str(amplitudes_sum))\\r\\n        # LOG.info("amplitudes_count = " + str(amplitudes_count))\\r\\n\\r\\n        threading.Timer(2.0, noise_listner).start()\\r\\n\\r\\n    else:\\r\\n        LOG.debug("Cancelled SmartME noise listening: " + str(THR_KILL))\\r\\n\\r\\n\\r\\ndef getMetric(worker, metric, ckan):\\r\\n    """Function to get metric values.\\r\\n\\r\\n    This function call the function relative to the \\''metric\\''\\r\\n    specified and if the \\''ckan\\'' flag is True we create the body for the\\r\\n    REST request to send to CKAN database to store the sample there;\\r\\n\\r\\n    :param metric: name of the metric analized: \\''Temperature\\'', etc\\r\\n    :param ckan: flag True --> create JSON body for the CKAN request\\r\\n    :return: ckan_data --> JSON data to send as request body to CKAN\\r\\n\\r\\n    """\\r\\n\\r\\n    try:\\r\\n\\r\\n        # Call Sensors Metrics: Temperature(), etc...\\r\\n        # m_value = str(globals()[metric.capitalize()]())\\r\\n        # print globals()[metric.capitalize()]\\r\\n\\r\\n        m_value = getattr(worker, metric.capitalize())()\\r\\n\\r\\n        m_timestamp = datetime.datetime.now().strftime(\\''%Y-%m-%dT%H:%M:%S.%f\\'')\\r\\n\\r\\n        if metric == \\''noise\\'':\\r\\n            LOG.info("SmartME Noise: " + str(m_value) + " amplitude")\\r\\n\\r\\n        elif metric == \\''temperature\\'':\\r\\n            LOG.info("SmartME Temperature " + str(m_value) + u" \\\\u2103")\\r\\n\\r\\n        if ckan:\\r\\n\\r\\n            ckan_data = {}\\r\\n            ckan_data["resource_id"] = str(SENSORS[metric][\\''ckanID\\''])\\r\\n            ckan_data["method"] = "insert"\\r\\n            ckan_data["records"] = []\\r\\n            sample = {}\\r\\n            sample["Latitude"] = location[\\''latitude\\'']\\r\\n            sample["Longitude"] = location[\\''longitude\\'']\\r\\n            sample["Altitude"] = location[\\''altitude\\'']\\r\\n            metric_func_name = metric.capitalize()\\r\\n            sample[metric_func_name] = m_value\\r\\n            sample["Date"] = m_timestamp\\r\\n            ckan_data["records"].append(sample)\\r\\n\\r\\n            ckan_data = json.dumps(ckan_data)\\r\\n\\r\\n        else:\\r\\n            ckan_data = None\\r\\n\\r\\n    except Exception as err:\\r\\n        LOG.error("Error getting metric: " + str(err))\\r\\n\\r\\n\\r\\n    return ckan_data\\r\\n\\r\\n\\r\\ndef getCKANdataset(board_uuid):\\r\\n    """To get CKAN resource IDs for each metric type managed by SmartME boards.\\r\\n\\r\\n    :param board_uuid:\\r\\n    :return:\\r\\n\\r\\n    """\\r\\n\\r\\n    print board_uuid\\r\\n\\r\\n    datasets_url = "http://" + ckan_addr + "/api/rest/dataset/" + board_uuid\\r\\n    print datasets_url\\r\\n    response, datasets = API.sendRequest(url=datasets_url, action=\\''GET\\'')\\r\\n    ckan_data = json.loads(datasets)\\r\\n\\r\\n    for resource in ckan_data[\\''resources\\'']:\\r\\n\\r\\n        # LOG.info(resource[\\''name\\''].capitalize())\\r\\n\\r\\n        if resource[\\''name\\''] in sensors_list:\\r\\n            # LOG.debug(resource[\\''name\\''])\\r\\n            SENSORS[resource[\\''name\\'']][\\''ckanID\\''] = resource[\\''id\\'']\\r\\n            # LOG.info(resource[\\''name\\''] + " - " + resource[\\''id\\''])\\r\\n\\r\\n\\r\\ndef setSensorsLayout(params):\\r\\n    for sensor in sensors_list:\\r\\n        SENSORS[sensor] = {}\\r\\n        SENSORS[sensor][\\''pin\\''] = params[sensor][\\''pin\\'']\\r\\n        SENSORS[sensor][\\''enabled\\''] = params[sensor][\\''enabled\\'']\\r\\n\\r\\n\\r\\ndef InitSmartMeBoard(params):\\r\\n    """This function init the SmartME board.\\r\\n\\r\\n    In the SmartME Arduino YUN board this function enables the needed\\r\\n    devices and set the needed parameters about sensors and location.\\r\\n\\r\\n    :param params: plugin parameters to configure the board.\\r\\n\\r\\n    """\\r\\n\\r\\n    # get location\\r\\n    global location\\r\\n    location = API.getLocation()\\r\\n    LOG.info(\\r\\n        "Board location: \\\\n"\\r\\n        + json.dumps(location, indent=4, separators=(\\'',\\'', \\'': \\''))\\r\\n    )\\r\\n\\r\\n    # set devices\\r\\n    try:\\r\\n\\r\\n        device.EnableI2c()\\r\\n        device.EnableGPIO()\\r\\n\\r\\n    except Exception as err:\\r\\n        LOG.error("Error configuring devices: " + str(err))\\r\\n        global THR_KILL\\r\\n        THR_KILL = False\\r\\n\\r\\n    # set up sensors\\r\\n    setSensorsLayout(params)\\r\\n\\r\\n\\r\\nclass Worker(Plugin.Plugin):\\r\\n\\r\\n    def __init__(self, uuid, name, q_result=None, params=None):\\r\\n        super(Worker, self).__init__(\\r\\n            uuid, name,\\r\\n            q_result=q_result,\\r\\n            params=params\\r\\n        )\\r\\n\\r\\n    def Temperature(self):\\r\\n        """To get Temperature value.\\r\\n\\r\\n        :return: Temperature value (float)\\r\\n\\r\\n        """\\r\\n        try:\\r\\n            voltage = device._readVoltage(SENSORS[\\''temperature\\''][\\''pin\\''])\\r\\n\\r\\n            Rthermistor = float(Rb) * (float(ADCres) / float(voltage) - 1)\\r\\n            rel_temp = float(Beta) / (\\r\\n            math.log(float(Rthermistor) * float(Ginf)))\\r\\n            temp = rel_temp - Kelvin\\r\\n\\r\\n            # LOG.info("Temperature " + str(temp) + u" \\\\u2103")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting temperature: " + str(err))\\r\\n\\r\\n        return temp\\r\\n\\r\\n    def Brightness(self):\\r\\n        """To get Brightness value.\\r\\n\\r\\n        :return: Brightness value (float)\\r\\n\\r\\n        """\\r\\n        try:\\r\\n            voltage = float(device._readVoltage(SENSORS[\\''brightness\\''][\\''pin\\'']))\\r\\n\\r\\n            ldr = (2500 / (5 - voltage * float(0.004887)) - 500) / float(3.3)\\r\\n\\r\\n            LOG.info("SmartME Brightness: " + str(ldr) + " (lux)")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting brightness: " + str(err))\\r\\n\\r\\n        return ldr\\r\\n\\r\\n    def Humidity(self):\\r\\n        """To get Humidity value: this function uses the Temperature sensor too.\\r\\n\\r\\n        :return: Humidity value (float)\\r\\n\\r\\n        """\\r\\n        try:\\r\\n\\r\\n            degCelsius = self.Temperature()\\r\\n            supplyVolt = float(4.64)\\r\\n            HIH4030_Value = float(\\r\\n                device._readVoltage(SENSORS[\\''humidity\\''][\\''pin\\'']))\\r\\n            voltage = HIH4030_Value / float(1023.) * supplyVolt\\r\\n            sensorRH = float(161.0) * float(voltage) / supplyVolt - float(25.8)\\r\\n            relHum = sensorRH / (float(1.0546) - float(0.0026) * degCelsius)\\r\\n\\r\\n            LOG.info("SmartME Humidity " + str(relHum) + " percent")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting humidity: " + str(err))\\r\\n\\r\\n        return relHum\\r\\n\\r\\n    def Pressure(self):\\r\\n        """To get Pressure value.\\r\\n\\r\\n        :return: Pressure value (float)\\r\\n\\r\\n        """\\r\\n        try:\\r\\n\\r\\n            in_pressure_raw = device.i2cRead(\\''pressure\\'')\\r\\n            pressure = float(in_pressure_raw) * float(0.00025) * 10\\r\\n\\r\\n            LOG.info("SmartME Pressure: " + str(pressure) + " hPa")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting pressure: " + str(err))\\r\\n\\r\\n        return pressure\\r\\n\\r\\n    def Noise(self):\\r\\n        """To get Noise value.\\r\\n\\r\\n        Elaborate a noise avarange value from noise listener.\\r\\n\\r\\n        :return: Noise value (float)\\r\\n\\r\\n        """\\r\\n\\r\\n        try:\\r\\n\\r\\n            global amplitudes_sum, amplitudes_count\\r\\n\\r\\n            if amplitudes_count == float(0):\\r\\n                amplitude = float(0)\\r\\n\\r\\n            else:\\r\\n                amplitude = float(amplitudes_sum / amplitudes_count)\\r\\n\\r\\n            amplitudes_sum = 0\\r\\n            amplitudes_count = 0\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting noise: " + str(err))\\r\\n\\r\\n        return amplitude\\r\\n\\r\\n\\r\\n    def run(self):\\r\\n\\r\\n        LOG.info("SmartME plugin starting...")\\r\\n\\r\\n        global THR_KILL\\r\\n        THR_KILL = self._is_running\\r\\n\\r\\n        # Board initialization\\r\\n        LOG.info("PARAMS list: " + str(self.params.keys()))\\r\\n\\r\\n        if len(self.params.keys()) != 0:\\r\\n\\r\\n            InitSmartMeBoard(self.params)\\r\\n\\r\\n            # Get polling time\\r\\n            polling_time = float(self.params[\\''polling\\''])\\r\\n            LOG.info("Polling time: " + str(polling_time))\\r\\n\\r\\n            # GET CKAN SENSORS UUID\\r\\n            getCKANdataset(API.getBoardID())\\r\\n\\r\\n            LOG.info(\\r\\n                "SENSORS: \\\\n"\\r\\n                + json.dumps(SENSORS, indent=4, separators=(\\'',\\'', \\'': \\''))\\r\\n            )\\r\\n\\r\\n            # START NOISE LISTENER if sensor enabled\\r\\n            if SENSORS[\\''noise\\''][\\''enabled\\'']:\\r\\n                LOG.info("Starting noise listening...")\\r\\n                noise_listner()\\r\\n\\r\\n            LOG.info("CKAN enabled: " + str(self.params[\\''ckan_enabled\\'']))\\r\\n\\r\\n            counter = 0\\r\\n\\r\\n            while (self._is_running and THR_KILL):\\r\\n\\r\\n                if sensors_list.__len__() != 0:\\r\\n\\r\\n                    LOG.info("\\\\n\\\\n")\\r\\n\\r\\n                    for sensor in sensors_list:\\r\\n\\r\\n                        if SENSORS[sensor][\\''enabled\\'']:\\r\\n\\r\\n                            if self.params[\\''ckan_enabled\\'']:\\r\\n\\r\\n                                API.sendRequest(\\r\\n                                    url=action_URL,\\r\\n                                    action=\\''POST\\'',\\r\\n                                    headers=headers,\\r\\n                                    body=getMetric(self, sensor, True),\\r\\n                                    verbose=False\\r\\n                                )\\r\\n\\r\\n                            else:\\r\\n                                getMetric(self, sensor, False)\\r\\n\\r\\n                    counter = counter + 1\\r\\n                    LOG.info("SmartME Samples sent: " + str(counter))\\r\\n\\r\\n                    time.sleep(polling_time)\\r\\n\\r\\n                else:\\r\\n                    LOG.warning("No sensors!")\\r\\n                    self._is_running = False\\r\\n                    THR_KILL = self._is_running\\r\\n\\r\\n            # Update the thread status: at this stage THR_KILL will be False\\r\\n            THR_KILL = self._is_running\\r\\n\\r\\n        else:\\r\\n            LOG.error("No parameters provided!")\\r\\n''
.', 0, '{"ckan_enabled": false, "noise": {"enabled": true, "pin": "A4"}, "temperature": {"enabled": true, "pin": "A0"}, "brightness": {"enabled": true, "pin": "A1"}, "gas": {"enabled": true, "pin": "A3"}, "humidity": {"enabled": true, "pin": "A2"}, "pressure": {"enabled": true, "pin": "i2c"}, "polling": "600"}', '{}', '13ae14174aa1424688a75253ef814261');
INSERT INTO iotronic.plugins (created_at, updated_at, id, uuid, name, public, code, callable, parameters, extra, owner) VALUES ('2017-05-03 11:41:29', '2018-05-11 15:45:28', 170, '09b9f21a-fc4d-4bd5-91a0-728a1003e691', 'zero', 1, 'S''# Copyright 2017 MDSLAB - University of Messina\\r\\n#    All Rights Reserved.\\r\\n#    Licensed under the Apache License, Version 2.0 (the "License"); you may\\r\\n#    not use this file except in compliance with the License. You may obtain\\r\\n#    a copy of the License at\\r\\n#\\r\\n#         http://www.apache.org/licenses/LICENSE-2.0\\r\\n#\\r\\n#    Unless required by applicable law or agreed to in writing, software\\r\\n#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\\r\\n#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\\r\\n#    License for the specific language governing permissions and limitations\\r\\n#    under the License.\\r\\n\\r\\nfrom iotronic_lightningrod.plugins import Plugin\\r\\n\\r\\nfrom oslo_log import log as logging\\r\\nLOG = logging.getLogger(__name__)\\r\\n\\r\\n# User imports\\r\\n\\r\\n\\r\\nclass Worker(Plugin.Plugin):\\r\\n\\r\\n    def __init__(self, uuid, name, q_result, params=None):\\r\\n        super(Worker, self).__init__(uuid, name, q_result, params)\\r\\n\\r\\n    def run(self):\\r\\n        LOG.info("Input parameters: " + str(self.params))\\r\\n        LOG.info("Plugin " + self.name + " process completed!")\\r\\n        self.q_result.put("ZERO RESULT")''
.', 1, '{}', '{}', '13ae14174aa1424688a75253ef814261');
INSERT INTO iotronic.plugins (created_at, updated_at, id, uuid, name, public, code, callable, parameters, extra, owner) VALUES ('2017-05-03 14:36:54', '2017-05-03 14:50:53', 171, 'bd4f53ec-caa4-45d9-8161-f3af10739d9a', 'led', 1, 'S''# Copyright 2017 MDSLAB - University of Messina\\r\\n#    All Rights Reserved.\\r\\n#\\r\\n#    Licensed under the Apache License, Version 2.0 (the "License"); you may\\r\\n#    not use this file except in compliance with the License. You may obtain\\r\\n#    a copy of the License at\\r\\n#\\r\\n#         http://www.apache.org/licenses/LICENSE-2.0\\r\\n#\\r\\n#    Unless required by applicable law or agreed to in writing, software\\r\\n#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\\r\\n#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\\r\\n#    License for the specific language governing permissions and limitations\\r\\n#    under the License.\\r\\n\\r\\nfrom iotronic_lightningrod.plugins import Plugin\\r\\nfrom iotronic_lightningrod.plugins import pluginApis as API\\r\\n\\r\\nfrom oslo_log import log as logging\\r\\nLOG = logging.getLogger(__name__)\\r\\n\\r\\n# User imports\\r\\ndevice = API.getBoardGpio()\\r\\n\\r\\nclass Worker(Plugin.Plugin):\\r\\n\\r\\n    def __init__(self, uuid, name, q_result, params=None):\\r\\n        super(Worker, self).__init__(uuid, name, q_result, params)\\r\\n\\r\\n    def run(self):\\r\\n        LOG.info("Input parameters: " + str(self.params))\\r\\n\\r\\n        device._setGPIOs("D13", "out", str(self.params[\\''pin\\'']))\\r\\n\\r\\n        #device.setPIN("D13", self.params[\\''pin\\''])\\r\\n\\r\\n\\r\\n        LOG.info("Plugin " + self.name + " process completed!")\\r\\n        self.q_result.put("Led D13: " + str(self.params[\\''pin\\'']))\\r\\n''
.', 1, '{"pin": 1}', '{}', '13ae14174aa1424688a75253ef814261');
INSERT INTO iotronic.plugins (created_at, updated_at, id, uuid, name, public, code, callable, parameters, extra, owner) VALUES ('2017-05-04 09:30:52', '2017-05-05 07:37:55', 172, '7fe58caa-19fe-4742-81ce-f724ace82ce2', 'monasca-health', 1, 'S''# Copyright 2017 MDSLAB - University of Messina\\r\\n#    All Rights Reserved.\\r\\n#\\r\\n#    Licensed under the Apache License, Version 2.0 (the "License"); you may\\r\\n#    not use this file except in compliance with the License. You may obtain\\r\\n#    a copy of the License at\\r\\n#\\r\\n#         http://www.apache.org/licenses/LICENSE-2.0\\r\\n#\\r\\n#    Unless required by applicable law or agreed to in writing, software\\r\\n#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\\r\\n#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\\r\\n#    License for the specific language governing permissions and limitations\\r\\n#    under the License.\\r\\n\\r\\nfrom iotronic_lightningrod.plugins import Plugin\\r\\nfrom iotronic_lightningrod.plugins import pluginApis as API\\r\\n\\r\\n\\r\\nfrom oslo_log import log as logging\\r\\nLOG = logging.getLogger(__name__)\\r\\n\\r\\n# User imports\\r\\nimport time\\r\\nimport psutil\\r\\n\\r\\n# MONASCA imports and global variables\\r\\nimport monasca_agent.forwarder.api.monasca_api as mon\\r\\nendpoint = None\\r\\nmessage_batch = []\\r\\nimport os\\r\\n\\r\\n\\r\\n\\r\\niotronic_ip = "212.189.207.225"\\r\\nhostname = os.uname()[1]\\r\\n\\r\\n\\r\\n\\r\\ndef sendToMonasca(measure, value):\\r\\n\\r\\n    global message_batch\\r\\n    global endpoint\\r\\n\\r\\n    # SEND TO MONASCA\\r\\n    LOG.debug("Sending metrics to Monasca...")\\r\\n    timestamp = int(time.time()*1000)\\r\\n\\r\\n    try:\\r\\n        msg = [{\\r\\n            \\''tenant_id\\'': None,\\r\\n            \\''measurement\\'':\\r\\n                {\\r\\n                    \\''timestamp\\'': timestamp,\\r\\n                    \\''dimensions\\'': {\\''hostname\\'': str(hostname), },\\r\\n                    \\''name\\'': \\''s4t-\\'' + measure,\\r\\n                    \\''value\\'': value,  # random.uniform(500, 1000),\\r\\n                    \\''value_meta\\'': None\\r\\n                }\\r\\n        }]\\r\\n\\r\\n        message_batch.extend(msg)\\r\\n\\r\\n        endpoint.post_metrics(message_batch)\\r\\n\\r\\n        # LOG.debug("wrote {}".format(len(message_batch)))\\r\\n        message_batch = []\\r\\n\\r\\n\\r\\n    except Exception as e:\\r\\n        LOG.error(\\''Error sending metrics to Monasca: \\'' + str(e))\\r\\n\\r\\n\\r\\nclass Worker(Plugin.Plugin):\\r\\n\\r\\n    def __init__(self, uuid, name, q_result=None, params=None):\\r\\n        super(Worker, self).__init__(uuid, name, q_result, params)\\r\\n\\r\\n    def run(self):\\r\\n\\r\\n        LOG.info("Input parameters: ")\\r\\n        LOG.info(str(self.params))\\r\\n\\r\\n        cpu_list = []\\r\\n\\r\\n        LOG.debug("Monasca API loading....")\\r\\n\\r\\n\\r\\n        agent_config = {\\r\\n            \\''is_enabled\\'': False,\\r\\n            \\''max_measurement_buffer_size\\'': -1,\\r\\n            \\''disable_file_logging\\'': False,\\r\\n            \\''additional_checksd\\'': \\''/usr/lib/monasca/agent/custom_checks.d\\'',\\r\\n            \\''user_domain_name\\'': \\''Default\\'',\\r\\n            \\''use_keystone\\'': True,\\r\\n            \\''num_collector_threads\\'': 1,\\r\\n            \\''statsd_log_file\\'': \\''/var/log/monasca/agent/statsd.log\\'',\\r\\n            \\''syslog_host\\'': None,\\r\\n            \\''keystone_timeout\\'': 20,\\r\\n            \\''max_buffer_size\\'': 1000,\\r\\n            \\''syslog_port\\'': None,\\r\\n            \\''limit_memory_consumption\\'': None,\\r\\n            \\''backlog_send_rate\\'': 1000,\\r\\n            \\''project_domain_id\\'': None,\\r\\n            \\''autorestart\\'': True,\\r\\n            \\''log_level\\'': \\''DEBUG\\'',\\r\\n            \\''collector_restart_interval\\'': 24,\\r\\n            \\''listen_port\\'': None,\\r\\n            \\''check_freq\\'': 30,\\r\\n            \\''hostname\\'': str(hostname),\\r\\n            \\''log_to_syslog\\'': False,\\r\\n            \\''non_local_traffic\\'': False,\\r\\n            \\''version\\'': \\''1.7.0\\'',\\r\\n            \\''service_type\\'': None,\\r\\n            \\''jmxfetch_log_file\\'': \\''/var/log/monasca/agent/jmxfetch.log\\'',\\r\\n            \\''pool_full_max_retries\\'': 4,\\r\\n            \\''project_domain_name\\'': \\''Default\\'',\\r\\n            \\''username\\'': \\''cmm-agent\\'',  # \\''mini-mon\\'',\\r\\n            \\''password\\'': \\''admin\\'',\\r\\n            \\''project_name\\'': \\''boston\\'',\\r\\n            \\''project_id\\'': None,\\r\\n            \\''collector_log_file\\'': \\''/var/log/monasca/agent/collector.log\\'',\\r\\n            \\''region_name\\'': None,\\r\\n            \\''skip_ssl_validation\\'': False,\\r\\n            \\''forwarder_url\\'': \\''http://localhost:17123\\'',\\r\\n            \\''amplifier\\'': 0,\\r\\n            \\''insecure\\'': False,\\r\\n            \\''dimensions\\'': {},\\r\\n            \\''endpoint_type\\'': None,\\r\\n            \\''ca_file\\'': None,\\r\\n            \\''sub_collection_warn\\'': 6,\\r\\n            \\''user_domain_id\\'': None,\\r\\n            \\''url\\'': \\''http://\\'' + iotronic_ip + \\'':8070/v2.0\\'',\\r\\n            \\''keystone_url\\'': \\''http://\\'' + iotronic_ip + \\'':35357/v3\\'',\\r\\n            \\''forwarder_log_file\\'': \\''/var/log/monasca/agent/forwarder.log\\'',\\r\\n            \\''write_timeout\\'': 10,\\r\\n            \\''log_to_event_viewer\\'': False\\r\\n        }\\r\\n\\r\\n        global endpoint\\r\\n        endpoint = mon.MonascaAPI(agent_config)\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n        while(self._is_running):\\r\\n\\r\\n            # CPU\\r\\n            for i in range(5):\\r\\n                cpu_percent = psutil.cpu_percent(interval=1)\\r\\n                cpu_list.append(cpu_percent)\\r\\n                #print cpu_percent\\r\\n\\r\\n            avg_cpu = float (sum(cpu_list) / float(len(cpu_list)) )\\r\\n            LOG.info("AVG CPU: " + str(avg_cpu)+" %")\\r\\n            sendToMonasca("cpu", avg_cpu)\\r\\n            cpu_list = []\\r\\n\\r\\n            # MEMORY\\r\\n            mem = psutil.virtual_memory()\\r\\n            LOG.info("MEM: " + str(mem.percent)+" % \\\\n\\\\n")\\r\\n            sendToMonasca("mem_p", mem.percent)\\r\\n            \\r\\n\\r\\n            time.sleep(10)\\r\\n''
.', 0, '{}', '{}', '13ae14174aa1424688a75253ef814261');
INSERT INTO iotronic.plugins (created_at, updated_at, id, uuid, name, public, code, callable, parameters, extra, owner) VALUES ('2017-05-06 10:13:40', '2017-05-09 21:17:23', 174, '71c39ff5-75ef-4ed0-ac35-a9cfca20ab2a', 'monascaV2', 1, 'S''# Copyright 2017 MDSLAB - University of Messina\\r\\n#    All Rights Reserved.\\r\\n#\\r\\n#    Licensed under the Apache License, Version 2.0 (the "License"); you may\\r\\n#    not use this file except in compliance with the License. You may obtain\\r\\n#    a copy of the License at\\r\\n#\\r\\n#         http://www.apache.org/licenses/LICENSE-2.0\\r\\n#\\r\\n#    Unless required by applicable law or agreed to in writing, software\\r\\n#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\\r\\n#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\\r\\n#    License for the specific language governing permissions and limitations\\r\\n#    under the License.\\r\\n\\r\\nfrom iotronic_lightningrod.plugins import Plugin\\r\\nfrom iotronic_lightningrod.plugins import pluginApis as API\\r\\n\\r\\n\\r\\n\\r\\n\\r\\nfrom oslo_log import log as logging\\r\\nLOG = logging.getLogger(__name__)\\r\\n\\r\\n# User imports\\r\\nimport json\\r\\nimport math\\r\\nimport time\\r\\nimport threading\\r\\nimport requests\\r\\n\\r\\n\\r\\n# MONASCA imports and global variables\\r\\nimport monasca_agent.forwarder.api.monasca_api as mon\\r\\nmessage_batch = []\\r\\nimport os\\r\\n\\r\\n\\r\\n\\r\\n# User global variables\\r\\n\\r\\nsensors_list = [\\r\\n    \\''temperature\\'',\\r\\n    \\''brightness\\''\\r\\n]\\r\\nposition = None\\r\\nSENSORS = {}\\r\\nlocation = {}\\r\\nTHR_KILL = None\\r\\niotronic_ip = "212.189.207.225"\\r\\nhostname = os.uname()[1]\\r\\ndevice = API.getBoardGpio()\\r\\n\\r\\n# IoTronic client management\\r\\nfrom iotronicclient import client\\r\\nfrom keystoneauth1.identity import v3\\r\\nfrom keystoneauth1 import session\\r\\nauth = v3.Password(auth_url=\\''http://\\''+iotronic_ip+\\'':35357/v3\\'',\\r\\n                   username=\\''admin\\'',\\r\\n                   password=\\''B0st0nc3rb3rus!\\'',\\r\\n                   project_name=\\''boston\\'',\\r\\n                   user_domain_id="default", project_domain_id="default"\\r\\n                   )\\r\\nsess = session.Session(auth=auth)\\r\\niotronic = client.get_client("1",session=sess)\\r\\n\\r\\nALERT = False\\r\\n\\r\\n\\r\\n\\r\\n# Sensors global parameters\\r\\n# - Temperature Parameters\\r\\nADCres = 1023.0\\r\\nBeta = 3950\\r\\nKelvin = 273.15\\r\\nRb = 10000\\r\\nGinf = 120.6685\\r\\nlatest_temp = None\\r\\n\\r\\n\\r\\ndef gettoken(user,psw,project):\\r\\n    url_k = "http://"+iotronic_ip+":35357/v3/auth/tokens"\\r\\n    payload={"auth": {\\r\\n        "identity": {\\r\\n            "methods": ["password"],\\r\\n            "password": {\\r\\n                "user": {\\r\\n                    "name": user,\\r\\n                    "domain": {"id": "default"},\\r\\n                    "password": [REDACTED]                }\\r\\n            }\\r\\n        },\\r\\n        "scope": {\\r\\n            "project": {\\r\\n                "name": project,\\r\\n                "domain": {"id": "default"}\\r\\n            }\\r\\n        }\\r\\n    }\\r\\n    }\\r\\n    \\r\\n    headers = {\\r\\n    \\''content-type\\'': "application/json",\\r\\n    \\''cache-control\\'': "no-cache",\\r\\n    }\\r\\n\\r\\n    r = requests.request("POST", url_k, data=json.dumps(payload), headers=headers)\\r\\n    token = r.headers[\\''X-Subject-Token\\'']\\r\\n    return token\\r\\n\\r\\n\\r\\ndef sendmonasca(board_name,lat,lon,values):\\r\\n    url_m = "http://"+iotronic_ip+":5607/v3.0/logs"\\r\\n\\r\\n    payload = {\\r\\n        "dimensions":{\\r\\n            "hostname":board_name,\\r\\n            "service":"sensors",\\r\\n            "lat":lat,\\r\\n            "long":lon\\r\\n        },\\r\\n        "logs": values\\r\\n    }\\r\\n    \\r\\n    \\r\\n    headers = {\\r\\n    \\''x-auth-token\\'': gettoken("cmm-agent","admin","boston"),\\r\\n    \\''content-type\\'': "application/json",\\r\\n    \\''cache-control\\'': "no-cache"\\r\\n    }\\r\\n    \\r\\n    response = requests.request("POST", url_m, data=json.dumps(payload), headers=headers)\\r\\n    LOG.info(str(response))\\r\\n\\r\\ndef set_val(temp,bri):\\r\\n    values=[{\\r\\n            "message":temp,\\r\\n            "dimensions":{\\r\\n                    "meter":"temperature",\\r\\n                    "component":"iotronic",\\r\\n                    "path":"/var/log/iotronic-lightining-rod.log",\\r\\n                    "log_level":"Info"\\r\\n                }\\r\\n            },\\r\\n                {\\r\\n                "message":bri,\\r\\n                "dimensions":{\\r\\n                    "meter":"brightness",\\r\\n                    "component":"iotronic",\\r\\n                    "path":"/var/log/iotronic-lightining-rod.log",\\r\\n                    "log_level":"Info"\\r\\n                }\\r\\n            }\\r\\n        ]\\r\\n    return values\\r\\n\\r\\n\\r\\ndef getMonascaMetric(metric, worker):\\r\\n\\r\\n    # Call Sensors Metrics: Temperature(), etc...\\r\\n    #m_value = str(globals()[metric.capitalize()]())\\r\\n    #print globals()[metric.capitalize()]\\r\\n\\r\\n    m_value = getattr(worker, metric.capitalize())()\\r\\n\\r\\n    #m_timestamp = datetime.datetime.now().strftime(\\''%Y-%m-%dT%H:%M:%S.%f\\'')\\r\\n    m_timestamp = int(time.time()*1000)\\r\\n\\r\\n    if metric == \\''temperature\\'':\\r\\n        LOG.info("Monasca Temperature " + str(m_value) + u" \\\\u2103")\\r\\n\\r\\n    data = {}\\r\\n    data[metric.capitalize()] = m_value\\r\\n    data["Date"] = str(m_timestamp)\\r\\n    data = json.dumps(data)\\r\\n\\r\\n    return data\\r\\n\\r\\n\\r\\ndef setSensorsLayout(params):\\r\\n    for sensor in sensors_list:\\r\\n        SENSORS[sensor] = {}\\r\\n        SENSORS[sensor][\\''pin\\''] = params[sensor][\\''pin\\'']\\r\\n        SENSORS[sensor][\\''enabled\\''] = params[sensor][\\''enabled\\'']\\r\\n\\r\\n\\r\\ndef InitSmartMeBoard(params):\\r\\n    """This function init the SmartME board.\\r\\n\\r\\n    In the SmartME Arduino YUN board this function enables the needed\\r\\n    devices and set the needed parameters about sensors and location.\\r\\n\\r\\n    :param params: plugin parameters to configure the board.\\r\\n\\r\\n    """\\r\\n\\r\\n    # get location\\r\\n    global location\\r\\n    location = API.getLocation()\\r\\n    LOG.info(\\r\\n        "Board location: \\\\n"\\r\\n        + json.dumps(location, indent=4, separators=(\\'',\\'', \\'': \\''))\\r\\n    )\\r\\n\\r\\n    # set devices\\r\\n    try:\\r\\n\\r\\n        global ALERT\\r\\n        if not ALERT:\\r\\n            device.EnableGPIO()\\r\\n\\r\\n    except Exception as err:\\r\\n        LOG.error("Error configuring devices: " + str(err))\\r\\n        global THR_KILL\\r\\n        THR_KILL = False\\r\\n\\r\\n\\r\\n    # set up sensors\\r\\n    setSensorsLayout(params)\\r\\n\\r\\n\\r\\ndef iotronicCall(board, params):\\r\\n    """thread worker function"""\\r\\n    try:\\r\\n        iotronic.plugin_injection.plugin_action(board.uuid, \\''71c39ff5-75ef-4ed0-ac35-a9cfca20ab2a\\'', \\''PluginReboot\\'', params)\\r\\n    except Exception as err:\\r\\n        LOG.error("RPC request error for board "+board.uuid+": " + str(err))\\r\\n\\r\\n    return\\r\\n\\r\\n\\r\\nclass Worker(Plugin.Plugin):\\r\\n\\r\\n    def __init__(self, uuid, name, q_result=None, params=None):\\r\\n        super(Worker, self).__init__(\\r\\n            uuid, name,\\r\\n            q_result=q_result,\\r\\n            params=params\\r\\n        )\\r\\n\\r\\n    def Brightness(self):\\r\\n\\r\\n        try:\\r\\n            voltage = float(device._readVoltage(SENSORS[\\''brightness\\''][\\''pin\\'']))\\r\\n\\r\\n            ldr = (2500 / (5 - voltage * float(0.004887)) - 500) / float(3.3)\\r\\n\\r\\n            LOG.info("Monasca Brightness: " + str(ldr) + " (lux)")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting Monasca brightness: " + str(err))\\r\\n\\r\\n        return ldr\\r\\n\\r\\n    def Temperature(self):\\r\\n\\r\\n        try:\\r\\n            voltage = device._readVoltage(SENSORS[\\''temperature\\''][\\''pin\\''])\\r\\n\\r\\n            Rthermistor = float(Rb) * (float(ADCres) / float(voltage) - 1)\\r\\n            rel_temp = float(Beta) / (\\r\\n            math.log(float(Rthermistor) * float(Ginf)))\\r\\n            temp = rel_temp - Kelvin\\r\\n\\r\\n            # LOG.info("Temperature " + str(temp) + u" \\\\u2103")\\r\\n\\r\\n        except Exception as err:\\r\\n            LOG.error("Error getting Monasca temperature: " + str(err))\\r\\n\\r\\n        return temp\\r\\n\\r\\n    def run(self):\\r\\n\\r\\n        LOG.info("Monasca plugin starting...")\\r\\n\\r\\n        global ALERT\\r\\n\\r\\n        global THR_KILL\\r\\n        THR_KILL = self._is_running\\r\\n\\r\\n        # Board initialization\\r\\n        LOG.info("PARAMS list: " + str(self.params.keys()))\\r\\n\\r\\n        LOG.debug("Monasca API loading....")\\r\\n        global message_batch\\r\\n\\r\\n        agent_config = {\\r\\n            \\''is_enabled\\'': False,\\r\\n            \\''max_measurement_buffer_size\\'': -1,\\r\\n            \\''disable_file_logging\\'': False,\\r\\n            \\''additional_checksd\\'': \\''/usr/lib/monasca/agent/custom_checks.d\\'',\\r\\n            \\''user_domain_name\\'': \\''Default\\'',\\r\\n            \\''use_keystone\\'': True,\\r\\n            \\''num_collector_threads\\'': 1,\\r\\n            \\''statsd_log_file\\'': \\''/var/log/monasca/agent/statsd.log\\'',\\r\\n            \\''syslog_host\\'': None,\\r\\n            \\''keystone_timeout\\'': 20,\\r\\n            \\''max_buffer_size\\'': 1000,\\r\\n            \\''syslog_port\\'': None,\\r\\n            \\''limit_memory_consumption\\'': None,\\r\\n            \\''backlog_send_rate\\'': 1000,\\r\\n            \\''project_domain_id\\'': None,\\r\\n            \\''autorestart\\'': True,\\r\\n            \\''log_level\\'': \\''DEBUG\\'',\\r\\n            \\''collector_restart_interval\\'': 24,\\r\\n            \\''listen_port\\'': None,\\r\\n            \\''check_freq\\'': 30,\\r\\n            \\''hostname\\'': str(hostname),\\r\\n            \\''log_to_syslog\\'': False,\\r\\n            \\''non_local_traffic\\'': False,\\r\\n            \\''version\\'': \\''1.7.0\\'',\\r\\n            \\''service_type\\'': None,\\r\\n            \\''jmxfetch_log_file\\'': \\''/var/log/monasca/agent/jmxfetch.log\\'',\\r\\n            \\''pool_full_max_retries\\'': 4,\\r\\n            \\''project_domain_name\\'': \\''Default\\'',\\r\\n            \\''username\\'': \\''cmm-agent\\'',\\r\\n            \\''password\\'': \\''admin\\'',\\r\\n            \\''project_name\\'': \\''boston\\'',\\r\\n            \\''project_id\\'': None,\\r\\n            \\''collector_log_file\\'': \\''/var/log/monasca/agent/collector.log\\'',\\r\\n            \\''region_name\\'': None,\\r\\n            \\''skip_ssl_validation\\'': False,\\r\\n            \\''forwarder_url\\'': \\''http://localhost:17123\\'',\\r\\n            \\''amplifier\\'': 0,\\r\\n            \\''insecure\\'': False,\\r\\n            \\''dimensions\\'': {},\\r\\n            \\''endpoint_type\\'': None,\\r\\n            \\''ca_file\\'': None,\\r\\n            \\''sub_collection_warn\\'': 6,\\r\\n            \\''user_domain_id\\'': None,\\r\\n            \\''url\\'': \\''http://\\''+ iotronic_ip +\\'':8070/v2.0\\'',\\r\\n            \\''keystone_url\\'': \\''http://\\''+ iotronic_ip +\\'':35357/v3\\'',\\r\\n            \\''forwarder_log_file\\'': \\''/var/log/monasca/agent/forwarder.log\\'',\\r\\n            \\''write_timeout\\'': 10,\\r\\n            \\''log_to_event_viewer\\'': False\\r\\n        }\\r\\n\\r\\n        endpoint = mon.MonascaAPI(agent_config)\\r\\n\\r\\n\\r\\n        if len(self.params.keys()) != 0:\\r\\n\\r\\n            InitSmartMeBoard(self.params)\\r\\n            \\r\\n            # Get trigger measure\\r\\n            trigger = str(self.params[\\''trigger\\''])\\r\\n            LOG.info("Trigger measure: " + str(trigger))\\r\\n\\r\\n            # Get polling time\\r\\n            polling_time = float(self.params[\\''polling\\''])\\r\\n            LOG.info("Polling time: " + str(polling_time))\\r\\n\\r\\n            # Get threshold\\r\\n            threshold = float(self.params[\\''threshold\\''])\\r\\n            \\r\\n            if trigger == "temperature":\\r\\n                LOG.info("Threshold: " + str(threshold) + u" \\\\u2103")\\r\\n            elif trigger == "brightness":\\r\\n                LOG.info("Threshold: " + str(threshold) + " lux")\\r\\n            else:\\r\\n                LOG.error("WRONG metric specified!")\\r\\n                self._is_running = False\\r\\n                THR_KILL = self._is_running\\r\\n                \\r\\n            \\r\\n\\r\\n\\r\\n            LOG.info(\\r\\n                "SENSORS: \\\\n"\\r\\n                + json.dumps(SENSORS, indent=4, separators=(\\'',\\'', \\'': \\''))\\r\\n            )\\r\\n\\r\\n            counter = 0\\r\\n\\r\\n\\r\\n\\r\\n            while (self._is_running and THR_KILL):\\r\\n\\r\\n                # TURN OFF notification LED\\r\\n                device._setGPIOs("D13", "out", "1")\\r\\n\\r\\n                if sensors_list.__len__() != 0:\\r\\n                    \\r\\n                    lm={"Temperature":"","Brightness":""}\\r\\n\\r\\n                    # Get metrics\\r\\n                    for sensor in sensors_list:\\r\\n\\r\\n                        if SENSORS[sensor][\\''enabled\\'']:\\r\\n\\r\\n                            try:\\r\\n\\r\\n                                measure = json.loads(getMonascaMetric(sensor, self))\\r\\n\\r\\n                                if sensor == trigger:\\r\\n\\r\\n                                    value = measure[trigger.capitalize()]\\r\\n                                    lm[sensor.capitalize()]=str(value)\\r\\n\\r\\n                                    # Check threshold\\r\\n                                    if float(value) >= float(threshold):\\r\\n\\r\\n                                        LOG.warning("ALERT - "+trigger.capitalize()+" over threshold!")\\r\\n\\r\\n                                        polling_time = 5\\r\\n\\r\\n                                        if not ALERT:\\r\\n\\r\\n                                            ALERT = True\\r\\n\\r\\n                                            boards_list = iotronic.board.list()\\r\\n                                            #print boards_list\\r\\n\\r\\n                                            for board in boards_list:\\r\\n\\r\\n                                                if board.uuid != API.getBoardID():\\r\\n\\r\\n                                                    if str(board.status) == "online":\\r\\n\\r\\n                                                        params = {\\r\\n                                                            "polling": polling_time,\\r\\n                                                            "threshold": threshold,\\r\\n                                                            "trigger": trigger,\\r\\n                                                            "ckan_enabled": False,\\r\\n                                                            "temperature": {\\r\\n                                                                "pin": "A0",\\r\\n                                                                "enabled": True\\r\\n                                                            },\\r\\n                                                            "brightness": {\\r\\n                                                                "pin": "A1",\\r\\n                                                                "enabled": True\\r\\n                                                            }\\r\\n                                                        }\\r\\n\\r\\n                                                        try:\\r\\n                                                            LOG.info("Rebooting Monasca plugin for board " + board.uuid)\\r\\n\\r\\n                                                            t = threading.Thread(\\r\\n                                                                target=iotronicCall,\\r\\n                                                                args=(board, params, ))\\r\\n                                                            t.start()\\r\\n\\r\\n                                                        except Exception as err:\\r\\n                                                            message = "RPC request expired for board " + board.uuid\\r\\n                                                            LOG.warning(" - " + message)\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n                                    else:\\r\\n\\r\\n                                        polling_time = float(self.params[\\''polling\\''])\\r\\n\\r\\n                                        if ALERT is True:\\r\\n\\r\\n                                            LOG.warning("ALERT - "+trigger.capitalize()+" under threshold!")\\r\\n\\r\\n                                            ALERT = False\\r\\n\\r\\n                                            try:\\r\\n\\r\\n                                                boards_list = iotronic.board.list()\\r\\n\\r\\n                                                for board in boards_list:\\r\\n\\r\\n                                                    if board.uuid != API.getBoardID():\\r\\n\\r\\n                                                        if str(board.status) == "online":\\r\\n\\r\\n                                                            params = {\\r\\n                                                                "polling": polling_time,\\r\\n                                                                "threshold": threshold,\\r\\n                                                                "trigger": trigger,\\r\\n                                                                "ckan_enabled": False,\\r\\n                                                                "temperature": {\\r\\n                                                                    "pin": "A0",\\r\\n                                                                    "enabled": True\\r\\n                                                                },\\r\\n                                                                "brightness": {\\r\\n                                                                    "pin": "A1",\\r\\n                                                                    "enabled": True\\r\\n                                                                }\\r\\n                                                            }\\r\\n\\r\\n                                                            try:\\r\\n                                                                LOG.info("Rebooting Monasca plugin for board " + board.uuid)\\r\\n\\r\\n                                                                t = threading.Thread(\\r\\n                                                                    target=iotronicCall,\\r\\n                                                                    args=(board,params,))\\r\\n                                                                t.start()\\r\\n\\r\\n                                                            except Exception as err:\\r\\n                                                                message = "Error executing Iotronic Client for board: " + board.uuid\\r\\n                                                                LOG.warning(" - " + message)\\r\\n\\r\\n                                            except Exception as err:\\r\\n                                                message = "Error resetting alarms: " + str(err)\\r\\n                                                LOG.warning(" - " + message)\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n                                else:\\r\\n                                    value = measure[sensor.capitalize()]\\r\\n                                    lm[sensor.capitalize()]=str(value)\\r\\n\\r\\n\\r\\n                                timestamp = measure[\\''Date\\'']\\r\\n\\r\\n                                LOG.debug(" - " + sensor + ": " + str(value) + " -  time: " + timestamp)\\r\\n\\r\\n                                # SEND TO MONASCA\\r\\n                                """\\r\\n                                \\''location\\'':{\\r\\n                                   "key": str(hostname),\\r\\n                                   "latitude": location[\\''latitude\\''],\\r\\n                                   "longitude": location[\\''longitude\\''],\\r\\n                                   "name": str(hostname)\\r\\n                                }\\r\\n                                """\\r\\n                                LOG.debug("Sending metrics to Monasca...")\\r\\n                                try:\\r\\n\\r\\n                                    msg = [{\\r\\n                                        \\''tenant_id\\'': None,\\r\\n                                        \\''measurement\\'':\\r\\n                                            {\\r\\n                                                \\''timestamp\\'': timestamp,\\r\\n                                                \\''dimensions\\'': {\\''hostname\\'': str(hostname), },\\r\\n                                                \\''name\\'': \\''s4t-\\'' + sensor,\\r\\n                                                \\''value\\'': value,\\r\\n                                                \\''value_meta\\'': None\\r\\n\\r\\n                                            }\\r\\n                                    }]\\r\\n\\r\\n                                    message_batch.extend(msg)\\r\\n\\r\\n                                    endpoint.post_metrics(message_batch)\\r\\n\\r\\n                                    message_batch = []\\r\\n\\r\\n\\r\\n                                except Exception as e :\\r\\n                                    LOG.error(\\''Error sending metrics to Monasca: \\'' + str(e))\\r\\n\\r\\n\\r\\n\\r\\n                            except Exception as err:\\r\\n                                message = "Error reading metrics: " + str(err)\\r\\n                                LOG.warning(" - " + message)\\r\\n\\r\\n\\r\\n                    counter = counter + 1\\r\\n                    LOG.info("Monasca Sample number: " + str(counter) + "\\\\n\\\\n")\\r\\n                    \\r\\n                    try:\\r\\n                        global location\\r\\n                        sendmonasca(str(hostname),\\r\\n                                    location[\\''latitude\\''],\\r\\n                                    location[\\''longitude\\''],\\r\\n                                    set_val(lm[\\''Temperature\\''],\\r\\n                                            lm[\\''Brightness\\'']))\\r\\n                        \\r\\n                        \\r\\n                    except Exception as e :\\r\\n                        LOG.error(\\''Error sending LOGS to Monasca: \\'' + str(e))\\r\\n\\r\\n                    # TURN ON notification LED\\r\\n                    device._setGPIOs("D13", "out", "0")\\r\\n\\r\\n                    time.sleep(polling_time)\\r\\n\\r\\n\\r\\n\\r\\n                else:\\r\\n                    LOG.warning("No sensors!")\\r\\n                    self._is_running = False\\r\\n                    THR_KILL = self._is_running\\r\\n\\r\\n            # Update the thread status: at this stage THR_KILL will be False\\r\\n            THR_KILL = self._is_running\\r\\n\\r\\n        else:\\r\\n            LOG.error("No parameters provided!")''
.', 0, '{}', '{}', '13ae14174aa1424688a75253ef814261');
INSERT INTO iotronic.plugins (created_at, updated_at, id, uuid, name, public, code, callable, parameters, extra, owner) VALUES ('2018-01-22 17:32:42', null, 178, '16ebebc9-8746-4654-9218-e54ed161d052', 'runner', 1, 'V# Copyright 2017 MDSLAB - University of Messina
\\u000a#    All Rights Reserved.
\\u000a#
\\u000a#    Licensed under the Apache License, Version 2.0 (the "License"); you may
\\u000a#    not use this file except in compliance with the License. You may obtain
\\u000a#    a copy of the License at
\\u000a#
\\u000a#         http://www.apache.org/licenses/LICENSE-2.0
\\u000a#
\\u000a#    Unless required by applicable law or agreed to in writing, software
\\u000a#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
\\u000a#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
\\u000a#    License for the specific language governing permissions and limitations
\\u000a#    under the License.
\\u000a
\\u000afrom iotronic_lightningrod.plugins import Plugin
\\u000afrom iotronic_lightningrod.plugins import pluginApis as API
\\u000a
\\u000afrom oslo_log import log as logging
\\u000aLOG = logging.getLogger(__name__)
\\u000a
\\u000a# User imports
\\u000aimport time
\\u000a
\\u000a
\\u000aclass Worker(Plugin.Plugin):
\\u000a    def __init__(self, uuid, name, q_result=None, params=None):
\\u000a        super(Worker, self).__init__(uuid, name, q_result, params)
\\u000a
\\u000a    def run(self):
\\u000a        LOG.info("Plugin " + self.name + " starting...")
\\u000a        LOG.info(self.params)
\\u000a
\\u000a        while(self._is_running):
\\u000a            LOG.info(self.params[''message''])
\\u000a            time.sleep(1)
\\u000a
p1
.', 0, '{"message": "Hello!"}', '{}', '13ae14174aa1424688a75253ef814261');
INSERT INTO iotronic.services (created_at, updated_at, id, uuid, name, port, project, protocol, extra) VALUES ('2018-02-12 10:48:09', '2018-07-04 11:18:48', 2, 'bf3b1dc4-01b5-4b7e-9731-025c1e2ab285', 'ssh', 22, '3c1e2e2c4bac40da9b4b1d694da6e2a1', 'TCP', '{}');
INSERT INTO iotronic.services (created_at, updated_at, id, uuid, name, port, project, protocol, extra) VALUES ('2018-07-06 10:14:28', null, 9, 'bd0c8361-e158-4e9a-a2be-386934c16cbd', 'web', 80, '3c1e2e2c4bac40da9b4b1d694da6e2a1', 'TCP', '{}');
INSERT INTO iotronic.services (created_at, updated_at, id, uuid, name, port, project, protocol, extra) VALUES ('2018-07-06 10:14:41', null, 10, '436db267-95a7-4563-8538-bd67f32dcaa4', 'web_ssl', 443, '3c1e2e2c4bac40da9b4b1d694da6e2a1', 'TCP', '{}');
INSERT INTO iotronic.services (created_at, updated_at, id, uuid, name, port, project, protocol, extra) VALUES ('2018-07-06 10:14:58', null, 11, '3914d4ce-c60a-4c51-8e1c-3859e815f540', 'node-red', 1880, '3c1e2e2c4bac40da9b4b1d694da6e2a1', 'TCP', '{}');
INSERT INTO iotronic.services (created_at, updated_at, id, uuid, name, port, project, protocol, extra) VALUES ('2018-07-10 09:26:52', null, 12, '83241b45-c9f8-4884-b162-b83132c2fe38', 'shellinabox', 4200, '3c1e2e2c4bac40da9b4b1d694da6e2a1', 'TCP', '{}');
INSERT INTO iotronic.wampagents (created_at, updated_at, id, hostname, wsurl, online, ragent) VALUES ('2017-03-30 10:28:30', '2018-07-10 09:32:39', 6, 'wagent1', 'wss://192.168.17.103:8181/', 1, 1);
INSERT INTO iotronic.wampagents (created_at, updated_at, id, hostname, wsurl, online, ragent) VALUES ('2017-04-28 14:49:20', '2018-07-26 10:49:12', 8, 'wagent2', 'wss://192.168.17.104:8181/', 1, 0);
INSERT INTO iotronic.wampagents (created_at, updated_at, id, hostname, wsurl, online, ragent) VALUES ('2018-02-22 12:07:28', '2018-07-06 10:23:50', 10, 'wagent3', 'wss://192.168.17.105:8181/', 1, 0);
INSERT INTO iotronic.wampagents (created_at, updated_at, id, hostname, wsurl, online, ragent) VALUES ('2018-02-22 12:07:28', '2018-07-06 10:25:44', 11, 'wagent4', 'wss://192.168.17.106:8181/', 1, 0);
SET FOREIGN_KEY_CHECKS=1;