Exemplo n.º 1
0
	def handleTelemetry(self):
		"""
		handle the Telemetry
		
		"""
		#humidityVal = self.humiditySensorSimTask.getTelemetryValue()
		#pressureVal = self.pressureSensorSimTask.getTelemetryValue()
		#tempVal = self.temperatureSensorSimTask .getTelemetryValue()
		configUtil = ConfigUtil()
		
		if self.useEmulator :
			if configUtil.getBoolean(section= ConfigConst.CONSTRAINED_DEVICE, key= ConfigConst.ENABLE_SENSE_HAT_KEY):
				humiditySd = self.humidityI2cSensorAdapterTask.generateTelemetry()
				pressureSd = self.pressureI2cSensorAdapterTask.generateTelemetry()
				tempSd = self.temperatureI2cSensorAdapterTask.generateTelemetry()
			else:
				humiditySd = self.humidityEmulator.generateTelemetry()
				pressureSd = self.pressureEmulator.generateTelemetry()
				tempSd = self.temperatureEmulator .generateTelemetry()
				soilHumiditySd = self.soilHumidityEmulator.generateTelemetry()
		else :
			
			humiditySd = self.humiditySensorSimTask.generateTelemetry()
			pressureSd = self.pressureSensorSimTask.generateTelemetry()
			tempSd = self.temperatureSensorSimTask .generateTelemetry()
		
		if self.dataMsgListener :
			self.dataMsgListener.handleSensorMessage(humiditySd)
			self.dataMsgListener.handleSensorMessage(pressureSd)
			self.dataMsgListener.handleSensorMessage(tempSd)
			self.dataMsgListener.handleSensorMessage(soilHumiditySd)
		
		
		logging.info(' >>>>>>>>> Humidity is < %s >,  SoilHumidity is <%s>,  Pressure is < %s >,  Temperature is < %s >.', str(humiditySd.getValue()), str(soilHumiditySd.getValue()), str(pressureSd.getValue()), str(tempSd.getValue()))
Exemplo n.º 2
0
    def __init__(self, enableMqtt: bool = True, enableCoap: bool = False):
        # set enable connection
        self.enableMqtt = enableMqtt
        self.enableCoap = enableCoap
        # load config
        self.configUtil = ConfigUtil()
        self.enableEmulator = self.configUtil.getBoolean(ConfigConst.CONSTRAINED_DEVICE,
                                                         ConfigConst.ENABLE_EMULATOR_KEY)
        self.stepmotor = StepMotorAdapterTask()
        # create system Perf manager
        self.sysPerfManager = SystemPerformanceManager()
        # set sensor config
        self.sam = SensorAdapterManager(useEmulator=self.enableEmulator)
        #set actuator config
        self.aam = ActuatorAdapterManager(useEmulator=self.enableEmulator)
        #set data generation config
        self.enableHandleTempChangeOnDevice = self.configUtil.getBoolean(ConfigConst.CONSTRAINED_DEVICE,
                                                                         ConfigConst.ENABLE_HANDLE_TEMP_CHANGE_ON_DEVICE_KEY)

        self.triggerHvacTempFloor = self.configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE,
                                                             ConfigConst.TRIGGER_HVAC_TEMP_FLOOR_KEY);

        self.triggerHvacTempCeiling = self.configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE,
                                                               ConfigConst.TRIGGER_HVAC_TEMP_CEILING_KEY);
        #self.stepmotor.moveTo(-40,-40,True)
        # set Mqtt client
        if enableMqtt is True:
            self.mqttClient = MqttClientConnector()
            #self.mqttClient.subscribeToTopic(ResourceNameEnum.CDA_ACTUATOR_RESPONSE_RESOURCE.value)
            #self.mqttClient.subscribeToTopic(ResourceNameEnum.CDA_ACTUATOR_CMD_RESOURCE.value)
            self.mqttClient.subscribeToTopic("ProgrammingIoT/StepMotor/Instruction")
            #self.mqttClient.mc.message_callback_add(callback=self.actuatorCallBack, sub=ResourceNameEnum.CDA_ACTUATOR_CMD_RESOURCE.value)
            self.mqttClient.mc.message_callback_add(callback=self.stepMotorCallBack, sub="ProgrammingIoT/StepMotor/Instruction")
    def __init__(self):
        configUtil = ConfigUtil()

        self.cpuUtilPct = None
        self.memUtilPct = None

        self.pollRate = configUtil.getInteger(
            section=ConfigConst.CONSTRAINED_DEVICE,
            key=ConfigConst.POLL_CYCLES_KEY,
            defaultVal=ConfigConst.DEFAULT_POLL_CYCLES)
        self.locationID = configUtil.getProperty(
            section=ConfigConst.CONSTRAINED_DEVICE,
            key=ConfigConst.DEVICE_LOCATION_ID_KEY,
            defaultVal=ConfigConst.NOT_SET)

        if self.pollRate <= 0:
            self.pollRate = ConfigConst.DEFAULT_POLL_CYCLES

        self.scheduler = BackgroundScheduler()
        self.scheduler.add_job(self.handleTelemetry(),
                               'interval',
                               seconds=self.pollRate)

        self.cpuUtilTask = SystemCpuUtilTask()
        self.memUtilTask = SystemMemUtilTask()

        self.dataMsgListener = None
        # self.memUtilPct = None
        # self.cpuUtilPct = None

        logging.info("Initializing SystemPerformance Manager...")
Exemplo n.º 4
0
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info("Testing MqttClientConnector class...")

        self.cfg = ConfigUtil()
        self.mcc = MqttClientConnector()
	def __init__(self, dataSet = None):
		super(PressureSensorEmulatorTask, self).__init__(SensorData.PRESSURE_SENSOR_TYPE, minVal = SensorDataGenerator.LOW_NORMAL_ENV_PRESSURE, maxVal = SensorDataGenerator.HI_NORMAL_ENV_PRESSURE)
		configUtil = ConfigUtil()
		#get ENABLE_SENSE_HAT_KEY value (bool)
		enableSenseHAT = configUtil.getBoolean(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_SENSE_HAT_KEY)
		if enableSenseHAT is False:
			enableEmulation = True
		else:
			enableEmulation = False
		# create senseHAT instance
		self.sh = SenseHAT(emulate=enableEmulation)
 def setUpClass(self):
     logging.basicConfig(
         format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
         level=logging.DEBUG)
     logging.info("Testing ActuatorAdapterManager class...")
     self.configUtil = ConfigUtil()
     self.enableEmulator = self.configUtil.getBoolean(
         ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_EMULATOR_KEY)
     self.defaultMsgListener = DefaultDataMessageListener()
     self.actuatorAdapterMgr = ActuatorAdapterManager(
         useEmulator=self.enableEmulator)
     self.actuatorAdapterMgr.setDataMessageListener(self.defaultMsgListener)
Exemplo n.º 7
0
	def __init__(self):
		super(HumidifierEmulatorTask, self).__init__(actuatorType = ActuatorData.HUMIDIFIER_ACTUATOR_TYPE, simpleName = "HUMIDIFIER")
		# Create an instance of SenseHAT and set the emulate flag to True if running the emulator, or False if using real hardware
		# This can be read from ConfigUtil using the ConfigConst.CONSTRAINED_DEVICE section and the ConfigConst.ENABLE_SENSE_HAT_KEY
		# If the ConfigConst.ENABLE_SENSE_HAT_KEY is False, set the emulate flag to True, otherwise set to False
		configUtil = ConfigUtil()
		#get ENABLE_SENSE_HAT_KEY value (bool)
		enableSenseHAT = configUtil.getBoolean(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_SENSE_HAT_KEY)
		if enableSenseHAT is False:
			enableEmulation = True
		else:
			enableEmulation = False
		# create senseHAT instance
		self.sh = SenseHAT(emulate=enableEmulation)
 def __init__(self, enableMqtt: bool = True, enableCoap: bool = False):
     self.sysPerfManager = SystemPerformanceManager()
     self.sensorAdapterManager = SensorAdapterManager()
     self.actuatorAdapterManager = ActuatorAdapterManager()
     self.configUtil = ConfigUtil()
     self.enableHandleTempChangeOnDevice = self.configUtil.getBoolean(
         ConfigConst.CONSTRAINED_DEVICE,
         ConfigConst.ENABLE_HANDLE_TEMP_CHANGE_ON_DEVICE_KEY)
     self.triggerHvacTempFloor = self.configUtil.getFloat(
         ConfigConst.CONSTRAINED_DEVICE,
         ConfigConst.TRIGGER_HVAC_TEMP_FLOOR_KEY)
     self.triggerHvacTempCeiling = self.configUtil.getFloat(
         ConfigConst.CONSTRAINED_DEVICE,
         ConfigConst.TRIGGER_HVAC_TEMP_CEILING_KEY)
	def setUpClass(self):
		logging.basicConfig(format = '%(asctime)s:%(module)s:%(levelname)s:%(message)s', level = logging.DEBUG)
		logging.info("Running DataIntegrationTest test cases...")
		
		encodeToUtf8 = False
		
		self.dataUtil = DataUtil(encodeToUtf8)

		self.cdaDataPath = ConfigUtil().getProperty(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.TEST_CDA_DATA_PATH_KEY)
		self.gdaDataPath = ConfigUtil().getProperty(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.TEST_GDA_DATA_PATH_KEY)
		
		if not os.path.exists(self.cdaDataPath):
			logging.info("================================================")
			logging.info("DataIntegrationTest - path needs to be created: " + self.cdaDataPath)
			os.makedirs(self.cdaDataPath, exist_ok = True)
Exemplo n.º 10
0
 def __init__(self):
     """
     Initialization of class.
     Create an instance of HvacEmulatorTask
     """
     super(SprinklerMasterEmulatorTask, self).__init__(actuatorType = ActuatorData.SPRINKLER_MASTER_ACTUATOR_TYPE, simpleName = "SPRI_MASTER")
     # Create an instance of SenseHAT and set the emulate flag to True if running the emulator, or False if using real hardware
     # This can be read from ConfigUtil using the ConfigConst.CONSTRAINED_DEVICE section and the ConfigConst.ENABLE_SENSE_HAT_KEY
     # If the ConfigConst.ENABLE_SENSE_HAT_KEY is False, set the emulate flag to True, otherwise set to False
     configUtil = ConfigUtil()
     if configUtil.getBoolean(section= ConfigConst.CONSTRAINED_DEVICE, key= ConfigConst.ENABLE_SENSE_HAT_KEY):
         enableEmulation = False 
     else:
         enableEmulation = True
     
     self.sh = SenseHAT(emulate = enableEmulation)
class SensorAdapterManagerTest(unittest.TestCase):
    """
	This test case class contains very basic unit tests for
	SensorAdapterManager. It should not be considered complete,
	but serve as a starting point for the student implementing
	additional functionality within their Programming the IoT
	environment.
	"""
    @classmethod
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info("Testing SensorAdapterManager class...")
        self.configUtil = ConfigUtil()
        self.enableEmulator = self.configUtil.getBoolean(
            ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_EMULATOR_KEY)
        self.defaultMsgListener = DefaultDataMessageListener()
        self.sensorAdapterMgr = SensorAdapterManager(
            useEmulator=self.enableEmulator)
        self.sensorAdapterMgr.setDataMessageListener(self.defaultMsgListener)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testStartAndStopManager(self):
        self.sensorAdapterMgr.startManager()

        sleep(20)

        self.sensorAdapterMgr.stopManager()
Exemplo n.º 12
0
 def __init__(self):
     """
     Constructor of HvacEmulatorTask.
     Init emulated or not SenseHAT instance according to config.
     """
     super(HvacEmulatorTask, self).__init__(actuatorType=ActuatorData.HVAC_ACTUATOR_TYPE,
                                            simpleName=ConfigConst.HVAC_ACTUATOR_NAME)
     self.enableEmulation = True
     configUtil = ConfigUtil()
     enableSenseHAT = configUtil.getBoolean(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_SENSE_HAT_KEY)
     if enableSenseHAT is True:
         self.enableEmulation = False
     else:
         self.enableEmulation = True
     self.sh = SenseHAT(emulate=self.enableEmulation)
     pass
     pass
 def __init__(self):
     self.dataUtil = DataUtil()
     self.configUtil = ConfigUtil()
     self.host = self.configUtil.getProperty(
         ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.HOST_KEY)
     self.port = self.configUtil.getInteger(
         ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.PORT_KEY)
     self.enableCrypt = self.configUtil.getBoolean(
         ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.ENABLE_CRYPT_KEY)
     if self.enableCrypt:
         self.credFilePath = self.configUtil.getProperty(
             ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.CRED_FILE_KEY)
         # TODO: init redis with encryption
     logging.info("Redis client setting: host = {0}, port = {1}.".format(
         self.host, self.port))
     # Init with no connection established
     self.curConnection: redis.client.Redis = None
Exemplo n.º 14
0
	def __init__(self, dataSet = None):
		"""
		Initialization of class.
		Create an instance of TemperatureSensorEmulatorTask
		"""
		# Create an instance of SenseHAT and set the emulate flag to True if running the emulator, or False if using real hardware
		# This can be read from ConfigUtil using the ConfigConst.CONSTRAINED_DEVICE section and the ConfigConst.ENABLE_SENSE_HAT_KEY
		# If the ConfigConst.ENABLE_SENSE_HAT_KEY is False, set the emulate flag to True, otherwise set to False
		super(TemperatureSensorEmulatorTask, self).__init__(SensorData.TEMP_SENSOR_TYPE, minVal = SensorDataGenerator.LOW_NORMAL_ENV_TEMP, maxVal = SensorDataGenerator.HI_NORMAL_ENV_TEMP)
		
		configUtil = ConfigUtil()
		if configUtil.getBoolean(section= ConfigConst.CONSTRAINED_DEVICE, key= ConfigConst.ENABLE_SENSE_HAT_KEY):
			enableEmulation = False 
		else:
			enableEmulation = True
			
		self.sh = SenseHAT(emulate = enableEmulation)
Exemplo n.º 15
0
 def __init__(self, dataSet=None):
     super(HumiditySensorEmulatorTask, self).__init__(
         SensorData.HUMIDITY_SENSOR_TYPE,
         minVal=SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY,
         maxVal=SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)
     # Create an instance of SenseHAT and set the emulate flag to True if running the emulator, or False if using real hardware
     # This can be read from ConfigUtil using the ConfigConst.CONSTRAINED_DEVICE section and the ConfigConst.ENABLE_SENSE_HAT_KEY
     # If the ConfigConst.ENABLE_SENSE_HAT_KEY is False, set the emulate flag to True, otherwise set to False
     configUtil = ConfigUtil()
     #get ENABLE_SENSE_HAT_KEY value (bool)
     enableSenseHAT = configUtil.getBoolean(
         ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_SENSE_HAT_KEY)
     if enableSenseHAT is False:
         enableEmulation = True
     else:
         enableEmulation = False
     #create senseHAT instance
     self.sh = SenseHAT(emulate=enableEmulation)
class ActuatorAdapterManagerTest(unittest.TestCase):
    """
	This test case class contains very basic unit tests for
	ActuatorSimAdapterManager. It should not be considered complete,
	but serve as a starting point for the student implementing
	additional functionality within their Programming the IoT
	environment.
	"""
    @classmethod
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info("Testing ActuatorAdapterManager class...")
        self.configUtil = ConfigUtil()
        self.enableEmulator = self.configUtil.getBoolean(
            ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_EMULATOR_KEY)
        self.defaultMsgListener = DefaultDataMessageListener()
        self.actuatorAdapterMgr = ActuatorAdapterManager(
            useEmulator=self.enableEmulator)
        self.actuatorAdapterMgr.setDataMessageListener(self.defaultMsgListener)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testHumidifierSimulation(self):
        ad = ActuatorData(actuatorType=ActuatorData.HUMIDIFIER_ACTUATOR_TYPE)
        ad.setValue(50.0)

        ad.setCommand(ActuatorData.COMMAND_ON)
        self.actuatorAdapterMgr.sendActuatorCommand(ad)

        ad.setCommand(ActuatorData.COMMAND_OFF)
        self.actuatorAdapterMgr.sendActuatorCommand(ad)

    def testHvacSimulation(self):
        ad = ActuatorData(actuatorType=ActuatorData.HVAC_ACTUATOR_TYPE)
        ad.setValue(22.5)

        ad.setCommand(ActuatorData.COMMAND_ON)
        self.actuatorAdapterMgr.sendActuatorCommand(ad)

        ad.setCommand(ActuatorData.COMMAND_OFF)
        self.actuatorAdapterMgr.sendActuatorCommand(ad)

    def testLEDSimulation(self):
        ad = ActuatorData(actuatorType=ActuatorData.LED_DISPLAY_ACTUATOR_TYPE)
        ad.setStateData(stateData="Test stateData")

        ad.setCommand(ActuatorData.COMMAND_ON)
        self.actuatorAdapterMgr.sendActuatorCommand(ad)

        ad.setCommand(ActuatorData.COMMAND_OFF)
        self.actuatorAdapterMgr.sendActuatorCommand(ad)
 def __init__(self, dataSet=None):
     """
     Constructor of PressureSensorEmulatorTask
     Using super class constructor to init
     :param dataSet: Dict for construct object with given data
     """
     super(PressureSensorEmulatorTask, self).__init__(
         sensorType=SensorData.PRESSURE_SENSOR_TYPE,
         dataSet=dataSet,
         minVal=SensorDataGenerator.LOW_NORMAL_ENV_PRESSURE,
         maxVal=SensorDataGenerator.HI_NORMAL_ENV_PRESSURE)
     self.enableEmulation = True
     configUtil = ConfigUtil()
     enableSenseHAT = configUtil.getBoolean(
         ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_SENSE_HAT_KEY)
     if enableSenseHAT is True:
         self.enableEmulation = False
     else:
         self.enableEmulation = True
     self.sh = SenseHAT(emulate=self.enableEmulation)
     pass
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.INFO)
        logging.info("Testing CoapClientConnector class...")

        self.dataMsgListener = DefaultDataMessageListener()

        self.pollRate = ConfigUtil().getInteger(
            ConfigConst.CONSTRAINED_DEVICE, ConfigConst.POLL_CYCLES_KEY,
            ConfigConst.DEFAULT_POLL_CYCLES)

        self.coapClient = CoapClientConnector()
Exemplo n.º 19
0
    def __init__(self):
        """
		Use the ConfigUtil configuration information for the CoAP Gateway to retrieve the host and port information.
		"""
        self.config = ConfigUtil()
        self.dataMsgListener = None
        self.coapClient = None

        self.host = self.config.getProperty(ConfigConst.COAP_GATEWAY_SERVICE,
                                            ConfigConst.HOST_KEY,
                                            ConfigConst.DEFAULT_HOST)
        self.port = self.config.getInteger(ConfigConst.COAP_GATEWAY_SERVICE,
                                           ConfigConst.PORT_KEY,
                                           ConfigConst.DEFAULT_COAP_PORT)

        logging.info('\tCoAP Server Host: ' + self.host)
        logging.info('\tCoAP Server Port: ' + str(self.port))
        """
		Validate the url information
		"""
        self.url = "coap://" + self.host + ":" + str(self.port) + "/"

        try:
            logging.info("Parsing URL: " + self.url)

            self.host, self.port, self.path = parse_uri(self.url)
            tmpHost = socket.gethostbyname(self.host)

            if tmpHost:
                self.host = tmpHost
                self._initClient()
            else:
                logging.error("Can't resolve host: " + self.host)

        except socket.gaierror:
            logging.info("Failed to resolve host: " + self.host)

        self._initClient()
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.INFO)
        logging.info(
            "Testing CoapServerAdapter and CoapClientConnector classes...")

        self.dataMsgListener = DefaultDataMessageListener()

        self.pollRate = ConfigUtil().getInteger(
            ConfigConst.CONSTRAINED_DEVICE, ConfigConst.POLL_CYCLES_KEY,
            ConfigConst.DEFAULT_POLL_CYCLES)

        self.coapClient = CoapClientConnector()
        self.coapServer = CoapServerAdapter(
            dataMsgListener=self.dataMsgListener)

        self.tempDataUpdateListener = GetTelemetryResourceHandler()
        self.sysPerfDataUpdateListener = GetSystemPerformanceResourceHandler()

        # add these CoAP resource handlers as listeners to the IDataMessageListener impl
        self.dataMsgListener.setTelemetryDataListener(
            ConfigConst.TEMP_SENSOR_NAME, self.tempDataUpdateListener)
        self.dataMsgListener.setSystemPerformanceDataListener(
            self.sysPerfDataUpdateListener)

        # add these CoAP resource handlers to the CoAP server
        self.coapServer.addResource( \
         ResourceNameEnum.CDA_SENSOR_MSG_RESOURCE, \
         ConfigConst.TEMP_SENSOR_NAME, \
         self.tempDataUpdateListener)

        self.coapServer.addResource( \
         ResourceNameEnum.CDA_SYSTEM_PERF_MSG_RESOURCE, \
         ConfigConst.SYSTEM_PERF_NAME, \
         self.sysPerfDataUpdateListener)

        # create a scheduler to update system perf data and temp sensor data at pollCycles
        self.scheduler = BackgroundScheduler()
        self.scheduler.add_job(self._updateTelemetry,
                               'interval',
                               seconds=self.pollRate)

        # start the server and the scheduled data updater
        self.coapServer.startServer()
        self.scheduler.start()
Exemplo n.º 21
0
    def __init__(self,
                 name=ConfigConst.NOT_SET,
                 typeID=ConfigConst.DEFAULT_TYPE_ID,
                 d=None):
        """
		Constructor.
		
		@param d Defaults to None. The data (dict) to use for setting all parameters.
		It's provided here as a convenience - mostly for testing purposes. The utility
		in DataUtil should be used instead.
		"""

        self.updateTimeStamp()
        self.hasError = False

        useDefaults = True

        if d:
            try:
                self.name = d[ConfigConst.NAME_PROP]
                self.typeID = d[ConfigConst.TYPE_ID_PROP]
                self.statusCode = d[ConfigConst.STATUS_CODE_PROP]
                self.latitude = d[ConfigConst.LATITUDE_PROP]
                self.longitude = d[ConfigConst.LONGITUDE_PROP]
                self.elevation = d[ConfigConst.ELEVATION_PROP]

                useDefaults = False
            except:
                pass

        if useDefaults:
            self.name = name
            self.typeID = typeID
            self.statusCode = ConfigConst.DEFAULT_STATUS
            self.latitude = ConfigConst.DEFAULT_LAT
            self.longitude = ConfigConst.DEFAULT_LON
            self.elevation = ConfigConst.DEFAULT_ELEVATION

        if not self.name:
            self.name = ConfigConst.NOT_SET

        # always pull location ID from configuration file
        self.locationID = ConfigUtil().getProperty(
            ConfigConst.CONSTRAINED_DEVICE, ConfigConst.DEVICE_LOCATION_ID_KEY)
    def setUpClass(self):
        logging.info("Testing MqttClientConnector class...")

        self.cfg = ConfigUtil()
        self.mcc = MqttClientConnector(clientID = 'CDAMqttClientConnectorTest001')
Exemplo n.º 23
0
 def setUpClass(self):
     logging.basicConfig(
         format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
         level=logging.DEBUG)
     logging.info("Testing ConfigUtil class...")
     self.configUtil = ConfigUtil(configFile=self.configFile)
Exemplo n.º 24
0
class MqttClientConnectorTest(unittest.TestCase):
    """
	This test case class contains very basic unit tests for
	MqttClientConnector. It should not be considered complete,
	but serve as a starting point for the student implementing
	additional functionality within their Programming the IoT
	environment.
	"""
    @classmethod
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info("Testing MqttClientConnector class...")

        self.cfg = ConfigUtil()
        self.mcc = MqttClientConnector()

    def setUp(self):
        pass

    def tearDown(self):
        pass

    @unittest.skip("Ignore for now.")
    def testConnectAndDisconnect(self):
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)

        self.mcc.connectClient()

        sleep(delay + 5)

        self.mcc.disconnectClient()

    @unittest.skip("Ignore for now.")
    def testConnectAndCDAManagementStatusPubSub(self):
        qos = 1
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)

        self.mcc.connectClient()
        self.mcc.subscribeToTopic(
            resource=ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE, qos=qos)
        sleep(5)

        self.mcc.publishMessage(
            resource=ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE,
            msg="TEST: This is the CDA message payload.",
            qos=qos)
        sleep(5)

        self.mcc.unsubscribeFromTopic(
            resource=ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE)
        sleep(5)

        sleep(delay)

        self.mcc.disconnectClient()

    @unittest.skip("Ignore for now.")
    def testActuatorCmdPubSub(self):
        qos = 0
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)

        actuatorData = ActuatorData()
        actuatorData.setCommand(7)

        self.mcc.setDataMessageListener(DefaultDataMessageListener())

        payload = DataUtil().actuatorDataToJson(actuatorData)

        self.mcc.connectClient()

        sleep(5)

        self.mcc.publishMessage(
            resource=ResourceNameEnum.CDA_ACTUATOR_CMD_RESOURCE,
            msg=payload,
            qos=qos)

        sleep(delay + 5)

        self.mcc.disconnectClient()

    @unittest.skip("Ignore for now.")
    def testCDAManagementStatusSubscribe(self):
        qos = 1
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)

        self.mcc.connectClient()
        self.mcc.subscribeToTopic(
            resource=ResourceNameEnum.CDA_MGMT_STATUS_CMD_RESOURCE, qos=qos)

        sleep(delay)

        self.mcc.disconnectClient()

    @unittest.skip("Ignore for now.")
    def testCDAManagementStatusPublish(self):
        """
		Uncomment this test when integration between the GDA and CDA using MQTT.
		
		"""
        qos = 1
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)

        self.mcc.connectClient()
        self.mcc.publishMessage(
            resource=ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE,
            msg="TEST: This is the CDA message payload.",
            qos=qos)

        sleep(delay)

        self.mcc.disconnectClient()
Exemplo n.º 25
0
class ConfigUtilTest(unittest.TestCase):
    """
	This test case class contains very basic unit tests for
	ConfigUtil. It should not be considered complete,
	but serve as a starting point for the student implementing
	additional functionality within their Programming the IoT
	environment.
	"""
    DEFAULT_USER = "******"
    DEFAULT_AUTH = "Bar"

    # optionally test the following files
    #  - EmptyTestConfig.props
    #  - InvalidTestConfig.props
    #  - None (which will default to ./config/PiotConfig.props)
    configFile = "./ValidTestConfig.props"

    @classmethod
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info("Testing ConfigUtil class...")
        self.configUtil = ConfigUtil(configFile=self.configFile)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testGetBooleanProperty(self):
        enableLogging = self.configUtil.hasProperty(
            ConfigConst.CONSTRAINED_DEVICE, ConfigConst.ENABLE_LOGGING_KEY)
        self.assertTrue(enableLogging)

    def testGetCredentials(self):
        creds = self.configUtil.getCredentials(ConfigConst.CONSTRAINED_DEVICE)
        self.assertIsNotNone(creds)
        self.assertEqual(creds[ConfigConst.USER_NAME_TOKEN_KEY],
                         self.DEFAULT_USER)
        self.assertEqual(creds[ConfigConst.USER_AUTH_TOKEN_KEY],
                         self.DEFAULT_AUTH)
        pass

    def testGetIntegerProperty(self):
        port = self.configUtil.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                          ConfigConst.PORT_KEY)
        self.assertEqual(port, ConfigConst.DEFAULT_MQTT_PORT)

    def testGetFloatProperty(self):
        hSimFloor = self.configUtil.getFloat(
            ConfigConst.CONSTRAINED_DEVICE, ConfigConst.HUMIDITY_SIM_FLOOR_KEY)
        self.assertGreater(hSimFloor, 0.0)

    def testGetProperty(self):
        hostName = self.configUtil.getProperty(
            ConfigConst.MQTT_GATEWAY_SERVICE, ConfigConst.HOST_KEY)
        self.assertTrue(hostName)

    def testHasProperty(self):
        self.assertTrue(
            self.configUtil.hasProperty(ConfigConst.CONSTRAINED_DEVICE,
                                        ConfigConst.ENABLE_EMULATOR_KEY))

    def testHasSection(self):
        self.assertTrue(
            self.configUtil.hasSection(ConfigConst.CONSTRAINED_DEVICE))

    def testIsConfigDataLoaded(self):
        self.assertTrue(self.configUtil.isConfigDataLoaded())
Exemplo n.º 26
0
 def __init__(self,
              useEmulator: bool = False,
              pollRate: int = 5,
              allowConfigOverride: bool = True):
     self.useEmulator = useEmulator
     self.pollRate = pollRate
     self.allowConfigOverride = allowConfigOverride
     self.dataMsgListener = IDataMessageListener()
     self.scheduler = BackgroundScheduler()
     self.scheduler.add_job(self.handleTelemetry,
                            'interval',
                            seconds=self.pollRate)
     # whether use Emulator
     if self.useEmulator is True:
         logging.info("Use Emulator")
         # load the Humidity emulator
         humidityModule = __import__(
             'programmingtheiot.cda.emulated.HumiditySensorEmulatorTask',
             fromlist=['HumiditySensorEmulatorTask'])
         heClazz = getattr(humidityModule, 'HumiditySensorEmulatorTask')
         self.humidityEmulator = heClazz()
         # load the Pressure emulator
         pressureModule = __import__(
             'programmingtheiot.cda.emulated.PressureSensorEmulatorTask',
             fromlist=['PressureSensorEmulatorTask'])
         heClazz = getattr(pressureModule, 'PressureSensorEmulatorTask')
         self.pressureEmulator = heClazz()
         # load the Temp emulator
         tempModule = __import__(
             'programmingtheiot.cda.emulated.TemperatureSensorEmulatorTask',
             fromlist=['TemperatureSensorEmulatorTask'])
         heClazz = getattr(tempModule, 'TemperatureSensorEmulatorTask')
         self.tempEmulator = heClazz()
     else:
         logging.info("Use Simulator")
         self.dataGenerator = SensorDataGenerator()
         configUtil = ConfigUtil()
         #define data range
         humidityFloor = configUtil.getFloat(
             ConfigConst.CONSTRAINED_DEVICE,
             ConfigConst.HUMIDITY_SIM_FLOOR_KEY,
             SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY)
         humidityCeiling = configUtil.getFloat(
             ConfigConst.CONSTRAINED_DEVICE,
             ConfigConst.HUMIDITY_SIM_CEILING_KEY,
             SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)
         pressureFloor = configUtil.getFloat(
             ConfigConst.CONSTRAINED_DEVICE,
             ConfigConst.PRESSURE_SIM_FLOOR_KEY,
             SensorDataGenerator.LOW_NORMAL_ENV_PRESSURE)
         pressureCeiling = configUtil.getFloat(
             ConfigConst.CONSTRAINED_DEVICE,
             ConfigConst.PRESSURE_SIM_CEILING_KEY,
             SensorDataGenerator.HI_NORMAL_ENV_PRESSURE)
         tempFloor = configUtil.getFloat(
             ConfigConst.CONSTRAINED_DEVICE, ConfigConst.TEMP_SIM_FLOOR_KEY,
             SensorDataGenerator.LOW_NORMAL_INDOOR_TEMP)
         tempCeiling = configUtil.getFloat(
             ConfigConst.CONSTRAINED_DEVICE,
             ConfigConst.TEMP_SIM_CEILING_KEY,
             SensorDataGenerator.HI_NORMAL_INDOOR_TEMP)
         #generate dataset
         self.humidityData = self.dataGenerator.generateDailyEnvironmentHumidityDataSet(
             minValue=humidityFloor,
             maxValue=humidityCeiling,
             useSeconds=False)
         self.pressureData = self.dataGenerator.generateDailyEnvironmentPressureDataSet(
             minValue=pressureFloor,
             maxValue=pressureCeiling,
             useSeconds=False)
         self.tempData = self.dataGenerator.generateDailyIndoorTemperatureDataSet(
             minValue=tempFloor, maxValue=tempCeiling, useSeconds=False)
         #create task with data
         self.htask = HumiditySensorSimTask(dataSet=self.humidityData)
         self.ptask = PressureSensorSimTask(dataSet=self.pressureData)
         self.ttask = TemperatureSensorSimTask(dataSet=self.tempData)
class MqttClientConnectorTest(unittest.TestCase):
    """
	This test case class contains very basic unit tests for
	MqttClientConnector. It should not be considered complete,
	but serve as a starting point for the student implementing
	additional functionality within their Programming the IoT
	environment.
	"""
    @classmethod
    def setUpClass(self):
        logging.basicConfig(
            format='%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info("Testing MqttClientConnector class...")

        self.cfg = ConfigUtil()
        self.mcc = MqttClientConnector(
            clientID='CDAMqttClientConnectorTest001')

    def setUp(self):
        pass

    def tearDown(self):
        pass

    @unittest.skip("Ignore for now.")
    def testConnectAndDisconnect(self):
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)

        self.mcc.connect()

        sleep(delay + 5)

        self.mcc.disconnect()

    @unittest.skip("Ignore for now.")
    def testConnectAndPublish(self):
        qos = 1
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)
        listener = DefaultDataMessageListener()

        self.mcc.connect()
        self.mcc.subscribeToTopic(
            ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE, qos)

        sleep(5)

        self.mcc.publishMessage(ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE,
                                "TEST: This is the CDA message payload.", qos)
        sleep(5)

        self.mcc.unsubscribeFromTopic(
            ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE)
        sleep(5)

        sleep(delay)

        self.mcc.disconnect()

    @unittest.skip("Ignore for now.")
    def testIntegrateWithGdaSubscribeCdaCmdTopic(self):
        qos = 1
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)
        listener = DefaultDataMessageListener()

        self.mcc.connect()
        self.mcc.subscribeToTopic(
            ResourceNameEnum.CDA_MGMT_STATUS_CMD_RESOURCE, qos)

        sleep(delay)

        self.mcc.disconnect()

    @unittest.skip("Ignore for now.")
    def testIntegrateWithGdaPublishCdaMgmtTopic(self):
        qos = 1
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)
        listener = DefaultDataMessageListener()

        self.mcc.connect()
        self.mcc.publishMessage(ResourceNameEnum.CDA_MGMT_STATUS_MSG_RESOURCE,
                                "TEST: This is the CDA message payload.", qos)

        sleep(5)

        self.mcc.disconnect()

    def testActuatorCmdPubSub(self):
        qos = 1
        # NOTE: delay can be anything you'd like - the sleep() calls are simply to slow things down a bit for observation
        delay = self.cfg.getInteger(ConfigConst.MQTT_GATEWAY_SERVICE,
                                    ConfigConst.KEEP_ALIVE_KEY,
                                    ConfigConst.DEFAULT_KEEP_ALIVE)
        actuatorData = ActuatorData()
        payload = DataUtil().actuatorDataToJson(actuatorData)
        self.mcc.connectClient()
        sleep(3)
        self.mcc.publishMessage(
            resource=ResourceNameEnum.CDA_ACTUATOR_CMD_RESOURCE,
            msg=payload,
            qos=qos)
        sleep(3)
        self.mcc.disconnectClient()
Exemplo n.º 28
0
    def __init__(self,
                 useEmulator: bool = False,
                 pollRate: int = 5,
                 allowConfigOverride: bool = True):
        self.useEmulator = useEmulator
        self.pollRate = pollRate

        self.dataMsgListener = 0
        self.allowConfigOverride = allowConfigOverride

        self.scheduler = BackgroundScheduler()
        self.scheduler.add_job(self.handleTelemetry,
                               'interval',
                               seconds=self.pollRate)

        if (self.useEmulator == True):
            logging.info("Emulators are being used")
            humidityModule = __import__(
                'programmingtheiot.cda.emulated.HumiditySensorEmulatorTask',
                fromlist=['HumiditySensorEmulatorTask'])
            heClazz = getattr(humidityModule, 'HumiditySensorEmulatorTask')
            self.humidityEmulator = heClazz()

            pressureModule = __import__(
                'programmingtheiot.cda.emulated.PressureSensorEmulatorTask',
                fromlist=['PressureSensorEmulatorTask'])
            heClazz = getattr(pressureModule, 'PressureSensorEmulatorTask')
            self.pressureEmulator = heClazz()

            tempModule = __import__(
                'programmingtheiot.cda.emulated.TemperatureSensorEmulatorTask',
                fromlist=['TemperatureSensorEmulatorTask'])
            heClazz = getattr(tempModule, 'TemperatureSensorEmulatorTask')
            self.tempEmulator = heClazz()

        else:
            logging.info("Simulators are being used")
            self.dataGenerator = SensorDataGenerator()
            configUtil = ConfigUtil()

            humidity_floor = configUtil.getFloat(
                ConfigConst.CONSTRAINED_DEVICE,
                ConfigConst.HUMIDITY_SIM_FLOOR_KEY,
                SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY)
            humidity_ceiling = configUtil.getFloat(
                ConfigConst.CONSTRAINED_DEVICE,
                ConfigConst.HUMIDITY_SIM_CEILING_KEY,
                SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)

            pressure_Floor = configUtil.getFloat(
                ConfigConst.CONSTRAINED_DEVICE,
                ConfigConst.PRESSURE_SIM_FLOOR_KEY,
                SensorDataGenerator.LOW_NORMAL_ENV_PRESSURE)
            pressure_ceiling = configUtil.getFloat(
                ConfigConst.CONSTRAINED_DEVICE,
                ConfigConst.PRESSURE_SIM_CEILING_KEY,
                SensorDataGenerator.HI_NORMAL_ENV_PRESSURE)

            temp_floor = configUtil.getFloat(
                ConfigConst.CONSTRAINED_DEVICE, ConfigConst.TEMP_SIM_FLOOR_KEY,
                SensorDataGenerator.LOW_NORMAL_INDOOR_TEMP)
            temp_ceiling = configUtil.getFloat(
                ConfigConst.CONSTRAINED_DEVICE,
                ConfigConst.TEMP_SIM_CEILING_KEY,
                SensorDataGenerator.HI_NORMAL_INDOOR_TEMP)

            self.humidityData = self.dataGenerator.generateDailyEnvironmentHumidityDataSet(
                minValue=humidity_floor,
                maxValue=humidity_ceiling,
                useSeconds=False)

            self.pressureData = self.dataGenerator.generateDailyEnvironmentPressureDataSet(
                minValue=pressure_Floor,
                maxValue=pressure_ceiling,
                useSeconds=False)

            self.tempData = self.dataGenerator.generateDailyIndoorTemperatureDataSet(
                minValue=temp_floor, maxValue=temp_ceiling, useSeconds=False)

            self.humiditySensorSimTask = HumiditySensorSimTask(
                self.humidityData)
            self.pressureSensorSimTask = PressureSensorSimTask(
                self.pressureData)
            self.temperatureSensorSimTask = TemperatureSensorSimTask(
                self.tempData)

            logging.info("Simulated Humidity Sensor Sim Task Value is: %s ",
                         self.humiditySensorSimTask.LatestSensorData)
            logging.info("Simulated Pressure Sensor Sim Task Value is : %s ",
                         self.pressureSensorSimTask.LatestSensorData)
            logging.info("Simulated Temperature Sensor Sim Task Value is: %s ",
                         self.temperatureSensorSimTask.LatestSensorData)
            self.handleTelemetry()
        pass
Exemplo n.º 29
0
	def __init__(self, useEmulator: bool = False, pollRate: int = 15, allowConfigOverride: bool = True):
		"""
		Initialization of class.
		Create an instance of SensorAdapterManager
		"""
		self.useEmulator = useEmulator
		self.pollRate = pollRate
		self.allowConfigOverride = allowConfigOverride
		self.dataMsgListener = None
		self.scheduler = BackgroundScheduler()
		self.scheduler.add_job(self.handleTelemetry, 'interval', seconds = self.pollRate)
		
		configUtil = ConfigUtil()
		
		"""
		If self.useEmulator is true, we will use Emulator to generate sensor data
		Else we will use SensorDataGenerator
		"""
		if self.useEmulator :
			logging.info("---> Emulators will be used ")
			
			
			
			if configUtil.getBoolean(section= ConfigConst.CONSTRAINED_DEVICE, key= ConfigConst.ENABLE_SENSE_HAT_KEY):
				logging.info("---> SMbus will be used ")
				self.humidityI2cSensorAdapterTask = HumidityI2cSensorAdapterTask()
				self.pressureI2cSensorAdapterTask = PressureI2cSensorAdapterTask()
				self.temperatureI2cSensorAdapterTask = TemperatureI2cSensorAdapterTask()
			else:
				# load the Humidity emulator
				humidityModule = __import__('programmingtheiot.cda.emulated.HumiditySensorEmulatorTask', fromlist = ['HumiditySensorEmulatorTask'])
				heClazz = getattr(humidityModule, 'HumiditySensorEmulatorTask')
				self.humidityEmulator = heClazz()
			
				pressureModule = __import__('programmingtheiot.cda.emulated.PressureSensorEmulatorTask', fromlist = ['PressureSensorEmulatorTask'])
				peClazz = getattr(pressureModule, 'PressureSensorEmulatorTask')
				self.pressureEmulator = peClazz()
			
				temperatureModule = __import__('programmingtheiot.cda.emulated.TemperatureSensorEmulatorTask', fromlist = ['TemperatureSensorEmulatorTask'])
				teClazz = getattr(temperatureModule, 'TemperatureSensorEmulatorTask')
				self.temperatureEmulator =teClazz()
				
				##add by miaoyao for final project
				soilHumidityModule = __import__('programmingtheiot.cda.emulated.SoilHumiditySensorEmulatorTask', fromlist = ['SoilHumiditySensorEmulatorTask'])
				shClazz = getattr(soilHumidityModule, 'SoilHumiditySensorEmulatorTask')
				self.soilHumidityEmulator = shClazz()
				

			
		else:
			logging.info("---> Simulators will be used ")
			self.dataGenerator = SensorDataGenerator()

			

			humidityFloor = configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.HUMIDITY_SIM_FLOOR_KEY, SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY)
			humidityCeiling = configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.HUMIDITY_SIM_CEILING_KEY, SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)
			
			pressureFloor = configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.PRESSURE_SIM_FLOOR_KEY, SensorDataGenerator.LOW_NORMAL_ENV_PRESSURE)
			pressureCeiling = configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.PRESSURE_SIM_CEILING_KEY, SensorDataGenerator.HI_NORMAL_ENV_PRESSURE)
			
			tempFloor = configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.TEMP_SIM_FLOOR_KEY, SensorDataGenerator.LOW_NORMAL_INDOOR_TEMP)
			tempCeiling = configUtil.getFloat(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.TEMP_SIM_CEILING_KEY, SensorDataGenerator.HI_NORMAL_INDOOR_TEMP)
			
			humidityData = self.dataGenerator.generateDailyEnvironmentHumidityDataSet(minValue = humidityFloor, maxValue = humidityCeiling, useSeconds = False)
			pressureData = self.dataGenerator.generateDailyEnvironmentPressureDataSet(minValue = pressureFloor, maxValue = pressureCeiling, useSeconds = False)
			tempData = self.dataGenerator.generateDailyIndoorTemperatureDataSet(minValue = tempFloor, maxValue = tempCeiling, useSeconds = False)
			
			
			
			
			self.humiditySensorSimTask = HumiditySensorSimTask(dataSet= humidityData)
			self.pressureSensorSimTask = PressureSensorSimTask(dataSet= pressureData)
			self.temperatureSensorSimTask = TemperatureSensorSimTask(dataSet= tempData)
Exemplo n.º 30
0
class CoapClientConnector(IRequestResponseClient):
    """
	Shell representation of class for student implementation.
	
	"""
    def __init__(self):
        """
		Use the ConfigUtil configuration information for the CoAP Gateway to retrieve the host and port information.
		"""
        self.config = ConfigUtil()
        self.dataMsgListener = None
        self.coapClient = None

        self.host = self.config.getProperty(ConfigConst.COAP_GATEWAY_SERVICE,
                                            ConfigConst.HOST_KEY,
                                            ConfigConst.DEFAULT_HOST)
        self.port = self.config.getInteger(ConfigConst.COAP_GATEWAY_SERVICE,
                                           ConfigConst.PORT_KEY,
                                           ConfigConst.DEFAULT_COAP_PORT)

        logging.info('\tCoAP Server Host: ' + self.host)
        logging.info('\tCoAP Server Port: ' + str(self.port))
        """
		Validate the url information
		"""
        self.url = "coap://" + self.host + ":" + str(self.port) + "/"

        try:
            logging.info("Parsing URL: " + self.url)

            self.host, self.port, self.path = parse_uri(self.url)
            tmpHost = socket.gethostbyname(self.host)

            if tmpHost:
                self.host = tmpHost
                self._initClient()
            else:
                logging.error("Can't resolve host: " + self.host)

        except socket.gaierror:
            logging.info("Failed to resolve host: " + self.host)

        self._initClient()

    """
	Send DISCOVER request to the server
	"""

    def sendDiscoveryRequest(
            self,
            timeout: int = IRequestResponseClient.DEFAULT_TIMEOUT) -> bool:
        logging.info('Discovering remote resources...')

        # NOTE: we can use the API to send a discovery 'GET', or - per [RFC7252](https://tools.ietf.org/html/rfc7252#section-7.2)
        # and its reference of [RFC6690](https://tools.ietf.org/html/rfc6690#section-1.2.1), we can just send the following:
        # self.coapClient.get(path = '/.well-known/core', callback = self._onDiscoveryResponse, timeout = timeout)
        self.coapClient.discover(callback=self._onDiscoveryResponse,
                                 timeout=timeout)

    """
	Send delete request to the server
	"""

    def sendDeleteRequest(
            self,
            resource: ResourceNameEnum,
            enableCON=False,
            timeout: int = IRequestResponseClient.DEFAULT_TIMEOUT) -> bool:
        logging.info("the method sendDeleteRequest is called")
        if resource:
            logging.debug("Issuing DELETE with path: " + resource.value)
            request = self.coapClient.mk_request(defines.Codes.DELETE,
                                                 path=resource.value)
            request.token = generate_random_token(2)

            if not enableCON:
                request.type = defines.Types["NON"]

            self.coapClient.send_request(request=request,
                                         callback=self._onDeleteResponse,
                                         timeout=timeout)
        else:
            logging.warning(
                "Can't test DELETE - no path or path list provided.")

    """
	Send get request to the server
	"""

    def sendGetRequest(
            self,
            resource: ResourceNameEnum,
            enableCON=False,
            timeout: int = IRequestResponseClient.DEFAULT_TIMEOUT) -> bool:
        logging.info("the method sendGetRequest is called")
        if resource:
            logging.debug("Issuing GET with path: " + resource.value)
            request = self.coapClient.mk_request(defines.Codes.GET,
                                                 path=resource.value)
            request.token = generate_random_token(2)

            if not enableCON:
                request.type = defines.Types["NON"]

            self.coapClient.send_request(request=request,
                                         callback=self._onGetResponse,
                                         timeout=timeout)
        else:
            logging.warning("Can't test GET - no path or path list provided.")

    """
	Send post request to the server
	"""

    def sendPostRequest(
            self,
            resource: ResourceNameEnum,
            payload: str,
            enableCON=False,
            timeout: int = IRequestResponseClient.DEFAULT_TIMEOUT) -> bool:
        #logging.info("the method sendPostRequest is called")
        if resource:
            logging.debug("Issuing POST with path: " + resource.value)
            request = self.coapClient.mk_request(defines.Codes.POST,
                                                 path=resource.value)
            request.token = generate_random_token(2)
            request.payload = payload

            if not enableCON:
                request.type = defines.Types["NON"]

            self.coapClient.send_request(request=request,
                                         callback=self._onPostResponse,
                                         timeout=timeout)
        else:
            logging.warning("Can't test POST - no path or path list provided.")

    """
	Send put request to the server
	"""

    def sendPutRequest(
            self,
            resource: ResourceNameEnum,
            payload: str,
            enableCON=False,
            timeout: int = IRequestResponseClient.DEFAULT_TIMEOUT) -> bool:
        #logging.info("the method sendPutRequest is called")
        if resource:
            logging.debug("Issuing PUT with path: " + resource.value)
            request = self.coapClient.mk_request(defines.Codes.PUT,
                                                 path=resource.value)
            request.token = generate_random_token(2)
            request.payload = payload

            if not enableCON:
                request.type = defines.Types["NON"]

            self.coapClient.send_request(request=request,
                                         callback=self._onPutResponse,
                                         timeout=timeout)
        else:
            logging.warning("Can't test PUT - no path or path list provided.")

    """
	Set the Data Message Listener
	"""

    def setDataMessageListener(self, listener: IDataMessageListener) -> bool:
        self.dataMsgListener = listener

    def startObserver(self,
                      resource: ResourceNameEnum,
                      ttl: int = IRequestResponseClient.DEFAULT_TTL) -> bool:
        pass

    def stopObserver(
            self,
            timeout: int = IRequestResponseClient.DEFAULT_TIMEOUT) -> bool:
        self.coapClient.close()

    """
	Initialize the coap client
	"""

    def _initClient(self):
        if not self.coapClient:
            self.coapClient = HelperClient(server=(self.host, self.port))

    """
	Callback function for sendDiscoveryRequest()
	"""

    def _onDiscoveryResponse(self, response):
        if response:
            logging.info(response.pretty_print())

            # get the payload and convert to a list of paths
            self.pathList = response.payload.split(',')
            index = 0

            # the following is optional, but provides an easy way to track all the returned resource names
            for path in self.pathList:
                for char in '<\>':
                    path = path.replace(char, '')

                self.pathList[index] = path

                logging.info('  Path entry [' + str(index) + ']:' +
                             self.pathList[index])
                index += 1
        else:
            logging.info("No response received.")

    """
	Callback function for sendGetRequest()
	"""

    def _onGetResponse(self, response):

        logging.info('[COAP_CALLBACK] GET response received.')

        if response:
            logging.info('Token: ' + str(response.token))
            logging.info(str(response.location_path))
            logging.info(str(response.payload))

            #
            # NOTE: This next section is optional if you want to send a callback to the self.dataMsgListener instance
            #

            # TODO: get the URI and convert to ResourceNameEnum

            resource = ResourceNameEnum.CDA_ACTUATOR_CMD_RESOURCE
            msg = str(response.payload)
            if response.payload:
                ad = DataUtil.jsonToActuatorData(self, msg)
                if ad.getActuatorType() == 4:
                    resource = ResourceNameEnum.CDA_ACTUATOR_CMD_RESOURCE
                else:
                    resource = ResourceNameEnum.CDA_CLOUD_ACTUATOR_CMD_RESOURCE
            if self.dataMsgListener and response.payload:
                self.dataMsgListener.handleIncomingMessage(resource, msg)

    """
	Callback function for sendPutRequest()
	"""

    def _onPutResponse(self, response):
        #logging.info('PUT response received.')

        if response:
            logging.info('Token: ' + str(response.token))
            logging.info(str(response.location_path))
            logging.info(str(response.payload))

    """
	Callback function for sendPostRequest()
	"""

    def _onPostResponse(self, response):
        #logging.info('POST response received.')

        if response:
            logging.info('Token: ' + str(response.token))
            logging.info(str(response.location_path))
            logging.info(str(response.payload))

    """
	Callback function for sendDeleteRequest()
	"""

    def _onDeleteResponse(self, response):
        logging.info('DELETE response received.')

        if response:
            logging.info('Token: ' + str(response.token))
            logging.info(str(response.location_path))
            logging.info(str(response.payload))