Esempio n. 1
0
 def init_sensors(self):
     """
     Initializes and connects to the sensors of this hub
     @return: A list of active sensors that can be interfaced with
     """
     for sensor in self.config.items('sensors'):
         self.sensors.append(self.sensor_factory.get_sensor_instance(sensor[0], self.config))
         log_to_console("Initialized sensor: " + sensor[0])
Esempio n. 2
0
 def get_sensor_data(self, sensor):
     end_time = dt.utcnow()
     start_time = dt.utcfromtimestamp(sensor.last_updated)
     measurements = sensor.get_all_measurements(start_time, end_time)
     if measurements:
         log_str = 'Caching measurements for ' + sensor.name
         log_to_console(log_str)
         if caching.cache_measurements(sensor, measurements, self):
             self.config.set(sensor.name, 'last_update', sensor.last_updated)
             self.config_write()
     return measurements
Esempio n. 3
0
    def post_file(self, file_to_post, username, password, server_url=None, token=None):
        """
        Tries to authenticate based on username/password if token is not provided.
        Posts provided file to API. THROES EXCEPTION! Must be handled!
        """

        if not server_url:
            log_to_console("No server_url provided")
            raise requests.ConnectionError

        # If no token is given, username and password is needed to provide new token
        if not token:
            token = self.authenticate(username, password, server_url)

        with open(file_to_post) as json_file:

            # Get the json data from file
            payload = json.load(json_file)

            # url = "http://127.0.0.1:8000/post-measurements/" # Remember trailing slash
            url = server_url + "post-measurements/"

            log_to_console("Posting to " + url)

            headers = {"content-type": "application/json", "Authorization": "Token " + token}

            r = requests.post(url, data=json.dumps(payload), headers=headers)

            log_to_console("Status_code " + str(r.status_code))
            log_to_console("Response " + r.text)

            self.raise_exception_if_bad_request(r)

        return token
Esempio n. 4
0
def check_configuration():
    os.chdir(os.path.dirname(__file__))
    cache_path = "../../cache"
    res_path = "../../res"
    for path in [res_path, cache_path]:
        if not os.path.isdir(path):
            os.makedirs(path)
    os.chdir(res_path)
    config = ConfigParser.RawConfigParser()
    if not os.path.exists(__config_file__):
        log_to_console('No config file, making it')
        create_new_config_file(__config_file__)

    else:
        config.read(__config_file__)
        for section in ['hub', 'sensors']:
            if not config.has_section(section):
                log_to_console('Config file corrupted, please reconfigure it')
                create_new_config_file(__config_file__)
                break
        config.read(__config_file__)
        options = ['hub_id', 'password', 'last_update', 'server_url', 'server_interval',
                   'server_wait', 'token']
        missing_options = [option for option in config.items('hub') if option[0] not in options]
        if missing_options:
            log_to_console('missing: ' + str(missing_options))
            log_to_console('Config file corrupted, please reconfigure it')
            create_new_config_file(__config_file__)
        config.read(__config_file__)
    config.read(__config_file__)
    return True
Esempio n. 5
0
def write_measurements_to_file(sensor, measurements, hub):
    max_date = sensor.last_updated
    for m in measurements:
        max_date = max(max_date, m['date'])
    sensor.last_updated = max_date
    new_measurements = get_new_measurements(sensor, measurements)
    if not new_measurements:
        log_to_console("No new measurements")
        return False
    utc_now = int(calendar.timegm(dt.utcnow().timetuple()))
    filename = __filepath__ + str(utc_now) + "_" + sensor.name + ".json"
    f = open(filename, 'w')
    measurement_dictionary = {'Observation': {'hub_id': hub.hub_id},
                              'Measurements': new_measurements}
    json.dump(measurement_dictionary, f, indent=4, sort_keys=True)
    f.close()
    return True
Esempio n. 6
0
    def authenticate(self, username, password, server_url):
        """
        Tries to authenticate the hub based on username and password. Raises exception if response
        status code is not 2xx. I.e username or password is wrong or serverside error.
        """

        # url = "http://127.0.0.1:8000/api-token-auth/" # Remember trailing slash
        url = server_url + "api-token-auth/"

        log_to_console("Authenticating to " + url)

        headers = {"content-type": "application/json"}

        r = requests.post(url, data=json.dumps({"username": username, "password": password}), headers=headers)

        log_to_console("Status_code " + str(r.status_code))

        self.raise_exception_if_bad_request(r)
        parsed_response = json.loads(r.text)

        return parsed_response["token"]
Esempio n. 7
0
 def add_sensor(self, name, sensor_type, mac_address=None):
     """
     Takes a mac adress and a name and adds it to the list of sensors of this hub
     @param name: The name of the sensor
     @param sensor_type: The type of sensor
     @param mac_address: The MAC address of the sensor
     @return: True if sensor was successfully added to the list, false otherwise
     """
     log_str = "Adding sensor: " + name + ", type: " + sensor_type + ', MAC address: ' + str(
         mac_address)
     log_to_console(log_str)
     if not [s for s in self.sensors if s.name == name]:
         self.config.set('sensors', name, sensor_type)
         self.config.add_section(name)
         self.config.set(name, 'type', sensor_type)
         self.config.set(name, 'mac_address', mac_address)
         self.config.set(name, 'last_update', int(calendar.timegm(dt.utcnow().timetuple())))
         self.config_write()
         self.sensors.append(self.sensor_factory.get_sensor_instance(name, self.config))
     else:
         log_to_console("A sensor with that name already exists")
Esempio n. 8
0
def send_data_to_server():
    filenames = caching.get_old_measurements(hub.last_updated)

    if not filenames:
        log_to_console("Nothing to send...")

    token = hub.token
    server_url = hub.server_url
    try:
        for filename in filenames:
            log_str = "sending file: \"" + filename + "\" to server"

            log_to_console(log_str)

            new_token = hub.json_posting.post_file(filename, hub.hub_id, hub.password,
                                                   server_url=server_url, token=token)

            if new_token != token:
                set_token(new_token)

        # Update last updated in config file
        timestamp = calendar.timegm(dt.utcnow().timetuple())
        hub.last_updated = timestamp
        hub.config.set('hub', 'last_update', timestamp)
        hub.config_write()

    # Only catching exceptions thrown by requests
    except HTTPError as e:
        # Ignore
        log_to_console(format_exc())

        # Handle 401 unauthorized, probably because token is outdated.
        # Delete it, effectively forcing a new authentication.
        if e.response.status_code == 401:
            log_to_console("Deleting token...")

            set_token("")

    except ConnectionError:
        # Ignore
        log_to_console(format_exc())

    except Timeout:
        # Ignore
        log_to_console(format_exc())

    except TooManyRedirects:
        # Ignore
        log_to_console(format_exc())

    except RequestException:  # Fallback if none of the above is caught
        # Ignore
        log_to_console(format_exc())
Esempio n. 9
0
def check_for_sensors(a_hub):
    if not a_hub.sensors:
        log_to_console('No sensors found, please add a sensor')
        sensor_name = raw_input('Sensor name: ').lower()
        sensor_type = raw_input('Sensor type: ')
        a_hub.add_sensor(sensor_name, sensor_type)