Example #1
0
def main():

    # connect to MQTT and InfluxDB
    mqtt_client = MQTTClient(host=MQTT_HOST,
                             port=MQTT_PORT,
                             user=MQTT_USERNAME,
                             password=MQTT_PASSWORD,
                             tls_cert=MQTT_TLS_CERT)
    mqtt_client.connect(forever=True)
    INFLUX_CLIENT.connect(host=INFLUXDB_HOST,
                          port=INFLUXDB_PORT,
                          username=INFLUXDB_USERNAME,
                          password=INFLUXDB_PASSWORD,
                          database=INFLUXDB_DB)
    setinflux_durationTime(
        influxDuration=INFLUXDB_DURATION_TIME,
        influx_shardGroupDuration=INFLUXDB_SHARDGROUPDURATION_TIME)

    # create and start convertor thread
    Thread(target=convertor).start()

    # create and start InfluxDB consumer thread
    Thread(target=influx_consumer).start()

    # subscribe to MQTT and fill the queue
    mqtt_client.subscribe(MQTT_TOPIC_PPMP, mqtt_producer)
    # srw2ho: topic already used: mqtt_client.subscribe(MQTT_TOPIC_INFO, mqtt_producer)

    mqtt_client.start()
Example #2
0
def start_azureiothub():
    global globMQTTClient
    # send complete config list for all devices (as gateway, not only single PLC device)
    globMQTTClient = MQTTClient(host=MQTT_HOST,
                                port=MQTT_PORT,
                                user=MQTT_USERNAME,
                                password=MQTT_PASSWORD,
                                tls_cert=MQTT_TLS_CERT)

    # connect to MQTT
    globMQTTClient.connect()

    loop = asyncio.get_event_loop()
    client = EventHubConsumerClient.from_connection_string(
        conn_str=CONNECTION_STR,
        consumer_group="$default",
        # transport_type=TransportType.AmqpOverWebsocket,  # uncomment it if you want to use web socket
        # http_proxy={  # uncomment if you want to use proxy
        #     'proxy_hostname': '127.0.0.1',  # proxy hostname.
        #     'proxy_port': 3128,  # proxy port.
        #     'username': '******',
        #     'password': '******'
        # }
    )
    try:
        loop.run_until_complete(
            client.receive_batch(on_event_batch=on_event_MQTTPayload,
                                 on_error=on_error))
    except KeyboardInterrupt:
        print("Receiving has stopped.")
    finally:
        loop.run_until_complete(client.close())
        loop.stop()
Example #3
0
def start_tcpconnections():
    global globMQTTClient
    hosts = toml.get('tcpdevices.hosts', ['localhost'])
    aliashosts = toml.get('tcpdevices.aliashosts', ['localhost'])
    ports = toml.get('tcpdevices.ports', [4840])
     
    
    timeoutsinsec = toml.get('tcpdevices.timeoutsinsecs', [10])

    # send complete config list for all devices (as gateway, not only single PLC device)
    globMQTTClient = MQTTClient(host=MQTT_HOST, port=MQTT_PORT, user=MQTT_USERNAME, password=MQTT_PASSWORD, tls_cert=MQTT_TLS_CERT)
    # create machine message with state ERROR (LWT) (do this before(!) connect)


    # connect to MQTT
    globMQTTClient.connect()

    loop = asyncio.get_event_loop()


    try:
        # loop.create_task(run_alltcpconnectors(hosts, ports, timeoutsinsec))
        # loop.run_forever()
        loop.run_until_complete(run_alltcpconnectors(hosts, aliashosts, ports, timeoutsinsec))
   
    except KeyboardInterrupt:
        print("Receiving has stopped.")
    finally:
        # loop.run_until_complete(client.close())
        loop.stop()
Example #4
0
class PPMPPublisher:

    def __init__(self):
        # connect to MQTT
        self.client = MQTTClient(host=MQTT_HOST, port=MQTT_PORT, user=MQTT_USER, password=MQTT_PASSWORD, tls_cert=MQTT_TLS_CERT)

        self.device = Device(
            state=DeviceState.ERROR,
            additionalData={
                'type': DEVICE_TYPE
            },
        )

        # set up ZeroMQ data sink
        self.consumer_inst = grafanaDevice(SUBSCRIBE_PORT, None)
        self.consumer_inst.connect(self.publish)()

    def connect(self):
        """ Connect to MQTT and set up LWTs
        """
        # create machine message with state ERROR (LWT) (do this before(!) connect)
        self.client.last_will(
            self.device.info_topic(),
            machine_message_generator(self.device, state=DeviceState.ERROR, code="offline"),
            retain=True
        )

        self.client.connect(forever=True)

        # create machine message with state=ON and code=online (retain)
        self.client.publish(
            self.device.info_topic(),
            machine_message_generator(self.device),
            retain=True
        )

        # do not exit, instead wait for changes
        self.client.loop()


    def publish(self, topic, **kwargs):
        """ Publishes data in PPMP structure via MQTT

        Arguments:
            series {obj} -- Series with value names as obj-key, values list ast obj-value
            timestamp {str} -- Reference timestamp
            offsets {list} -- List of offsets (same size as data value is required!)
        """
        # create a measurements
        measurements = [ TimeMeasurement(value['timestamp'], Series([0], **{key: value['values']})) for key, value in kwargs.items() ]

        # publish data via MQTT
        self.client.publish(
            self.device.ppmp_topic(),
            measurement_payload_generator(self.device, measurements)
        )
Example #5
0
from influxconnector.convertor.simple_json_dict import SimpleJSONDict
from influxconnector.client import InfluxClient
from ppmpmessage.convertor.ppmp import PPMPObject
from mqttconnector.client import MQTTClient
import time

MQTT_TOPIC = 'mh/ppmp'

if __name__ == "__main__":
    # connect to InfluxDB
    influx = InfluxClient()
    influx.connect()

    # connect to MQTT
    mqtt = MQTTClient()
    mqtt.connect()

    mqtt.subscribe(
        MQTT_TOPIC, lambda data: influx.write(
            PPMPObject(data).export_to_influxdb(), 'ppmp'))
    #mqtt.subscribe(MQTT_TOPIC, lambda data: influx.write(SimpleJSONDict(data).export_to_influxdb(), 'sofc'))

    while True:
        time.sleep(1)
Example #6
0
                        password=MQTT_PASSWORD,
                        tls_cert=MQTT_TLS_CERT)

    device = Device(
        state=DeviceState.ERROR,
        additionalData={'type': DEVICE_TYPE},
    )

    # create machine message with state ERROR (LWT) (do this before(!) connect)
    client.last_will(device.info_topic(),
                     machine_message_generator(device,
                                               state=DeviceState.ERROR,
                                               code="offline"),
                     retain=True)

    client.connect()

    # create machine message with state=ON and code=online (retain)
    client.publish(device.info_topic(),
                   machine_message_generator(device),
                   retain=True)

    while True:
        measurements = []

        # create 3 TimeMeasurements
        for i in range(1):
            # add 5 random series to measurement (10 millisecond offsets)
            series = Series(
                [index * 10 for index in range(len(VARIABLES))],
                **{var: get_random_measurements(var)