Пример #1
0
def main(path, topic):
    dns_dict = LRUCache(10000)
    max_usage = 0
    max_domain = ''
    client = MQTTClient('a2wcug9wfns56q-ats.iot.us-east-2.amazonaws.com',
                        'certificates/d6ccf7c6bd-certificate.pem.crt',
                        'certificates/d6ccf7c6bd-private.pem.key',
                        'certificates/AmazonRootCA1.pem')
    client.connect()
    while True:
        files = get_files_by_mdate(path, suffix='.pcap')
        for file in files:
            try:
                records = parse_pcap(file, dns_dict)
            except Scapy_Exception as err:
                if str(err) == "No data could be read!":
                    print('empty file', file,
                          'possibly being written by tcpdump')
                    break
                raise
            if not records: continue
            print('summarized count', len(json.dumps(records)) / 1000, 'KB')
            max_domain_usage = max(records, key=lambda x: x['size'])
            if max_domain_usage['size'] > max_usage:
                max_domain = max_domain_usage['domain']
                max_usage = max_domain_usage['size']
            while records:
                message = json.dumps(records[:500])
                client.publish(topic, message)
                records = records[500:]
            print('deleting file', file)
            os.remove(file)
        print('all files processed. sleeping for 1 minute.')
        print('domain', max_domain, 'usage', max_usage)
        time.sleep(60)
Пример #2
0
def create_mqtt_client():
    return MQTTClient(os.environ.get('PROJECT_ID'),
                      os.environ.get('REGISTRY_ID'),
                      os.environ.get('DEVICE_ID'),
                      os.environ.get('PRIVATE_KEY_FILE'),
                      os.environ.get('REGION'), os.environ.get('CA_CERTS'),
                      os.environ.get('ALGORITHM'))
Пример #3
0
def mqtt_connect():
    board_id = config['board']['id']
    ip = config['mqtt']['ip']
    client = MQTTClient(board_id, ip)
    client.connect()

    return client
Пример #4
0
    def __init_devices(self):
        if self._config.has_ups_lite:
            from UPS_Lite import UPSLite
            self._upslite = UPSLite()
            self._input_devices.append(self._upslite)

        if self._config.has_lcd_hat_1in3:
            from lcd_hat_1in3 import LCDHat
            self._display = LCDHat()
            self._input_devices.append(self._display)

        if self._config.has_oled_hat_1in3:
            from oled_hat_1in3 import OLEDHat
            self._display = OLEDHat()
            self._input_devices.append(self._display)
            self._background_color = 255  # 黑白颠倒
            self._foreground_color = 0

        if self._config.use_pygame:
            from desktop_win import DesktopWin
            self._display = DesktopWin()
            self._input_devices.append(self._display)

        if self._config.use_mqtt:
            from mqtt_client import MQTTClient
            self._mqtt_client = MQTTClient(self._event_queue)
Пример #5
0
class Loop(Thread):

    com: common.Common = common.Common()
    mqtt: MQTTClient = MQTTClient(MessageReceiver(com), 'HTTPLooper')

    def __init__(self, config):
        self.mqtt.start_loop()
        for topic in config['topics']['subscribe']:
            self.mqtt.subscribe(topic)
        super(Loop, self).__init__()

    def run(self):

        jobs = self.com.jobs()

        while jobs > 0:
            for task in self.com.tasks():

                if task[0] == common.PUBLISH:
                    self.mqtt.publish(task[1], task[2])
                elif task[0] == common.SUBSCRIBE:
                    self.mqtt.subscribe(task[1])

            jobs = self.com.jobs()

        self.mqtt.stop_loop()

    def stop(self):
        self.com.stop()
Пример #6
0
    def __init__(self):

        self.is_on = False
        self.temp_f = 0
        self.temp_f_target = 212
        self.control_p = 2
        self.control_i = 0.1
        self.control_d = 2
        self.temp_history = []
        self.shed_on_time = None
        self.sched_off_time = None
        self.last_on_time = time.time()
        self.last_off_time = None
        self.pid_freq = 1
        self.read_freq = 10
        self.post_freq = 10
        self.stop_funcs = []
        self.mqtt_client = MQTTClient()
        self.pid = PID(self.control_p,
                       self.control_i,
                       self.control_d,
                       setpoint=self.temp_f_target)
        self.pid.output_limits = (0, 100)

        spi = SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
        cs = DigitalInOut(board.D5)
        self.sensor = MAX31855(spi, cs)

        he_pin = 26  # GPIO26
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(he_pin, GPIO.OUT)
        self.he_pwm = GPIO.PWM(he_pin, self.pid_freq * 3)
        self.he_pwm.start(0)
Пример #7
0
def main():
    global mqclient
    mqclient = MQTTClient(board.location, board.mqtt_server, ssl=True,
            ssl_params={'psk_ident':board.mqtt_ident, 'psk_key':board.mqtt_key})
    print("Connect:", mqclient.connect())

    mqclient.set_callback(msg_in)
    mqclient.subscribe(REPL_IN)
    print("Subscribed to", REPL_IN)
Пример #8
0
    def __init__(self):
        self.client = MQTTClient()

        # Messages from robots
        self.client.client.on_message = self.robot_message_received

        # Load/ Create Database
        self.data_base = FleetDatabase()
        self.db_connection = self.data_base.create_connection('Fleet_SQLite_Database.db')
        self.data_base.create_table(self.db_connection, self.data_base.table_sql)
Пример #9
0
 def start(self, stm_driver, login_gui):
     print("init HospiTalkie")
     self.name = "Ola"
     self.stm_driver = stm_driver
     self.login_gui = login_gui
     self.mqtt_client = MQTTClient(self.name, self.stm_driver)
     self.player = Player(self.stm_driver)
     self.recorder = Recorder(self.stm_driver)
     self.fileManager = FileManager(self.stm_driver)
     self.messageCounter = 0
     self.isBuffer = True
     self.sender = None
Пример #10
0
def main():
    client = MQTTClient(
        project_id=config.project_id,
        cloud_region=config.cloud_region,
        registry_id=config.registry_id,
        device_id=config.device_id,
        private_key_file=config.private_key_file,
        algorithm=config.jwt_algorithm,
        ca_certs=config.ssl_ca_certs,
        mqtt_bridge_hostname=config.mqtt_bridge_hostname,
        mqtt_bridge_port=config.mqtt_bridge_port
    )
    client.loop()
    loop = asyncio.get_event_loop()
    while True: 
        loop.run_until_complete(run(client))
Пример #11
0
 def __init__(self, channel, host, port, username=None, password=None):
     self.channel = channel
     self.host = host
     self.port = port
     self.client = MQTTClient(
         userdata={
             "server": self,
             "channel": self.channel,
             "host": self.host,
             "port": self.port,
         },
         callbacks={
             'on_connect': on_connect,
             'on_disconnect': on_disconnect,
             'on_message': on_message,
         }
     ).connect()
Пример #12
0
 def __init__(self):
     self.client = MQTTClient()
     while True:
         self.client.client.publish(
             "knx/fleet_manager/robot_state",
             json.dumps({
                 'position': {
                     'x': random.randint(0, 10),
                     'y': random.randint(0, 10)
                 },
                 'vehicle_id': 'AMR{}'.format(random.randint(0, 10)),
                 'driving': True,
                 'battery': 95.4,
                 'abort': False,
                 'order_id': None
             }))
         time.sleep(1)
Пример #13
0
class Archiver:

    client: MQTTClient = MQTTClient(StorageEngine, 'Archiver')

    def __init__(self):
        self.client.start_loop()
        self.client.subscribe('archiver/subscribe')
        self.client.subscribe('archiver/get')
        self.client.subscribe('archiver/stop')

    def run(self):

        try:
            while True:
                self.client.wait(2)
        except:
            self.client.stop_loop()
            self.client.disconnect()
            print('quitting')
Пример #14
0
    def __init__(self):
        self.client = MQTTClient()

        # Messages from robots
        self.client.client.on_message = self.robot_message_received

        # Websocket
        self.url = "ws://localhost:8888/websocket"
        self.connect_timeout = DEFAULT_CONNECT_TIMEOUT
        self.request_timeout = DEFAULT_REQUEST_TIMEOUT
        self.ws_conn = None
        self.ws_connected = False
        self.connect_ws(self.url)

        PeriodicCallback(self.keep_alive, 20000).start()
        try:
            ioloop.IOLoop.instance().start()
        except KeyboardInterrupt:
            self.close()
def main():
    parser = argparse.ArgumentParser(description='GCP arguments')
    parser.add_argument('--project', help='GCP project id')
    parser.add_argument('--registry', help='IoT registry id ')
    parser.add_argument('--region', help='Region of the IoT core registry')
    parser.add_argument('--device', help='id of the device to create')
    parser.add_argument('--cacerts', help='path to root certs')
    args = parser.parse_args()

    client = MQTTClient(args.project, args.registry, args.device, args.region,
                        args.cacerts)
    client.connect_to_server()

    payload = {}
    payload['connected'] = True
    payload['device'] = args.device

    client.send_event(args.device, json.dumps(payload))

    client.disconnect_from_server()
Пример #16
0
def main():
    # All things global should be defined here
    global firebaseApp
    global firebaseDB
    global lightEventsRef
    global carEventsRef
    global mqttClient
    global LED_HIGH
    global LED_LOW
    cred = credentials.Certificate(
        "mdec-5edc2-firebase-adminsdk-vg9vm-9c5355fe8e.json")
    firebaseApp = firebase_admin.initialize_app(cred)
    firebaseDB = database
    databaseURL = "https://mdec-5edc2.firebaseio.com/"
    lightEventsRef = database.reference("light/lightEvents", firebaseApp,
                                        databaseURL)
    carEventsRef = database.reference("car/carEvents", firebaseApp,
                                      databaseURL)

    mqttClient = MQTTClient()
    LED_HIGH = "D1"
    LED_LOW = "D2"
Пример #17
0
from mqtt_client import MQTTClient
import time

client = MQTTClient()

client.start_loop()

while True:
    client.publish('time/sync/current', str(time.time()))
    time.sleep(1)
Пример #18
0
##################################################
## MQTT Test
## Ensures MQTT Broker can be connected to
##################################################
## Unlicensed
##################################################
## Author: benchPSU
## Copyright: Copyright 2019, Spiroflow
## Credits: [Mark Gee, Joel Yeow, Harvin Iriawan, Raymond Ooi]
## License: None
## Version: 1.0
## Maintainer: Mark Gee
## Status: active
##################################################

# Import relevant modulesimport sys
import sys
sys.path.append("./mqtt_client")
import paho.mqtt.client as mqtt
from mqtt_client import MQTTClient

# Define connection variables
HOST = "test.mosquitto.org"
PORT = 8884
TOPIC = "IC.embedded/benchpsu"

client = MQTTClient(HOST, PORT, TOPIC)
print("MQTT test success!")
Пример #19
0
# http("http://192.168.1.133:8000/configuration/room/setpoint/update", "POST", JSON.stringify({"sensor":currentSensorSelection, "setpoint":currentSetpointValue, "time":time}))

import requests, random, time, json
from mqtt_client import Receiver, MQTTClient


class OnReceive(Receiver):
    def on_message(self, client, userdata, message):
        msg = str(time.time()) + "," + str(message.payload.decode("utf-8"))
        print(msg)


receiver = OnReceive()
client = MQTTClient(receiver, 'latency_tester')
client.subscribe('latency/response')

try:
    client.start_loop()

    timer = time.time()
    update = 1 / 1000
    sender = 0
    while True:
        t1 = time.time()
        t0 = t1 - timer
        if t0 >= update:
            print(str(time.time()) + ",send," + str(sender))
            requests.post(
                'http://192.168.1.133:8000/configuration/room/setpoint/update',
                data=json.dumps({
                    "sensor": '30:AE:A4:DF:9A:6C',
Пример #20
0
import atexit
from mqtt_client import MQTTClient


# at exit function
def cleanup(client):
    client.disconnect()
    client.loop_stop()


# do turnstile stuff
tester = MQTTClient()
atexit.register(cleanup, tester)
while True:  # block
    topic = (raw_input("enter topic name:\n")).strip()
    msg = (raw_input("enter message:\n")).strip()
    tester.publish(topic, msg)
Пример #21
0
def subscribe():
    from mqtt_client import MQTTClient
    MQTTClient().start()
Пример #22
0
from mqtt_client import MQTTClient
import ssl
import json
import paho.mqtt.client as mqtt

with open("config/config.json", "r") as load_f:
    parameter = json.load(load_f)

cli = MQTTClient(parameter["host"], parameter["port"])

cli.tls_set(parameter["ca_cert"], parameter["certfile"], parameter["keyfile"])

cli.on_log

cli.connect(parameter["username"], parameter["password"])

cli.on_connect

cli.subscribe(parameter["topic0"])

cli._on_message

cli.loop()
Пример #23
0
class OnReceive(Receiver):
    def on_message(self, client, userdata, message):
        global room_name

        msg = str(message.payload.decode("utf-8"))

        if message.topic == sensor_name + '/room/config':
            msg = json.loads(msg)
            room_name = msg['room']
            update_config(msg)
            print(msg)


# get_room_data()
receiver = OnReceive()
client = MQTTClient(receiver)

client.start_loop()

client.subscribe(sensor_name + '/room/config')

if room_name is None:
    client.publish('sensor/registration', sensor_name + '/temperature')
    client.publish('sensor/registration', sensor_name + '/humidity')
    client.publish('sensor/registration', sensor_name + '/lux')

try:
    while True:
        if room_name != None:

            temperature = str(get_temperature())