Пример #1
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()
Пример #2
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()
Пример #3
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)
        )
Пример #4
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()
Пример #5
0
    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)()
Пример #6
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)
Пример #7
0
 def setUp(self):
     self.mqtt_client = MQTTClient(host='localhost',
                                   port=8883,
                                   user='******',
                                   password='******',
                                   tls_cert="")
Пример #8
0
class Test(unittest.TestCase):
    def setUp(self):
        self.mqtt_client = MQTTClient(host='localhost',
                                      port=8883,
                                      user='******',
                                      password='******',
                                      tls_cert="")

    def test_get_wildchard_topics_single_plus(self):
        callback = Mock()

        WILDCARD1 = 'mh/+/ppmp'

        self.mqtt_client.subscribe(WILDCARD1, callback)

        self.assertEqual(self.mqtt_client.get_wildchard_topics('mh/test/ppmp'),
                         WILDCARD1)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/ppmp'), WILDCARD1)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppmp'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test2/ppmp'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppmp2'),
            WILDCARD1)

    def test_get_wildchard_topics_single_hash(self):
        callback = Mock()

        WILDCARD1 = '#/ppmp'

        self.mqtt_client.subscribe(WILDCARD1, callback)

        self.assertEqual(self.mqtt_client.get_wildchard_topics('mh/test/ppmp'),
                         WILDCARD1)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/ppmp'), WILDCARD1)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('xy/test_2/ppmp'), WILDCARD1)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppmp2'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test2/xy'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppmp_'),
            WILDCARD1)

    def test_get_wildchard_topics_multiple_plus(self):
        callback = Mock()

        WILDCARD1 = 'mh/+/ppmp'
        WILDCARD2 = 'mh/+/cmd'
        WILDCARD3 = 'mh/+/cmd/res'

        self.mqtt_client.subscribe(WILDCARD1, callback)
        self.mqtt_client.subscribe(WILDCARD2, callback)
        self.mqtt_client.subscribe(WILDCARD3, callback)

        self.assertEqual(self.mqtt_client.get_wildchard_topics('mh/test/ppmp'),
                         WILDCARD1)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/ppmp'), WILDCARD1)

        self.assertEqual(self.mqtt_client.get_wildchard_topics('mh/test/cmd'),
                         WILDCARD2)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/cmd'), WILDCARD2)

        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/cmd/res'),
            WILDCARD3)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/cmd/res'),
            WILDCARD3)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppmp'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test2/ppmp'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppmp2'),
            WILDCARD1)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/cmd'),
            WILDCARD2)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test2/cmd'),
            WILDCARD2)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/cmd2'),
            WILDCARD2)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/cmd/res'),
            WILDCARD3)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test2/cmd/res'),
            WILDCARD3)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/cmd/res2'),
            WILDCARD3)

    def test_get_wildchard_topics_multiple_hash(self):
        callback = Mock()

        WILDCARD1 = 'mh/#/ppmp'
        WILDCARD2 = '#/cmd'
        WILDCARD3 = 'mh/#/cmd/res'

        self.mqtt_client.subscribe(WILDCARD1, callback)
        self.mqtt_client.subscribe(WILDCARD2, callback)
        self.mqtt_client.subscribe(WILDCARD3, callback)

        self.assertEqual(self.mqtt_client.get_wildchard_topics('mh/test/ppmp'),
                         WILDCARD1)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/ppmp'), WILDCARD1)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/test3/ppmp'),
            WILDCARD1)

        self.assertEqual(self.mqtt_client.get_wildchard_topics('mh/test/cmd'),
                         WILDCARD2)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/cmd'), WILDCARD2)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('xy/test_2/test3/cmd'),
            WILDCARD2)

        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/cmd/res'),
            WILDCARD3)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/cmd/res'),
            WILDCARD3)
        self.assertEqual(
            self.mqtt_client.get_wildchard_topics('mh/test_2/test3/cmd/res'),
            WILDCARD3)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppm'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test2/ppmp'),
            WILDCARD1)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/ppmp2'),
            WILDCARD1)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/cmd/test'),
            WILDCARD2)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test_2/cm'),
            WILDCARD2)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/cmd2'),
            WILDCARD2)

        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics(
                'mh/test/test2/cmd/res/test'), WILDCARD3)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('xy/test/test2/cmd/res'),
            WILDCARD3)
        self.assertNotEqual(
            self.mqtt_client.get_wildchard_topics('mh/test/test2/cmd/res2'),
            WILDCARD3)
Пример #9
0
def get_random_measurements(variable):
    index = VARIABLES.index(variable)
    value = SERIES_BASE[index]

    meas_list = [
        random.uniform(value - SERIES_RANGE[index],
                       value + SERIES_RANGE[index]) for _ in range(10)
    ]
    return meas_list


if __name__ == '__main__':
    # connect to MQTT
    client = MQTTClient(host=MQTT_HOST,
                        port=MQTT_PORT,
                        user=MQTT_USER,
                        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)
Пример #10
0
except OSError as error:  
    logger.info(f'create logfolder: {LOGFOLDER}:{error}')
# fl = logging.FileHandler('OPC-UA.log')
# Rotation file handler miit 200 000 bytes pro file und 10 files in rotation
fl = RotatingFileHandler(f'{LOGFOLDER}{PROJECT_NAME}.log',mode='a', maxBytes=2*(10**5), backupCount=10)
fl.setLevel(logging.ERROR)
fl.setFormatter(formatter)
logger.addHandler(fl)


# list of all OPC-UA client processes
asynctaskhandls = []
processes = []


globMQTTClient = MQTTClient(host=MQTT_HOST, port=MQTT_PORT, user=MQTT_USERNAME, password=MQTT_PASSWORD, tls_cert=MQTT_TLS_CERT)
    
iothubdevices = dict()

jsonPayloadArray = list()
Temp_Mean = 0
   
def createASCIIpayload(payload):
    
    # a = c_wchar_p(payload)
    
    buf = io.BytesIO()
    cmdlen =  len (payload) 
    cmdlenheader = cmdlen.to_bytes(4, byteorder="little")
    buf.write(cmdlenheader)
    header = bytes([0x55,0x55])