示例#1
0
def main():
    logger.info(f"Starting server")

    settings = load_settings()

    client: Optional[TransportClient] = None
    if settings.mqtt:
        client = MqttClient(host_name, settings.mqtt)

    if settings.signalr:
        client = SignalRClient(settings.signalr)

    if not client:
        raise Exception("No transport client was created")

    client.start(on_request_receive)

    while is_running:
        ip_address = get_host_ip()
        update_known_printers(settings)

        status = HostStatus(online=True,
                            ip=ip_address,
                            host=host_name,
                            update_s=settings.printer_check_period_s,
                            printers=[
                                p.info() for p in printers.values()
                                if p.info().model is not None
                            ])
        client.publish(status)
        time.sleep(settings.printer_check_period_s)
示例#2
0
文件: run_pub.py 项目: fstakem/pyedj
def main():
    args = get_arguments()
    server = args.server
    port = int(args.port)
    topic = args.topic

    print('Parameters')
    print(f'Server: {server}')
    print(f'Port: {port}')
    print(f'Topic: {topic}')
    print()

    client = MqttClient()
    client.connect(server, port, 60)

    while True:
        timestamp = datetime.utcnow()
        num = random() * 100
        msg = {
                'timestamp': timestamp.strftime("%Y-%m-%d %H:%M:%S"),
                'value': num}

        print(f'Publishing: {msg}')
        client.publish(topic, json.dumps(msg))
        time.sleep(3)
示例#3
0
def send_mqtt_msgs(service_info, msgs, interval_sec):
    client = MqttClient()
    client.connect(service_info['host'], service_info['protocol']['port'], 60)

    for msg in msgs:
        client.publish(service_info['protocol']['publish']['default_topic'],
                       json.dumps(msg))
        time.sleep(interval_sec)
示例#4
0
def main():
    print("Getting IP address")
    ip_address = get_ip_address('wlan0')
    print("IP address " + ip_address)
    ser = serial.Serial('/dev/ttyUSB0', 9600)
    print("Serial connected ")
    renderer_client = RendererClient(ip_address)
    print("Connecting MQTT client")
    mqtt_client = MqttClient(on_connect, on_message, (renderer_client, ser))

    print("Proceeed to drawing part")

    while (True):
        sensorData = ser.readline()
        while (sensorData):
            renderer_client.setSensorData(sensorData)
            mqtt_client.publish("SENSOR", renderer_client.getState())
            sensorData = ser.readline()
class SmartHomeController:
    device_controller = None
    mqtt_client = None
    device_serial = None
    devices = None
    loop_thread = None
    publish_thread = None

    def __init__(self):
        self.device_serial = self.get_device_serial()
        self.device_controller = DeviceController(devices_config)
        self.devices = self.device_controller.get_devices_info()
        topics = [self.device_serial + "/#"]

        print(self.devices)

        self.mqtt_client = MqttClient(mqtt_config, topics,
                                      self.onMessageReceivedCallback)
        self.mqtt_client.connect(self.device_serial)

        self.loop_thread = threading.Thread(target=self.mqtt_client.loop,
                                            daemon=True)
        self.publish_thread = threading.Thread(
            target=self.publish_device_data_periodically, daemon=True)

    def onMessageReceivedCallback(self, mqttc, user_data, msg):
        if (msg.topic == (self.device_serial + "/devices/info/req")):
            self.mqtt_client.publish(
                self.device_serial + "/devices/info",
                json.dumps(self.device_controller.get_devices_info()))
            return

        device = msg.topic.split("/")[1]
        devices_names = list(self.devices.keys())

        if (device in devices_names):
            # Set device state
            message = msg.payload.decode("utf-8")
            active = None

            if (message == "On"):
                active = True

            if (message == "Off"):
                active = False

            self.device_controller.set_device_active(device, active)
            self.mqtt_client.publish(
                self.device_serial + "/devices/" + device + "/status",
                json.dumps(self.device_controller.get_devices_info()[device]))

    def publish_device_data_periodically(self):
        # Periodically send devices info
        while True:
            self.mqtt_client.publish(
                self.device_serial + "/devices/info",
                json.dumps(self.device_controller.get_devices_info()))
            time.sleep(10)

    def run(self):
        # Start threads and wacth their status
        while True:
            loop_thread_alive = sh.loop_thread.isAlive()
            publish_thread_alive = sh.publish_thread.isAlive()

            print("loop thread active: " + str(loop_thread_alive))
            print("publish thread active: " + str(publish_thread_alive))

            if not loop_thread_alive:
                sh.loop_thread.start()

            if not publish_thread_alive:
                sh.publish_thread.start()

            time.sleep(1)

    @staticmethod
    def get_device_serial():
        device_serial = "0000000000000000"

        with open('/proc/cpuinfo', 'r') as f:
            device_serial = f.read()
            search = re.search(r"\nSerial\s+:\s+(?P<serial>[0-9a-f]{16})",
                               device_serial)

            if search is None:
                raise BaseException("Cannot find device serial!")

        return search.group("serial")
示例#6
0
import json
import time
from random import random
from datetime import datetime

from mqtt_client import MqttClient

server = 'localhost'
port = 1883
topic = 'ingestion/test/'

client = MqttClient()
client.connect(server, port, 60)

while True:
    timestamp = datetime.utcnow()
    num = random() * 100
    msg = {'timestamp': timestamp.strftime("%Y-%m-%d %H:%M:%S"), 'value': num}
    print(f'Publishing: {msg}')
    client.publish(topic, json.dumps(msg))
    time.sleep(3)