Ejemplo n.º 1
0
class SimulatedDevice(Device):
    def __init__(self, name, interval=1):
        super(SimulatedDevice,
              self).__init__(name=name,
                             entity_id=systemUUID().get_uuid(name),
                             entity_type="SimulatedDevice")
        self.mqtt = MqttDeviceComms(url="test.mosquitto.org",
                                    port=1883,
                                    clean_session=True,
                                    conn_disconn_timeout=1000)
        print('Connection to broker established...')
        self.interval = interval
        self.randomVar = 0
        self.run()

    def run(self):
        self.th = threading.Thread(target=self.simulate)
        self.th.daemon = False
        self.th.start()

    def simulate(self):
        print('Simulation beginning...')
        while True:
            self.randomVar = random.randint(0, 30)
            self.randomVar = [self.randomVar, self.randomVar]
            self.mqtt.publish("random_data", str(self.randomVar), qos=2)
            print(self.randomVar)
            time.sleep(self.interval)
Ejemplo n.º 2
0
    def run(self, registry):
        """
        The execution function of a liota package.

        Acquires "iotcc_mqtt" and "iotcc_mqtt_edge_system" from registry and registers edge_system related metrics
        with the DCC and publishes those metrics.

        :param registry: the instance of ResourceRegistryPerPackage of the package
        :return:
        """
        self.iotcc = registry.get("iotcc_mqtt")
        self.iotcc_edge_system = copy.copy(
            registry.get("iotcc_mqtt_edge_system"))

        self.mqtt_dev_comms = MqttDeviceComms(self.broker_ip,
                                              self.broker_port,
                                              identity=None,
                                              tls_conf=None,
                                              qos_details=None,
                                              client_id="pulse",
                                              clean_session=True,
                                              userdata={
                                                  "self": self,
                                                  "registry": registry
                                              },
                                              protocol="MQTTv311",
                                              transport="tcp",
                                              keep_alive=60,
                                              enable_authentication=False,
                                              conn_disconn_timeout=10)

        self.mqtt_dev_comms.subscribe(self.broker_topic, 0, sub_callback)
def mqtt_subscribe(edge_system_object):
    # RemoteSystemIdentity Object to connect with broker used in DeviceComms
    remote_system_identity = RemoteSystemIdentity(root_ca_cert=config['broker_root_ca_cert'],
                                                  username=config['broker_username'], password=['broker_password'])

    # Create Edge System identity object with all required certificate details
    edge_system_identity = EdgeSystemIdentity(edge_system=edge_system_object, cert_file=config['edge_system_cert_file'],
                                              key_file=config['edge_system_key_file'])

    # Encapsulate TLS parameters
    tls_conf = TLSConf(cert_required=config['cert_required'], tls_version=config['tls_version'],
                       cipher=config['cipher'])

    # Encapsulate QoS related parameters
    qos_details = QoSDetails(in_flight=config['in_flight'], queue_size=config['queue_size'], retry=config['retry'])

    # Create MQTT connection object with required params
    mqtt_conn = MqttDeviceComms(remote_system_identity=remote_system_identity, edge_system_identity=edge_system_identity,
                                tls_details=tls_conf, qos_details=None, url=config['BrokerIP'], clean_session=True,
                                port=config['BrokerPort'], keep_alive=config['keep_alive'], enable_authentication=True)

    # Subscribe to channels : "temperature/kitchen" and "temperature/living-room" with preferred QoS level 0, 1 or 2
    # Provide callback function as a parameter for corresponding channel
    mqtt_conn.subscribe(config['MqttChannel1'], 1, callback_kitchen_temp)
    mqtt_conn.subscribe(config['MqttChannel2'], 1, callback_living_room_temp)
Ejemplo n.º 4
0
    def __init__(self, mqtt_cfg, name=None, simulator=None):
        super(MqttSimulator, self).__init__(name=name)
        log.debug("MqttSimulator is initializing")

        broker_ip_port_topic = mqtt_cfg["broker_ip_port_topic"]
        str_list = broker_ip_port_topic.split(':')
        if str_list[0] == "" or str_list[0] == None:
            log.debug("No broker ip is specified!")
            self.broker_ip = "127.0.0.1"
        else:
            self.broker_ip = str(str_list[0])
        if str_list[1] == "" or str_list[1] == None:
            log.debug("No broker port is specified!")
        self.broker_port = int(str_list[1])
        if str_list[2] == "" or str_list[2] == None:
            log.debug("No broker topic is specified!")
        else:
            self.topic = str(str_list[2])
        self.simulator = simulator

        # RemoteSystemIdentity Object to connect with broker used in DeviceComms
        self.remote_system_identity = RemoteSystemIdentity(
            mqtt_cfg['broker_root_ca_cert'], mqtt_cfg['broker_username'],
            mqtt_cfg['broker_password'])
        # Create Edge System identity object with all required certificate details
        self.edge_system_identity = EdgeSystemIdentity(
            self.simulator.edge_system_object,
            mqtt_cfg['edge_system_cert_file'],
            mqtt_cfg['edge_system_key_file'])
        if ((mqtt_cfg['cert_required'] == "None")
                or (mqtt_cfg['cert_required'] == "CERT_NONE")):
            self.tls_conf = None
        else:
            # Encapsulate TLS parameters
            self.tls_conf = TLSConf(mqtt_cfg['cert_required'],
                                    mqtt_cfg['tls_version'],
                                    mqtt_cfg['cipher'])
        # Encapsulate QoS related parameters
        self.qos_details = QoSDetails(mqtt_cfg['in_flight'],
                                      mqtt_cfg['queue_size'],
                                      mqtt_cfg['retry'])
        # Create MQTT connection object with required params
        self.mqtt_conn = MqttDeviceComms(
            remote_system_identity=self.remote_system_identity,
            edge_system_identity=self.edge_system_identity,
            tls_details=self.tls_conf,
            qos_details=None,
            url=self.broker_ip,
            clean_session=True,
            port=int(self.broker_port),
            keep_alive=int(mqtt_cfg['keep_alive']),
            enable_authentication=False)

        log.debug("MqttSimulator is initialized")
        print "MqttSimulator is initialized"
        self.cfg_sets = mqtt_cfg
        self.cnt = 0
        self.flag_alive = True
        self.start()
Ejemplo n.º 5
0
 def __init__(self, name, interval=1):
     super(SimulatedDevice,
           self).__init__(name=name,
                          entity_id=systemUUID().get_uuid(name),
                          entity_type="SimulatedDevice")
     self.mqtt = MqttDeviceComms(url="test.mosquitto.org",
                                 port=1883,
                                 clean_session=True,
                                 conn_disconn_timeout=1000)
     print('Connection to broker established...')
     self.interval = interval
     self.randomVar = 0
     self.run()
Ejemplo n.º 6
0
def mqtt_subscribe():
    # Encapsulates Identity
    identity = Identity(config['broker_root_ca_cert'], config['broker_username'], config['broker_password'],
                        config['edge_system_cert_file'], config['edge_system_key_file'])
    # Encapsulate TLS parameters
    tls_conf = TLSConf(cert_required=config['cert_required'], tls_version=config['tls_version'],
                       cipher=config['cipher'])

    # Create MQTT connection object with required params
    mqtt_conn = MqttDeviceComms(url=config['BrokerIP'], port=config['BrokerPort'], identity=identity,
                                tls_conf=tls_conf,
                                qos_details=None,
                                clean_session=True,
                                keep_alive=config['keep_alive'], enable_authentication=True)

    # Subscribe to channels : "temperature/kitchen" and "temperature/living-room" with preferred QoS level 0, 1 or 2
    # Provide callback function as a parameter for corresponding channel
    mqtt_conn.subscribe(config['MqttChannel1'], 1, callback_kitchen_temp)
    mqtt_conn.subscribe(config['MqttChannel2'], 1, callback_living_room_temp)
Ejemplo n.º 7
0
def mqtt_subscribe():
    # Encapsulates Identity
    identity = Identity(config['broker_root_ca_cert'],
                        config['broker_username'], config['broker_password'],
                        config['edge_system_cert_file'],
                        config['edge_system_key_file'])
    # Encapsulate TLS parameters
    tls_conf = TLSConf(cert_required=config['cert_required'],
                       tls_version=config['tls_version'],
                       cipher=config['cipher'])

    # Create MQTT connection object with required params
    mqtt_conn = MqttDeviceComms(url=config['BrokerIP'],
                                port=config['BrokerPort'],
                                identity=identity,
                                tls_conf=tls_conf,
                                qos_details=None,
                                clean_session=True,
                                keep_alive=config['keep_alive'],
                                enable_authentication=True)

    # Subscribe to channels : "temperature/kitchen" and "temperature/living-room" with preferred QoS level 0, 1 or 2
    # Provide callback function as a parameter for corresponding channel
    mqtt_conn.subscribe(config['MqttChannel1'], 1, callback_kitchen_temp)
    mqtt_conn.subscribe(config['MqttChannel2'], 1, callback_living_room_temp)
Ejemplo n.º 8
0
    def __init__(self, mqtt_cfg, name=None, simulator=None):
        super(MqttSimulator, self).__init__(name=name)
        log.debug("MqttSimulator is initializing")

        broker_ip_port_topic = mqtt_cfg["broker_ip_port_topic"]
        str_list = broker_ip_port_topic.split(':')
        if str_list[0] == "" or str_list[0] == None:
            log.debug("No broker ip is specified!")
            self.broker_ip = "127.0.0.1"
        else:
            self.broker_ip = str(str_list[0])
        if str_list[1] == "" or str_list[1] == None:
            log.debug("No broker port is specified!")
        self.broker_port = int(str_list[1])
        if str_list[2] == "" or str_list[2] == None:
            log.debug("No broker topic is specified!")
        else:
            self.topic = str(str_list[2])
        self.simulator = simulator

        # Encapsulates Identity
        self.identity = Identity(mqtt_cfg['broker_root_ca_cert'], mqtt_cfg['broker_username'],
                                 mqtt_cfg['broker_password'], mqtt_cfg['edge_system_cert_file'],
                                 mqtt_cfg['edge_system_key_file'])
        if ((mqtt_cfg['cert_required'] == "None") or  (mqtt_cfg['cert_required'] == "CERT_NONE")):
            self.tls_conf = None
        else:
            # Encapsulate TLS parameters
            self.tls_conf = TLSConf(mqtt_cfg['cert_required'], mqtt_cfg['tls_version'], mqtt_cfg['cipher'])
        # Encapsulate QoS related parameters
        self.qos_details = QoSDetails(mqtt_cfg['in_flight'], int(mqtt_cfg['queue_size']), mqtt_cfg['retry'])
        # Create MQTT connection object with required params
        self.mqtt_conn = MqttDeviceComms(url=self.broker_ip, port=int(self.broker_port), identity=self.identity,
                                         tls_conf=self.tls_conf, qos_details=self.qos_details,  clean_session=True,
                                         keep_alive=int(mqtt_cfg['keep_alive']), enable_authentication=False)

        log.debug("MqttSimulator is initialized")
        print "MqttSimulator is initialized"
        self.cfg_sets = mqtt_cfg
        self.cnt = 0
        self.flag_alive = True
        self.start()
Ejemplo n.º 9
0
def mqtt_subscribe(edge_system_object):
    # RemoteSystemIdentity Object to connect with broker used in DeviceComms
    remote_system_identity = RemoteSystemIdentity(
        root_ca_cert=config['broker_root_ca_cert'],
        username=config['broker_username'],
        password=['broker_password'])

    # Create Edge System identity object with all required certificate details
    edge_system_identity = EdgeSystemIdentity(
        edge_system=edge_system_object,
        cert_file=config['edge_system_cert_file'],
        key_file=config['edge_system_key_file'])

    # Encapsulate TLS parameters
    tls_conf = TLSConf(cert_required=config['cert_required'],
                       tls_version=config['tls_version'],
                       cipher=config['cipher'])

    # Encapsulate QoS related parameters
    qos_details = QoSDetails(in_flight=config['in_flight'],
                             queue_size=config['queue_size'],
                             retry=config['retry'])

    # Create MQTT connection object with required params
    mqtt_conn = MqttDeviceComms(remote_system_identity=remote_system_identity,
                                edge_system_identity=edge_system_identity,
                                tls_details=tls_conf,
                                qos_details=None,
                                url=config['BrokerIP'],
                                clean_session=True,
                                port=config['BrokerPort'],
                                keep_alive=config['keep_alive'],
                                enable_authentication=True)

    # Subscribe to channels : "temperature/kitchen" and "temperature/living-room" with preferred QoS level 0, 1 or 2
    # Provide callback function as a parameter for corresponding channel
    mqtt_conn.subscribe(config['MqttChannel1'], 1, callback_kitchen_temp)
    mqtt_conn.subscribe(config['MqttChannel2'], 1, callback_living_room_temp)
Ejemplo n.º 10
0
class MqttSimulator(DeviceSimulator):
    """
    MqttSimulator does inter-process communication (IPC), and
    publishes on topics to send simulated device beacon messages.
    """

    def __init__(self, mqtt_cfg, name=None, simulator=None):
        super(MqttSimulator, self).__init__(name=name)
        log.debug("MqttSimulator is initializing")

        broker_ip_port_topic = mqtt_cfg["broker_ip_port_topic"]
        str_list = broker_ip_port_topic.split(':')
        if str_list[0] == "" or str_list[0] == None:
            log.debug("No broker ip is specified!")
            self.broker_ip = "127.0.0.1"
        else:
            self.broker_ip = str(str_list[0])
        if str_list[1] == "" or str_list[1] == None:
            log.debug("No broker port is specified!")
        self.broker_port = int(str_list[1])
        if str_list[2] == "" or str_list[2] == None:
            log.debug("No broker topic is specified!")
        else:
            self.topic = str(str_list[2])
        self.simulator = simulator

        # Encapsulates Identity
        self.identity = Identity(mqtt_cfg['broker_root_ca_cert'], mqtt_cfg['broker_username'],
                                 mqtt_cfg['broker_password'], mqtt_cfg['edge_system_cert_file'],
                                 mqtt_cfg['edge_system_key_file'])
        if ((mqtt_cfg['cert_required'] == "None") or  (mqtt_cfg['cert_required'] == "CERT_NONE")):
            self.tls_conf = None
        else:
            # Encapsulate TLS parameters
            self.tls_conf = TLSConf(mqtt_cfg['cert_required'], mqtt_cfg['tls_version'], mqtt_cfg['cipher'])
        # Encapsulate QoS related parameters
        self.qos_details = QoSDetails(mqtt_cfg['in_flight'], int(mqtt_cfg['queue_size']), mqtt_cfg['retry'])
        # Create MQTT connection object with required params
        self.mqtt_conn = MqttDeviceComms(url=self.broker_ip, port=int(self.broker_port), identity=self.identity,
                                         tls_conf=self.tls_conf, qos_details=self.qos_details,  clean_session=True,
                                         keep_alive=int(mqtt_cfg['keep_alive']), enable_authentication=False)

        log.debug("MqttSimulator is initialized")
        print "MqttSimulator is initialized"
        self.cfg_sets = mqtt_cfg
        self.cnt = 0
        self.flag_alive = True
        self.start()

    def run(self):
        msg = {
            "Apple56": {
                "k1": "v1",
                "SN": "0",
                "kn": "vn"
            }
        }
        log.info('MqttSimulator is running')
        print "MqttSimulator is running"
        while self.flag_alive:
            if self.cnt >= 5:
                time.sleep(1000);
            else:
                msg["Apple56"]["SN"] = str(self.cnt)
                log.debug("send msg:{0}".format(msg))
                self.mqtt_conn.publish(self.topic, json.dumps(msg), 2, False)
                time.sleep(5)
            self.cnt += 1
            if self.cnt > 20:
                self.flag = False
        log.info("Thread exits: %s" % str(self.name))
        self.mqtt_conn._disconnect()

    def clean_up(self):
        self.flag_alive = False
        self.mqtt_conn._disconnect()
Ejemplo n.º 11
0
    edge_system = Dk300EdgeSystem(config['EdgeSystemName'])

    # Connect with MQTT broker using DeviceComms and subscribe to topics
    # Get kitchen and living room temperature values using MQTT channel

    kafka = Kafka(
        KafkaDccComms(ip=config['KafkaIP'], port=str(config['KafkaPort'])))
    # graphite = Graphite(SocketDccComms(ip=config['GraphiteIP'],
    # port=int(config['GraphitePort'])))

    kafka_reg_edge_system = kafka.register(edge_system)
    # graphite_reg_edge_system = graphite.register(edge_system)
    mqtt_conn = MqttDeviceComms(url=config['BrokerIP'],
                                port=config['BrokerPort'],
                                identity=None,
                                tls_conf=None,
                                qos_details=None,
                                clean_session=True,
                                keep_alive=config['keep_alive'],
                                enable_authentication=False)

    mqtt_conn.subscribe(config['MqttChannel1'], 0, callback_kafka)

    try:

        metric_name = config['MetricName']
        content_metric = Metric(
            name=metric_name,
            unit=None,
            interval=1,
            aggregation_size=1,
            sampling_function=
Ejemplo n.º 12
0
class MqttSimulator(DeviceSimulator):
    """
    MqttSimulator does inter-process communication (IPC), and
    publishes on topics to send simulated device beacon messages.
    """
    def __init__(self, mqtt_cfg, name=None, simulator=None):
        super(MqttSimulator, self).__init__(name=name)
        log.debug("MqttSimulator is initializing")

        broker_ip_port_topic = mqtt_cfg["broker_ip_port_topic"]
        str_list = broker_ip_port_topic.split(':')
        if str_list[0] == "" or str_list[0] == None:
            log.debug("No broker ip is specified!")
            self.broker_ip = "127.0.0.1"
        else:
            self.broker_ip = str(str_list[0])
        if str_list[1] == "" or str_list[1] == None:
            log.debug("No broker port is specified!")
        self.broker_port = int(str_list[1])
        if str_list[2] == "" or str_list[2] == None:
            log.debug("No broker topic is specified!")
        else:
            self.topic = str(str_list[2])
        self.simulator = simulator

        # Encapsulates Identity
        self.identity = Identity(mqtt_cfg['broker_root_ca_cert'],
                                 mqtt_cfg['broker_username'],
                                 mqtt_cfg['broker_password'],
                                 mqtt_cfg['edge_system_cert_file'],
                                 mqtt_cfg['edge_system_key_file'])
        if ((mqtt_cfg['cert_required'] == "None")
                or (mqtt_cfg['cert_required'] == "CERT_NONE")):
            self.tls_conf = None
        else:
            # Encapsulate TLS parameters
            self.tls_conf = TLSConf(mqtt_cfg['cert_required'],
                                    mqtt_cfg['tls_version'],
                                    mqtt_cfg['cipher'])
        # Encapsulate QoS related parameters
        self.qos_details = QoSDetails(mqtt_cfg['in_flight'],
                                      int(mqtt_cfg['queue_size']),
                                      mqtt_cfg['retry'])
        # Create MQTT connection object with required params
        self.mqtt_conn = MqttDeviceComms(url=self.broker_ip,
                                         port=int(self.broker_port),
                                         identity=self.identity,
                                         tls_conf=self.tls_conf,
                                         qos_details=self.qos_details,
                                         clean_session=True,
                                         keep_alive=int(
                                             mqtt_cfg['keep_alive']),
                                         enable_authentication=False)

        log.debug("MqttSimulator is initialized")
        print "MqttSimulator is initialized"
        self.cfg_sets = mqtt_cfg
        self.cnt = 0
        self.flag_alive = True
        self.start()

    def run(self):
        msg = {"Apple56": {"k1": "v1", "SN": "0", "kn": "vn"}}
        log.info('MqttSimulator is running')
        print "MqttSimulator is running"
        while self.flag_alive:
            if self.cnt >= 5:
                time.sleep(1000)
            else:
                msg["Apple56"]["SN"] = str(self.cnt)
                log.debug("send msg:{0}".format(msg))
                self.mqtt_conn.publish(self.topic, json.dumps(msg), 2, False)
                time.sleep(5)
            self.cnt += 1
            if self.cnt > 20:
                self.flag = False
        log.info("Thread exits: %s" % str(self.name))
        self.mqtt_conn._disconnect()

    def clean_up(self):
        self.flag_alive = False
        self.mqtt_conn._disconnect()
Ejemplo n.º 13
0

def on_message(client, data, msg):
    d = eval(msg.payload)
    print(d)


# getting values from conf file
config = {}
execfile('sampleProp.conf', config)

if __name__ == '__main__':
    edge_system = Dell5KEdgeSystem(config['EdgeSystemName'])
    graphite = Graphite(
        SocketDccComms(ip=config['GraphiteIP'], port=config['GraphitePort']))
    graphite_reg_dev = graphite.register(edge_system)
    mqtt = MqttDeviceComms(url="test.mosquitto.org",
                           port=1883,
                           clean_session=True,
                           conn_disconn_timeout=1000)
    print('Connection to broker established...')
    mqtt.subscribe("random_data", callback=on_message, qos=2)
    print('Subscribed to random_data')
    metric_name = "model.device_data"
    random_metric = Metric(name=metric_name,
                           interval=5,
                           sampling_function=random_function)
    reg_metric = graphite.register(random_metric)
    graphite.create_relationship(graphite_reg_dev, reg_metric)
    reg_metric.start_collecting()
Ejemplo n.º 14
0
class PackageClass(LiotaPackage):

    broker_ip = "127.0.0.1"
    broker_port = 1883
    broker_topic = "#"
    metrics = []
    reg_devices = []

    def run(self, registry):
        """
        The execution function of a liota package.

        Acquires "iotcc_mqtt" and "iotcc_mqtt_edge_system" from registry and registers edge_system related metrics
        with the DCC and publishes those metrics.

        :param registry: the instance of ResourceRegistryPerPackage of the package
        :return:
        """
        self.iotcc = registry.get("iotcc_mqtt")
        self.iotcc_edge_system = copy.copy(
            registry.get("iotcc_mqtt_edge_system"))

        self.mqtt_dev_comms = MqttDeviceComms(self.broker_ip,
                                              self.broker_port,
                                              identity=None,
                                              tls_conf=None,
                                              qos_details=None,
                                              client_id="pulse",
                                              clean_session=True,
                                              userdata={
                                                  "self": self,
                                                  "registry": registry
                                              },
                                              protocol="MQTTv311",
                                              transport="tcp",
                                              keep_alive=60,
                                              enable_authentication=False,
                                              conn_disconn_timeout=10)

        self.mqtt_dev_comms.subscribe(self.broker_topic, 0, sub_callback)

    def clean_up(self):
        """
        The clean up function of a liota package.

        Stops metric collection and publish.
        :return:
        """
        # Kindly include this call to stop the metrics collection on package unload

        try:
            for metric in self.metrics:
                metric.stop_collecting()
        except Exception:
            log.info("Stop collecting failed.")
            raise

        try:
            for device in self.reg_devices:
                self.iotcc.unregister(device)
        except Exception:
            log.info("Unregister devices failed.")
            raise

        try:
            self.mqtt_dev_comms._disconnect()
        except Exception:
            log.info("Disconnect failed.")
            raise