def handle_scheduler_response(self, topic, headers, message, match): msg = jsonapi.loads(message[0]) response_type = headers.get('type', 0) if response_type == 'NEW_SCHEDULE': if msg.get('result', 0) == 'SUCCESS': self.logger.write("Schedule Successful") self.ready = True
def on_outside_temp(self, topic, headers, message, match): '''Respond to the outside air temperature events.''' print "Topic: {topic}, {headers}, Message: {message}".format( topic=topic, headers=headers, message=message) #Content type is json, load it for use cur_temp = jsonapi.loads(message[0]) #If temp has risen, attempt to set cool supply fan if cur_temp > self.prev_temp: self.change_coolspeed() self.prev_temp = cur_temp
def process_data(self, topic, headers, message, match): data = jsonapi.loads(message[0]) # print >> self.logger, topic, message device_label = topic.split('/')[4] if device_label in self.deviceDataHandlers: # look up device device = self.deviceDataHandlers[device_label] # call device process_data method device.process_data(time.time(), data)
def handle_new(self, headers, message, now): requester = headers.get('requesterID') taskID = headers.get('taskID') priority = headers.get('priority') try: requests = jsonapi.loads(message[0]) except (ValueError, IndexError) as ex: # Could be ValueError of JSONDecodeError depending # on if simplesjson was used. JSONDecodeError # inherits from ValueError #We let the schedule manager tell us this is a bad request. requests = [] result = self._schedule_manager.request_slots( requester, taskID, requests, priority, now) success = SCHEDULE_RESPONSE_SUCCESS if result.success else SCHEDULE_RESPONSE_FAILURE #If we are successful we do something else with the real result data data = result.data if not result.success else {} topic = topics.ACTUATOR_SCHEDULE_RESULT() headers = self.get_headers(requester, task_id=taskID) headers['type'] = SCHEDULE_ACTION_NEW self.publish_json(topic, headers, { 'result': success, 'data': data, 'info': result.info_string }) #Dealing with success and other first world problems. if result.success: self.update_device_state_and_schedule(now) for preempted_task in result.data: topic = topics.ACTUATOR_SCHEDULE_RESULT() headers = self.get_headers(preempted_task[0], task_id=preempted_task[1]) headers['type'] = SCHEDULE_ACTION_CANCEL self.publish_json( topic, headers, { 'result': SCHEDULE_CANCEL_PREEMPTED, 'info': '', 'data': { 'agentID': requester, 'taskID': taskID } })
def handle_set(self, topic, headers, message, match): point = match.group(1) collection_tokens, point_name = point.rsplit('/', 1) requester = headers.get('requesterID') headers = self.get_headers(requester) if not message: error = {'type': 'ValueError', 'value': 'missing argument'} self.push_result_topic_pair(ERROR_RESPONSE_PREFIX, point, headers, error) return else: try: message = jsonapi.loads(message[0]) if isinstance(message, bool): message = int(message) except ValueError as ex: # Could be ValueError of JSONDecodeError depending # on if simplesjson was used. JSONDecodeError # inherits from ValueError error = {'type': 'ValueError', 'value': str(ex)} self.push_result_topic_pair(ERROR_RESPONSE_PREFIX, point, headers, error) return if self.check_lock(collection_tokens, requester): request_url = '/'.join( [url, collection_tokens, ACTUATOR_COLLECTION, point_name]) payload = {'state': str(message)} try: r = requests.put(request_url, params=payload) self.process_smap_request_result(r, point, requester) except (requests.exceptions.ConnectionError) as ex: error = {'type': ex.__class__.__name__, 'value': str(ex)} self.push_result_topic_pair(ERROR_RESPONSE_PREFIX, point, headers, error) else: error = { 'type': 'LockError', 'value': 'does not have this lock' } self.push_result_topic_pair(ERROR_RESPONSE_PREFIX, point, headers, error)
def on_lock_result(self, topic, headers, message, match): '''Respond to lock result events.''' print "Topic: {topic}, {headers}, Message: {message}".format( topic=topic, headers=headers, message=message) if headers['requesterID'] != agent_id: #If we didn't request this lock, we don't care about the result print "Not me, don't care." return mess = jsonapi.loads(message[0]) #If we got a success then set it at a random value if mess == 'SUCCESS': setting = random.randint(10, 90) headers[headers_mod.CONTENT_TYPE] = ( headers_mod.CONTENT_TYPE.PLAIN_TEXT) headers['requesterID'] = agent_id self.publish(topics.ACTUATOR_SET(point=fan_point, **rtu_path), headers, agent_id) elif mess == 'RELEASE': #Our lock release result was a success print "Let go of lock"
def handle_full_request(self, topic, headers, message, matched): # Path is part of topic. path = topic[len(topics.BASE_ARCHIVER_FULL_REQUEST):] result_layout = headers.get('ResultLayout', 'HIERARCHICAL') # Range is message. It will either be "start"-"end" or 1h, 1d, # etc... from now range_str = message[0] source = headers.get('SourceName', source_name) # Find UUID for path payload = ('select * where Metadata/SourceName="{}" ' 'and Path~"{}"'.format(source, path)) done = False retries = 0 while not done and retries <= 5: # TODO: Need to do some error handling here! try: r = requests.post(archiver_url, data=payload) if r.status_code == 200: # Data should be a list of dictionaries at this point in time uuid_list = jsonapi.loads(r.text) done = True else: print str(retries) + ": " + str( r.status_code) + ": " + payload retries += 1 except ValueError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 except ConnectionError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 #Can get a 503 network busy #TODO: Respond with error # TODO: Need to do some error handling here! # Data should be a list of dictionaries at this point in time if not uuid_list: # TODO: log this error return timeseries = {} hierarchichal = {} payload_template = "select data in {} where {{}}".format(range_str) if len(uuid_list) == 0: return uuid_clause = "uuid='{}'".format(uuid_list[0]['uuid']) for stream in uuid_list[1:]: uuid_clause += (" or uuid='{}'".format(stream['uuid'])) payload = payload_template.format(uuid_clause) # # Request data and store Readings in timeseries[path] full_data = None tries = 0 done = False while not done and retries <= 5: # TODO: Need to do some error handling here! try: r = requests.post(archiver_url, data=payload) if 'Syntax error' in r.text: # TODO Log this error self.publish(topics.BASE_ARCHIVER_RESPONSE + path, None, 'Syntax error in date range') return # Request data for UUID in range #[{"uuid": "5b94d5ed-1e1d-51cf-a6d8-afae5c055292", "Readings": [[1368750281000.0, 75.5], [1368750341000.0, 75.5], ... done = True except ValueError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 except ConnectionError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 if 'Syntax error' in r.text: # TODO Log this error self.publish(topics.BASE_ARCHIVER_RESPONSE + path, None, 'Syntax error in date range') return # Request data for UUID in range #[{"uuid": "5b94d5ed-1e1d-51cf-a6d8-afae5c055292", # "Readings": [[1368750281000.0, 75.5], [1368750341000.0, 75.5], ... full_data = jsonapi.loads(r.text) reading_dict = {} for readings in full_data: reading_dict[readings['uuid']] = readings.get('Readings', []) for stream in uuid_list: # uuid_clause += (" or uuid='{}'".format(stream['uuid'])) path = stream['Path'] print stream (hierarchichal, timeseries) = build_paths(path, hierarchichal, timeseries) timeseries[path]['uuid'] = stream['uuid'] timeseries[path]['Properties'] = stream['Properties'] timeseries[path]['Path'] = path timeseries[path]['Readings'] = reading_dict[stream['uuid']] pub_headers = { headers_mod.FROM: 'ArchiverAgent', headers_mod.TO: headers[headers_mod.FROM] if headers_mod.FROM in headers else 'Unknown' } if result_layout == 'FLAT': self.publish_json(topics.BASE_ARCHIVER_RESPONSE + path, pub_headers, timeseries) else: self.publish_json(topics.BASE_ARCHIVER_RESPONSE + path, pub_headers, hierarchichal)
def handle_request(self, topic, headers, message, matched): # Path is part of topic. path = topic[len(topics.BASE_ARCHIVER_REQUEST):] # Range is message. It will either be "start"-"end" or 1h, 1d, # etc... from now range_str = message[0] source = headers.get('SourceName', source_name) # Find UUID for path payload = ('select uuid where Metadata/SourceName="{}" ' 'and Path="{}"'.format(source, path)) done = False retries = 0 while not done and retries <= 5: # TODO: Need to do some error handling here! try: r = requests.post(archiver_url, data=payload) if r.status_code == 200: # Data should be a list of dictionaries at this point in time uuid_list = jsonapi.loads(r.text) done = True else: print str(retries) + ": " + str( r.status_code) + ": " + payload retries += 1 except ValueError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 except ConnectionError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 #Can get a 503 network busy #TODO: Respond with error # TODO: Need to do some error handling here! # Data should be a list of dictionaries at this point in time if not uuid_list: # TODO: log this error return payload_template = "select data in {} where {{}}".format(range_str) if len(uuid_list) == 0: return uuid_clause = "uuid='{}'".format(uuid_list[0]['uuid']) for stream in uuid_list[1:]: uuid_clause.append(" or uuid='{}'".format(stream['uuid'])) payload = payload_template.format(uuid_clause) full_data = None tries = 0 done = False while not done and retries <= 5: # TODO: Need to do some error handling here! try: r = requests.post(archiver_url, data=payload) if 'Syntax error' in r.text: # TODO Log this error self.publish(topics.BASE_ARCHIVER_RESPONSE + path, None, 'Syntax error in date range') return # Request data for UUID in range #[{"uuid": "5b94d5ed-1e1d-51cf-a6d8-afae5c055292", "Readings": [[1368750281000.0, 75.5], [1368750341000.0, 75.5], ... done = True except ValueError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 except ConnectionError as e: print str(retries) + ": " + str(e) + ": " + payload retries += 1 if 'Syntax error' in r.text: # TODO Log this error self.publish(topics.BASE_ARCHIVER_RESPONSE + path, None, 'Syntax error in date range') return # Request data for UUID in range #[{"uuid": "5b94d5ed-1e1d-51cf-a6d8-afae5c055292", # "Readings": [[1368750281000.0, 75.5], [1368750341000.0, 75.5], ... full_data = jsonapi.loads(r.text) data = full_data[0].get('Readings', []) pub_headers = { headers_mod.FROM: 'ArchiverAgent', headers_mod.TO: headers[headers_mod.FROM] if headers_mod.FROM in headers else 'Unknown' } if data > 0: # There was data for this stream in the specified range. # Convert data to json and publish self.publish_json(topics.BASE_ARCHIVER_RESPONSE + path, pub_headers, data)
def on_new_data(self, topic, headers, message, match): data = jsonapi.loads(message[0]) mixed_air_temperature=data print(mixed_air_temperature)