def on_message(client, userdata, msg):
    msgs = [{'topic':"information/service/log", 'payload':str(msg.payload)},
    ("information/system/log", str(msg.payload), 0, False)]
    publish.multiple(msgs, hostname=broker_main)

    # messafe filtering

    if (msg.topic=="control/service/" + service_type + "/" + service_name + "/power"):
        if(msg.payload=="off"):
            power_off()
        elif(msg.payload=="on"):
            power_on()
    
    if (msg.topic=="control/service/" + service_type + "/" + service_name + "/tuning"):
        if(msg.payload=="increase"):
            increase_temperature()
        elif(msg.payload=="decrease"):
            decrease_temperature()
def main():
    payload = []
    cpuPercent = psutil.cpu_percent()
    memoryUtilization = psutil.virtual_memory().percent
    diskPercent = psutil.disk_usage('/').percent
    #print(f'CPU: {cpuPercent}\nMemory: {memoryUtilization}\nDisk: {diskPercent}\n')
    payload.append({"topic": MQTT_TOPIC_PREFIX + "cpu", "payload": cpuPercent})
    payload.append({
        "topic": MQTT_TOPIC_PREFIX + "memory",
        "payload": memoryUtilization
    })
    payload.append({
        "topic": MQTT_TOPIC_PREFIX + "disk",
        "payload": diskPercent
    })

    # Publish to MQTT
    will = {
        "topic": MQTT_AVAILABLE_TOPIC,
        "payload": "offline",
        "retain": True
    }
    publish.multiple(payload,
                     hostname=MQTT_HOST,
                     client_id="app_server_system_monitor",
                     keepalive=MQTT_KEEP_ALIVE,
                     will=will)
    def publish_multiple(self, msgs, hostname="localhost", port=1883,
            client_id="", keepalive=60, will=None, auth=None,
            tls=None, protocol=mqtt.MQTTv31):

        """ Publish multiple messages and disconnect. This keyword uses the
        [http://eclipse.org/paho/clients/python/docs/#multiple|multiple]
        function of publish module.

        `msgs` a list of messages to publish. Each message is either a dict
                or a tuple. If a dict, it must be of the form:
                msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>,
                        'retain':<retain>}
                Only the topic must be present. Default values will be used
                for any missing arguments. If a tuple, then it must be of the
                form:
                ("<topic>", "<payload>", qos, retain)

                See `publish single` for the description of hostname, port,
                client_id, keepalive, will, auth, tls, protocol.

        Example:

        | ${msg1} | Create Dictionary | topic=${topic} | payload=message 1 |
        | ${msg2} | Create Dictionary | topic=${topic} | payload=message 2 |
        | ${msg3} | Create Dictionary | topic=${topic} | payload=message 3 |
        | @{msgs} | Create List | ${msg1} | ${msg2} | ${msg3} |
        | Publish Multiple | msgs=${msgs} | hostname=127.0.0.1 |

        """
        logger.info('Publishing to: %s:%s, msgs: %s' %
                    (hostname, port, msgs))
        publish.multiple(msgs, hostname, port, client_id, keepalive,
                        will, auth, tls, protocol)
Esempio n. 4
0
def send(msg, user_list, qos=2, retain=False):
    """
    发布mqtt消息
    :param msg:消息内容,可以是字符串、int、bytearray
    :param user_list: 用户列表数组(不带前缀的),例如:["zhangsan","lilei"]
    :param qos: 消息质量(0:至多一次,1:至少一次,2:只有一次)
    :param retain:设置是否保存消息,为True时当订阅者不在线时发送的消息等上线后会得到通知,否则只发送给在线的设备
    :return:
    """
    auth = {"username": MOSQUITTO_PUB_USER, "password": MOSQUITTO_PUB_PWD}
    client_id = MOSQUITTO_PREFIX + str(uuid.uuid1())
    msgs = []
    for i in user_list:
        print(i)
        msg_obj = dict()
        msg_obj["qos"] = qos
        msg_obj["retain"] = retain
        msg_obj["topic"] = MOSQUITTO_TOPIC_PREFIX + str(i)
        msg_obj["payload"] = msg
        msgs.append(msg_obj)
    if len(msgs) > 0 and msg:
        print(msgs)
        try:
            publish.multiple(msgs, hostname=MOSQUITTO_HOST, port=MOSQUITTO_PORT, client_id=client_id, keepalive=60,
                             will=None, auth=auth, tls=None, protocol=MQTTv31)
            ret = 1
        except Exception as e:
            print(str(e))
            ret = -1
    else:
        ret = -2
    return ret
Esempio n. 5
0
def main_loop():
    msg_time = ("state/opi/time", get_time(), 0, False)

    msg_cpu_temperature = ("state/opi/cpu_temperature", get_cpu_temperature(),
                           0, False)
    msg_cpu_frequency = ("state/opi/cpu_frequency", get_cpu_frequency(), 0,
                         False)

    env_temperature, env_humidity = get_si7021_data()
    msg_env_temperature = ("state/opi/env_temperature",
                           ("%.2f" % env_temperature), 0, False)
    msg_env_humidity = ("state/opi/env_humidity", ("%.2f" % env_humidity), 0,
                        False)

    msgs = [
        msg_time, msg_cpu_temperature, msg_cpu_frequency, msg_env_temperature,
        msg_env_humidity
    ]

    try:
        publish.multiple(msgs,
                         hostname=MQTT_SERVER,
                         port=MQTT_SERVER_PORT,
                         client_id=MQTT_CLIENT_ID)
    except BaseException:
        mlogger.logger.warning("MQTT Publish error.")

    threading.Timer(MQTT_PUBLISH_PERIOD, main_loop).start()
Esempio n. 6
0
def main_loop(owm, mqtt_host, base_topic, period):
    msgs = []
    while True:
        try:
            weather = owm.get()
        except OWMError as err:
            print("Error: ", err)

        json_data = json.loads(weather.to_JSON())

        for key, value in json_data.items():
            # hack for temperature in unit=Celsius
            if key == 'temperature':
                value = weather.get_temperature(unit='celsius')
            # msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>,
            #  'retain':<retain>}
            if not isinstance(value, dict):
                msg = {}
                msg['topic'] = base_topic + '/' + key
                msg['payload'] = value
                msgs.append(msg)
            else:
                chain_topic = base_topic + '/' + key
                for key2, value2 in value.items():
                    msg = {}
                    msg['topic'] = chain_topic + '/' + key2
                    msg['payload'] = value2
                    msgs.append(msg)

        publish.multiple(msgs, hostname="mqtt", port=1883, client_id="owmpub")
        sleep(period)
Esempio n. 7
0
def main(mqtt_host, mqtt_port, state_file, not_home, debug):
    mqtt_messages = []
    now = time.time()

    with State(state_file) as state:
        a = read_in()
        for b in a:
            mac_address = ":".join(
                format(int(x), "02x") for x in b.split(" ")[0].split(".")[13:])
            state[mac_address] = time.time()

        for mac_address, epoch in dict(state).iteritems():
            if epoch + not_home < now:
                payload = "not_home"
            else:
                payload = "home"
            mqtt_messages.append({
                "topic": "location/{0}".format(mac_address),
                "payload": payload
            })
    if not debug:
        publish.multiple(mqtt_messages, mqtt_host, mqtt_port)
    else:
        print mqtt_messages
    return 0
def updateMqtt(NeoStat, updateInterval):
    cfg = SafeConfigParser()
    cfg.optionxform = str
    cfg.read(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/neohub.conf"))
    host = cfg.get("mqtt", "hostname")
    port = eval(cfg.get("mqtt", "port"))
    topic = cfg.get("mqtt", "topic")
    qos = eval(cfg.get("mqtt", "qos"))
    retain = eval(cfg.get("mqtt", "retain"))
    client_id =  "neohub" + NeoStat.name  + str(os.getpid())
    if eval(cfg.get("mqtt", "auth")):
        auth = {"username": cfg.get("mqtt", "user"), "password": cfg.get("mqtt", "password")}
    else:
        auth = None

    while True:
        try:
            NeoStat.update()
            time.sleep(updateInterval)

            msgs = [{"topic": topic + NeoStat.name, "payload": """{ "temperature" : """ + str(NeoStat.current_temperature)
            + """, "status" : """ + "\"" + NeoStat.operation + "\"" "  "
            + "}", "qos": qos, "retain": retain}]

            log.debug("msgs = " + str(msgs))

            publish.multiple(msgs, hostname=host, port=port, client_id=client_id, auth=auth)
        except:
            log.error("Unable to publish message")
Esempio n. 9
0
    def easy_multiple(self,
                      msgs,
                      hostname="localhost",
                      port=1883,
                      keepalive=60,
                      will=None,
                      auth=None,
                      tls=None):
        """
        Publish multiple messages to a broker, then disconnect cleanly.
        arguments:
            msgs
            a list of messages to publish. Each message is either a dict or a tuple.
            If a dict, only the topic must be present. Default values will be used for any missing arguments. The dict must be of the form:
            msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>, 'retain':<retain>}
            topic must be present and may not be empty. If payload is "", None or not present then a zero length payload will be published. If qos is not present, the default of 0 is used. If retain is not present, the default of False is used.
            If a tuple, then it must be of the form:
            ("<topic>", "<payload>", qos, retain)

            See easy_publish() for the description of hostname, port, keepalive, will, auth, tls.

            e.g:
            msgs = [{'topic':"paho/test/multiple", 'payload':"multiple 1"},
                ("paho/test/multiple", "multiple 2", 0, False)]
            easy_multiple(msgs, hostname="iot.eclipse.org")            
        """
        import paho.mqtt.publish as publish
        publish.multiple(msgs, hostname, port, keepalive, will, auth, tls)
Esempio n. 10
0
def run():
    try:
        ser = serial.Serial('/dev/ttyAMA0', 38400)
        line = ser.readline().decode('utf-8').strip()
        line_values = line.split()

        topics = (
            '/current/nodeid',
            '/current/1',
            '/current/2',
            '',
            # '/current/3',
        )

        # Convert all read values to float
        values = map(float, line_values)

        # Shape a nested list of all the [topic, value] we want to send in one shot using function publish.multiple.
        mqtt_message = [[topic, value] for topic, value in zip(topics, values)
                        if topic]

        # Send the message
        publish.multiple(hostname=MQTT_BROKER, port=MQTT_PORT, mqtt_message)

    except:
        traceback.print_exc()

    finally:
        ser.close()
        mqtt_client.disconnect()
Esempio n. 11
0
def publish_adafruit():

    adafruit_username = "******"
    adafruit_key = "f38fefdd1fa94e2aaec9fd857b036e19"

    sensors_data = mongo_read()
    # print(sensors_data)  # FIXME: DEBUG

    msgs = []

    for sensor in sensors_data:
        # sensor[0] = sensor name
        # sensor[1] = sensor data
        # QoS = 0
        # Retain = True
        # ex.: andreibosco/f/sink_temperature, 29.37, 0, True
        msg = (adafruit_username + "/f/sink_" + str(sensor[0]), str(sensor[1]),
               0, True)
        msgs.append(msg)

    # print("Messages :", msgs)  # FIXME: DEBUG

    publish.multiple(msgs,
                     hostname="io.adafruit.com",
                     port=1883,
                     auth={
                         "username": adafruit_username,
                         "password": adafruit_key
                     })

    logging.info("Published to adafruit")  # FIXME: DEBUG

    return True
def publishStates(green, yellow, red):
    # Publish a message
    #Create JSON strings
    greenState_json = json.dumps({
        "Green State = ": green,
        "TimeStamp = ": time.time()
    })
    yellowState_json = json.dumps({
        "Yellow State = ": yellow,
        "TimeStamp = ": time.time()
    })
    redState_json = json.dumps({
        "Red State = ": red,
        "TimeStamp = ": time.time()
    })

    #Create array of MQTT messages
    green_msg = {"/Green State", "payload" + greenState_json}
    yellow_msg = {"/Yellow State", "payload" + yellowState_json}
    red_msg = {"/Red State", "payload" + redState_json}

    msgs = [green_msg, yellow_msg, red_msg]

    #Publish array of messages
    print("About to publish")
    publish.multiple(msgs, hostname=url.hostname, port=url.port, auth=auth)
    print("published")
    def on_file_received(self, file):
        # do something when a file has been received
        print('on_file_received', file)
        split_fpath = file.split('/')
        cam_name = split_fpath[-4]
        # TODO: fix image to be a format that Telegraf will recognise:
        encoded_image = self.convertImageToBase64(file)
        # self.convertImageToBase64(file).decode('ascii')
        print('encoded image ends with:',encoded_image[-10:-1])

        # Payload is using InfluxDB Line protocol format:
        # motion,sensor_type=camera,device_name=<> value=-60
        # = measurement,tag=tag1 measurement_name=vale <optional_timestamp>
        # publish a message for the image and for the indicator of motion:
        publish.multiple(
            [{
                "topic":"cached_file/camera_image/{}".format(cam_name),
                "payload":"images,type=image,device_name={} value={}".format(cam_name, str(encoded_image))
            },
            {
                "topic": "cached/camera_motion/{}".format(cam_name),
                "payload": "motion,type=motion,device_name={} value={}".format(cam_name, int(1))
            }],
            hostname=mqtt_host,
            port=mqtt_port
        )
Esempio n. 14
0
    def output(self, data=None, tag=None, mqtt_broker="localhost", mqtt_user=None, mqtt_pass=None):
        log.info("Using output processor: hass_config")
        if data is None:
            return

        if mqtt_user is not None and mqtt_pass is not None:
            auth = {"username": mqtt_user, "password": mqtt_pass}
            log.info(f"Using mqtt authentication, username: {mqtt_user}, password: [supplied]")
        else:
            log.debug("No mqtt authentication used")
            auth = None

        # Build array of mqtt messages with hass autoconfig format
        msgs = []
        # Remove command and _command_description
        data.pop("_command", None)
        data.pop("_command_description", None)
        # Loop through responses
        for key in data:
            # value = data[key][0]
            unit = data[key][1]
            # <discovery_prefix>/<component>/[<node_id>/]<object_id>/config
            # topic "homeassistant/binary_sensor/garden/config"
            # msg '{"name": "garden", "device_class": "motion", "state_topic": "homeassistant/binary_sensor/garden/state", "unit_of_measurement": "°C"}'
            topic = f"homeassistant/sensor/pm_{tag}_{key}/config"
            payload = f'{{"name": "pm_{tag}_{key}", "state_topic": "homeassistant/sensor/pm_{tag}_{key}/state", "unit_of_measurement": "{unit}"}}'
            msg = {"topic": topic, "payload": payload, "retain": True}
            msgs.append(msg)
        publish.multiple(msgs, hostname=mqtt_broker, auth=auth)
Esempio n. 15
0
def iothub_client_telemetry_sample_run():

    try:
            client = iothub_client_init()

            # Build the message with simulated telemetry values.
            temperature,pressure,humidity = readBME280All()
            humidity = round(humidity, 2)
            msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity, pressure=pressure)
            message = Message(msg_txt_formatted, content_encoding='utf-8', content_type='application/json')

            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            if temperature > 30:
              message.custom_properties["temperatureAlert"] = "true"
            else:
              message.custom_properties["temperatureAlert"] = "false"

            # Send the message.
            print( "Sending message: {}".format(message) )
            client.send_message(message)
            publish.multiple([
                {'topic': "balkon/temperature", 'payload': temperature},
                {'topic': "balkon/humidity", 'payload': humidity}
                ], hostname="192.168.0.138")
            print ( "Message successfully sent" )

    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Esempio n. 16
0
def publish(msg_list=[], payload=None, keep=False, **kws):
    """
    :param msg_list: list: containing dicts w/ fields 'topic', 'payload', 'qos', 'retain'
    :param keep: bool: flag for retaining, used only with single message in list
    """
    print(f"publishing {len(msg_list)} to {kws['data']['topic']}")
    if len(msg_list):
        pubber.multiple(
            msgs=msg_list,
            hostname=kws["host"],
            port=kws["port"],
            keepalive=kws["keepalive"],
            protocol=mqtt.MQTTv311,
            transport="tcp"
        )
    else:
        pubber.single(
            topic=kws["data"]["topic"],
            payload=payload,
            qos=kws["data"]["qos"],
            retain=keep,
            hostname=kws["host"],
            port=kws["port"],
            keepalive=kws["keepalive"],
            protocol=mqtt.MQTTv311,
            transport="tcp"
        )
Esempio n. 17
0
def publish_messages(ping, upload, download, cfg):
    auth = {'username': cfg['mqtt']['user'], 'password': cfg['mqtt']['pw']}
    discovery_msgs = [(cfg['upload']['discovery_topic'], create_discovery_message(cfg['upload']['discovery_name'], cfg['upload']['state_topic'], 'MBit/s'), 0, True),\
                     (cfg['download']['discovery_topic'], create_discovery_message(cfg['download']['discovery_name'], cfg['download']['state_topic'], 'MBit/s'), 0, True),\
                     (cfg['ping']['discovery_topic'], create_discovery_message(cfg['ping']['discovery_name'], cfg['ping']['state_topic'], 'ms'), 0, True)]
    try:
        publish.multiple(discovery_msgs,
                         hostname=cfg['mqtt']['host'],
                         client_id=cfg['mqtt']['client_id'],
                         port=cfg['mqtt']['port'],
                         auth=auth)
    except ConnectionError:
        print("Unable to publish discovery messages via mqtt:",
              file=sys.stderr)
        traceback.print_exc(file=sys.stderr)

    state_msgs = [(cfg['ping']['state_topic'], ping, 0, False),\
                  (cfg['upload']['state_topic'], upload, 0, False),\
                  (cfg['download']['state_topic'], download, 0, False)]
    try:
        publish.multiple(state_msgs,
                         hostname=cfg['mqtt']['host'],
                         client_id=cfg['mqtt']['client_id'],
                         port=cfg['mqtt']['port'],
                         auth=auth)
    except ConnectionError:
        print("Unable to publish state messages via mqtt:", file=sys.stderr)
        traceback.print_exc(file=sys.stderr)
Esempio n. 18
0
def main(args):
    auth = {}
    if args.password and args.username:
        auth["password"] = args.password
        auth["username"] = args.username
    while True:
        messages = []
        with prpd.open(args) as reader:
            for command, field, _time, value in reader.read():
                if args.payload_simple:
                    payload = value
                else:
                    payload = {
                        "value": value,
                        "unit": field.unit,
                    }
                messages.append({
                    "topic": f"{args.prefix}/{command.name}/{field.name}",
                    "payload": json.dumps(payload),
                })
        publish.multiple(messages,
                         hostname=args.hostname,
                         port=args.port,
                         auth=auth)
        time.sleep(args.interval)
Esempio n. 19
0
    def __mqtt_publish(self, msg):
        basetopic = 'dashboard/chromecast/' + self.device.cast_type + '/'
        msg = [
            {
                'topic':
                basetopic + 'media',
                'payload':
                (json.dumps(msg.media,
                            default=lambda o: o.__dict__)).encode('utf-8'),
                'retain':
                True
            },
            {
                'topic':
                basetopic + 'app',
                'payload':
                (json.dumps(msg.app,
                            default=lambda o: o.__dict__)).encode('utf-8'),
                'retain':
                True
            },
            {
                'topic': basetopic + 'state',
                'payload': msg.player_state,
                'retain': True
            },
        ]

        publish.multiple(msg, hostname=self.mqtthost, port=self.mqttport)
Esempio n. 20
0
def lowerfps_thread():
    global threadstate, Maxcount, MaxBandwidth
    index = 0
    while threadstate:
        try:
            if index == Maxcount:
                index = 0
            msgs = \
            [
                {
                    'topic': HighResolution[index],
                    'payload': "down"
                }
            ]
            publish.multiple(msgs, hostname="61.253.199.32")
            time.sleep(3)
            msgs = \
                [
                    {
                        'topic': HighResolution[index],
                        'payload': "up"
                    }
                ]
            publish.multiple(msgs, hostname="61.253.199.32")
            index += 1
        except IndexError:
            threadstate = False
Esempio n. 21
0
    def output(self, sensor):
        dictionary = sensor.dictionary()

        msgs = []

        for type in sensor.sensor_data_types():
            topic = config.mqtt_sensor_topic_format.format(
                self.__hostname, type, sensor.id)

            msg = {
                'topic': topic,
                'payload': dictionary[type],
                'qos': self.__mqtt_cfg.qos,
                'retain': self.__mqtt_cfg.retain
            }
            msgs.append(msg)

            if self.__verbose:
                print "DBG: Publishing value '{}' to topic '{}'".format(
                    dictionary[type], topic)

        import paho.mqtt.publish as publish
        publish.multiple(msgs,
                         hostname=self.__mqtt_cfg.mqtt_host,
                         port=self.__mqtt_cfg.port,
                         client_id=self.__mqtt_cfg.client_id,
                         keepalive=self.__mqtt_cfg.keepalive)

        if self.__verbose:
            print "DBG: Messages published"
Esempio n. 22
0
def process():
    ups = subprocess.run(["upsc", "ups@" + ups_host], stdout=subprocess.PIPE)
    lines = ups.stdout.decode('utf-8').split('\n')

    msgs = []

    for line in lines:
        fields = line.split(':')
        if len(fields) < 2:
            continue

        key = fields[0].strip()
        value = fields[1].strip()

        if cached_values.get(key, None) != value:
            cached_values[key] = value
            topic = base_topic + key.replace('.', '/').replace(' ', '_')
            msgs.append((topic, value, 0, True))

        timestamp = time.time()
        msgs.append((base_topic + 'timestamp', timestamp, 0, True))
        msgs.append((base_topic + 'lastUpdate',
                     datetime.datetime.fromtimestamp(timestamp).strftime(
                         '%Y-%m-%d %H:%M:%S %Z'), 0, True))
        mqtt.multiple(msgs, hostname=mqtt_host, port=mqtt_port)
Esempio n. 23
0
    def publish_multiple(self, messages):
        """Publish multiple messages at once.

        This publishes the messages to the remote broker.

        Parameters
        ----------
        messages : Message[]
            The messages to publish.
        """
        # ensure type
        msgs = []
        for message in messages:
            assert isinstance(message, Message)
            msgs.append((message.topic(), message.payload()))
        # prep auth
        auth = None
        if self.username is not None:
            auth = {"username": self.username, "password": self.password}
        # publish messages
        Logger.trace('Publishing messages',
                     fields={
                         'count': len(msgs),
                         'host': self.host,
                         'port': self.port,
                         'auth': True if auth is not None else False
                     })
        MqttPublisher.multiple(msgs,
                               hostname=self.host,
                               port=self.port,
                               auth=auth)
Esempio n. 24
0
def publish_temps_aws(temps, config):
    '''Publish temperature readings to AWS IoT.

    temps: iterable
    config: AWS IoT configuration
    '''
    # for each temperature reading, publish to `topic/sensor_id`
    messages = []
    topic = config['topic']
    for t in temps:
        messages.append({
            'topic': '{}/{}'.format(topic, t['sensor_id']),
            'payload': json.dumps(t)
        })

    if messages:
        # configure TLS for secure connection
        certs = config['certs']
        tls = dict(
            ca_certs=certs['ca_certs'],
            certfile=certs['certfile'],
            keyfile=certs['keyfile'],
            tls_version=ssl.PROTOCOL_TLSv1_2,
            ciphers=None
        )
        print('Publishing to {host}:{port}'.format(
            host=config['host'], port=config['port'],
        ))
        publish.multiple(
            messages,
            hostname=config['host'],
            port=config['port'],
            tls=tls
        )
Esempio n. 25
0
def determin(v1, v2, v3):
    global status
    global result
    global flag
    print(
        "v1.avg : {}, v2.avg : {} v3.avg : {}, result : {}, flag : {}, status : {}"
        .format(v1, v2, v3, result, flag, status))
    #if -> first and is or
    #1->down, 2->up, 0->stop
    if (abs(v1 - v2) > allow_gap
            or abs(v1 - v3) > allow_gap and hasPeople == True):  #down
        status = 1
    if (abs(v1 - v3) < allow_gap and abs(v1 - v2) < allow_gap
            and hasPeople == True):  #stop
        status = 0
    elif (hasPeople == False):  #up
        status = 2
    result.append(status)
    if (len(result) > 2):  #만약 길이가3보다크다면
        result.pop(0)
    if (flag != status and sum(result) / SIZE == status):
        flag = status
        msgs = [{'topic': '/status/toTx2', 'payload': flag, 'qos': 0}]
        print(msgs)
        publish.multiple(msgs, hostname=brokerIP)
Esempio n. 26
0
def sendMsg():
    msgs = []
    global idx
    nowStr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    topic = "stagebo/chatroom"


    msg = {
        "time": nowStr,
        "data": "this is data."
    }


    msgItem = {'topic': topic, 'payload': msg, 'qos': qos}
    # msgItem = (topic,msg)
    msgs.append(msgItem)
    print(idx)
    publish.multiple(msgs,
                     auth={
                         'username': username,
                         'password': password
                     },
                     port=port,
                     protocol=mqtt.MQTTv311,
                     hostname=hostname)


    idx += 1
Esempio n. 27
0
def publish_temps_aws(temps, config):
    '''Publish temperature readings to AWS IoT.

    temps: iterable
    config: AWS IoT configuration
    '''
    # for each temperature reading, publish to `topic/sensor_id`
    messages = []
    topic = config['topic']
    for t in temps:
        messages.append({
            'topic': '{}/{}'.format(topic, t['sensor_id']),
            'payload': json.dumps(t)
        })

    if messages:
        # configure TLS for secure connection
        certs = config['certs']
        tls = dict(ca_certs=certs['ca_certs'],
                   certfile=certs['certfile'],
                   keyfile=certs['keyfile'],
                   tls_version=ssl.PROTOCOL_TLSv1_2,
                   ciphers=None)
        print('Publishing to {host}:{port}'.format(
            host=config['host'],
            port=config['port'],
        ))
        publish.multiple(messages,
                         hostname=config['host'],
                         port=config['port'],
                         tls=tls)
Esempio n. 28
0
def publish_split_topic_dsmr_reading(reading):
    """ Publishes a DSMR reading to a broker, formatted in a separate topic per field name, if set and enabled. """
    split_topic_settings = telegram.SplitTopicTelegramMQTTSettings.get_solo()

    if not split_topic_settings.enabled:
        return

    # User specified formatting.
    config_parser = configparser.ConfigParser()
    config_parser.read_string(split_topic_settings.formatting)
    topic_mapping = config_parser['mapping']

    mqtt_messages = []
    serialized_reading = json.loads(serializers.serialize('json', [reading]))
    reading_fields = dict(serialized_reading[0]['fields'].items())
    reading_fields['id'] = serialized_reading[0]['pk']

    # Copy all fields described in the mapping.
    for k, v in reading_fields.items():
        if k not in topic_mapping:
            continue

        mqtt_messages.append({
            'topic': topic_mapping[k],
            'payload': v,
        })

    broker_kwargs = get_broker_configuration()

    try:
        publish.multiple(msgs=mqtt_messages, **broker_kwargs)
    except ValueError as error:
        logger.error(
            'MQTT publish_split_topic_dsmr_reading() | {}'.format(error))
Esempio n. 29
0
def publish_multiple(
    list_of_topic_message_tuples, hostname=leader_hostname, retries=10, **mqtt_kwargs
):
    """
    list_of_topic_message_tuples is of the form ("<topic>", "<payload>", qos, retain)

    """
    for retry_count in range(retries):
        try:
            mqtt_publish.multiple(
                list_of_topic_message_tuples, hostname=hostname, **mqtt_kwargs
            )
            return
        except (ConnectionRefusedError, socket.gaierror, OSError, socket.timeout):
            # possible that leader is down/restarting, keep trying, but log to local machine.
            from pioreactor.logging import create_logger

            logger = create_logger("pubsub.publish_multiple", to_mqtt=False)
            logger.debug(
                f"Attempt {retry_count}: Unable to connect to host: {hostname}",
                exc_info=True,
            )
            time.sleep(5 * retry_count)  # linear backoff

    else:

        logger = create_logger("pubsub.publish_multiple", to_mqtt=False)
        logger.error(f"Unable to connect to host: {hostname}. Exiting.")
        raise ConnectionRefusedError(f"Unable to connect to host: {hostname}.")
def pubService():

    items = [
        '[OPC_Sample]Program:MainProgram.OUTPUT1',
        '[OPC_Sample]Program:MainProgram.OUTPUT2',
        '[OPC_Sample]Program:MainProgram.INPUT'
    ]
    while True:
        try:
            opc = OpenOPC.client()
            opc.connect('RSLinx OPC Server')
            opcData = opc.read(items)
        except:
            print "pubService OPC exception"
        else:
            msgs = []
            for i in opcData:
                msgs.append(("opcsample/get/" + i[0] + "/", i[1], 0, False))
            try:
                publish.multiple(msgs,
                                 hostname="***.eercan.com",
                                 auth={
                                     'username': "******",
                                     'password': "******"
                                 })
            except:
                print "pubService MQTT exception, sleeping 5 sec"
                time.sleep(5)
            time.sleep(1)
            opc.close()
def mqtt_publish(msgs):
    # Publish the sensor data to mqtt broker
    try:
        _LOGGER.info("Sending messages to mqtt broker...")
        if "mqtt_username" in CONFIG and CONFIG[
                "mqtt_username"] != "" and "mqtt_password" in CONFIG and CONFIG[
                    "mqtt_password"] != "":
            auth = {
                'username': CONFIG["mqtt_username"],
                'password': CONFIG["mqtt_password"]
            }
        else:
            auth = None
        publish.multiple(msgs,
                         hostname=CONFIG["mqtt_host"],
                         port=CONFIG["mqtt_port"],
                         client_id="airthings-mqtt",
                         auth=auth)
        _LOGGER.info("Done sending messages to mqtt broker.")
    except MQTTException as e:
        _LOGGER.error(
            "Failed while sending messages to mqtt broker: {}".format(e))
    except:
        _LOGGER.exception(
            "Unexpected exception while sending messages to mqtt broker.")
    def publish_multiple(self, msgs, hostname="localhost", port=1883,
            client_id="", keepalive=60, will=None, auth=None,
            tls=None, protocol=mqtt.MQTTv31):

        """ Publish multiple messages and disconnect. This keyword uses the
        [http://eclipse.org/paho/clients/python/docs/#multiple|multiple]
        function of publish module.

        `msgs` a list of messages to publish. Each message is either a dict
                or a tuple. If a dict, it must be of the form:
                msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>,
                        'retain':<retain>}
                Only the topic must be present. Default values will be used
                for any missing arguments. If a tuple, then it must be of the
                form:
                ("<topic>", "<payload>", qos, retain)

                See `publish single` for the description of hostname, port,
                client_id, keepalive, will, auth, tls, protocol.

        Example:

        | ${msg1} | Create Dictionary | topic=${topic} | payload=message 1 |
        | ${msg2} | Create Dictionary | topic=${topic} | payload=message 2 |
        | ${msg3} | Create Dictionary | topic=${topic} | payload=message 3 |
        | @{msgs} | Create List | ${msg1} | ${msg2} | ${msg3} |
        | Publish Multiple | msgs=${msgs} | hostname=127.0.0.1 |

        """
        logger.info('Publishing to: %s:%s, msgs: %s' %
                    (hostname, port, msgs))
        publish.multiple(msgs, hostname, port, client_id, keepalive,
                        will, auth, tls, protocol)
Esempio n. 33
0
def sendMQTT():
    # Init MQTT
    mqtt_config = configparser.ConfigParser()
    mqtt_config.read("{0}/mqtt.ini".format(workdir))
    mqtt_broker_cfg = mqtt_config["broker"]

    try:
        auth = None
        mqtt_username = mqtt_broker_cfg.get("username")
        mqtt_password = mqtt_broker_cfg.get("password")

        if mqtt_username:
            auth = {"username": mqtt_username, "password": mqtt_password}

        publish.multiple(messages,
                         hostname=mqtt_broker_cfg.get("host"),
                         port=mqtt_broker_cfg.getint("port"),
                         client_id=mqtt_broker_cfg.get("client"),
                         auth=auth)
    except Exception as ex:
        print(datetime.datetime.now(),
              "Error publishing to MQTT: {0}".format(str(ex)))

    with open("{0}/averages.ini".format(workdir), "w") as averages_file:
        averages.write(averages_file)
Esempio n. 34
0
def foo(argument):
    msgs = [{
        'topic': argument,
        'payload': "REST to MQTT"
    }, (argument, "second message", 0, False)]
    publish.multiple(msgs, hostname="10.37.85.223")
    return "GOT: %s" % argument
Esempio n. 35
0
def publish_day_totals():
    """ Publishes day totals to a broker, if set and enabled. """
    json_settings = day_totals.JSONDayTotalsMQTTSettings.get_solo()
    split_topic_settings = day_totals.SplitTopicDayTotalsMQTTSettings.get_solo(
    )

    if not json_settings.enabled and not split_topic_settings.enabled:
        return

    try:
        latest_electricity = ElectricityConsumption.objects.all().order_by(
            '-read_at')[0]
    except IndexError:
        # Don't even bother when no data available.
        return

    day_consumption = dsmr_consumption.services.day_consumption(
        day=timezone.localtime(latest_electricity.read_at).date())

    mqtt_messages = []

    if json_settings.enabled:
        mqtt_messages += day_totals_as_json(day_consumption, json_settings)

    if split_topic_settings.enabled:
        mqtt_messages += day_totals_per_topic(day_consumption,
                                              split_topic_settings)

    broker_kwargs = get_broker_configuration()

    try:
        publish.multiple(msgs=mqtt_messages, **broker_kwargs)
    except ValueError as error:
        logger.error('MQTT publish_day_totals() | {}'.format(error))
	def notif_inbox_manajer(self):
		query = "select username from manajer"
		result = model.get_query(query)
		msgs = []
		for row in result:
			username = row['username']
			msg = {'topic':self.topic_manajer+username, 'payload':"inbox"}
			msgs.append(msg)
		publish.multiple(msgs,hostname="localhost",auth=self.auth,client_id="sipadu_notif_inbox")
Esempio n. 37
0
def publish_packet_raw(message):
    try:
        msgs = [{'topic': "paho/test/iotBUET/bulk_raw/", 'payload': message},
                ("paho/test/multiple", "multiple 2", 0, False)]
        pub.multiple(msgs, hostname="iot.eclipse.org")
        return True

    except gaierror:
        log.error('[MQTT] Publish ERROR.')
        eprint ("[MQTT] Publish ERROR." )
        return False
Esempio n. 38
0
def test_connection():
    try:
        msgs = [{'topic': "paho/test/iotTEST/" },
                ("paho/test/multiple", "multiple 2", 0, False)]
        pub.multiple(msgs, hostname="iot.eclipse.org")
        return True

    except gaierror:
        log.error('[MQTT] Connection Test ERROR.')
        eprint ("[MQTT] Connection Test ERROR." )
        return False
Esempio n. 39
0
 def publish_multiple(self, obj):
     publish.multiple(obj,
                      hostname=self.endpoint,
                      port=self.port,
                      tls={'ca_certs': self.root_ca,
                           'certfile': self.cert,
                           'keyfile': self.key,
                           'tls_version': ssl.PROTOCOL_TLSv1_2
                           }
                      ,
                      protocol=MQTTv311)
Esempio n. 40
0
 def publish(self, topic, obj, qos=0, retain=False):
     msg = {'topic': topic, 'payload': obj, 'qos': qos, 'retain': retain}
     publish.multiple([msg],
                      hostname=self.endpoint,
                      port=self.port,
                      tls={'ca_certs': self.root_ca,
                           'certfile': self.cert,
                           'keyfile': self.key,
                           'tls_version': ssl.PROTOCOL_TLSv1_2
                           }
                      ,
                      protocol=MQTTv311)
Esempio n. 41
0
def publish_temperatures(outside_temp, heating_feed, heating_return, heating_return_target, source_feed, source_return, water_temp, water_target):
  mqtt.multiple(hostname=MQTT_BROKER,
    msgs = [
      ('outside/temperature', outside_temp, 0, True),
      ('house/heating/floor/feed', heating_feed, 0, True),
      ('house/heating/floor/return', heating_return, 0, True),
      ('house/heating/floor/return_target', heating_return_target, 0, True),
      ('house/heating/source/feed', source_feed, 0, True),
      ('house/heating/source/return', source_return, 0, True),
      ('house/heating/water/current', water_temp, 0, True),
      ('house/heating/water/target', water_target, 0, True)
    ]
  )
Esempio n. 42
0
def MQTTcallback(pkt):
    logger.debug("Callback")
    msg.setMsg(pkt)
    now = datetime.datetime.now()

    logger.debug("ID: {0}".format(msg.getID())) 

    if mqtt_enabled:
        d=msg.getDict()
        msgs=list()
        for key in d:
            msgs.append((mqtt_topic+"/"+key,d[key],0,False))
        logger.debug("Publishing packet data to MQTT broker")
        publish.multiple(msgs,hostname=mqtt_host,port=mqtt_port)
    msg.clear()
def main():
    """Main function, parse args and read alarm files, send resulting events to mqtt broker"""
    parser = argparse.ArgumentParser(description="An Asterisk Alarmreciever to MQTT inteface",
                                     epilog="Version 0.1 by Dave Sargeant")

    parser.add_argument("-e", "--eventdir", help="The directory containing event files",
                        type=event_directory)
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="increase output verbosity")
    parser.add_argument("-m", "--mqtt-broker", dest='mqtt_broker', default='localhost',
                        help="Relay events to mqtt server")

    args = parser.parse_args()

    syslog_handler = logging.handlers.SysLogHandler(address='/dev/log')
    _LOG.addHandler(syslog_handler)

    if args.verbose is True:
        _LOG.setLevel(logging.DEBUG)

    _LOG.info("Event dir %s", args.eventdir)
    for root, dummy_dirs, files in os.walk(args.eventdir):
        for alarmrec_file in files:
            if alarmrec_file.startswith("event-") and not alarmrec_file.endswith(".handled"):
                file_and_path = os.path.join(root, alarmrec_file)
                _LOG.info("Handling event file %s", file_and_path)
                eventfile = AlarmEventFile(file_and_path)
                try:
                    os.rename(file_and_path, "{}.handled".format(file_and_path))
                except OSError as os_err:
                    _LOG.error("Unable to rename file :%s", str(os_err))
                    continue

                msgs = []
                for (event_type, description, datatype, zonenum) in eventfile:
                    payload = "{description} {datatype}={data}".format(description=description,
                                                                       datatype=datatype,
                                                                       data=zonenum)
                    topic = "whouse/alexor/{}".format(event_type)

                    msg = {'topic':topic,
                           'payload':payload}
                    _LOG.debug("Adding (topic=%s) : %s to %s", topic, payload, args.mqtt_broker)
                    msgs.append(msg)

                if len(msgs):
                    _LOG.debug("Sending %d message to broker %s", len(msgs), args.mqtt_broker)
                    mqtt.multiple(msgs, hostname=args.mqtt_broker)
Esempio n. 44
0
def publish(msgs,broker="localhost"):
    data = []
    prefix = "/weather/"
    for k in msgs.keys():
        try:
            for k2 in msgs[k]:
                t = prefix + str(k) + '/' + str(k2)
                p = str(msgs[k][k2])
                data.append( (t,p,0,True) )
        except Exception:
            pass
        t = prefix + str(k)
        p = str(msgs[k]['value']) + " " + str(msgs[k]['unit'])
        data.append( (t,p,0,True) )
        
    pub.multiple(data, broker, port=1883, client_id="Weather")
Esempio n. 45
0
	def sendDeviceStatus(self):
		global publish
		deviceInfo = []
		
		deviceInfo.append(self.addDeviceInfo("name", self.device.name))
		deviceInfo.append(self.addDeviceInfo("host", self.device.host))

		if len(str(self.device.app_display_name)):
			deviceInfo.append(self.addDeviceInfo("app",  self.device.app_display_name))
		else:
			deviceInfo.append(self.addDeviceInfo("app", "None"))


		if self.device.media_controller is not None:
			if self.device.media_controller.status is not None:
				deviceInfo.append(self.addDeviceInfo("state", self.device.media_controller.status.player_state))
				
				if self.device.media_controller.status.player_state == pychromecast.controllers.media.MEDIA_PLAYER_STATE_PLAYING:
					deviceInfo.append(self.addDeviceInfo("is_playing", "ON"))
				else:
					deviceInfo.append(self.addDeviceInfo("is_playing", "OFF"))
					
				deviceInfo.append(self.addDeviceInfo("title", 			self.device.media_controller.status.title))
				deviceInfo.append(self.addDeviceInfo("series_title", 		self.device.media_controller.status.series_title))
				deviceInfo.append(self.addDeviceInfo("artist", 			self.device.media_controller.status.artist))
				deviceInfo.append(self.addDeviceInfo("album", 			self.device.media_controller.status.album_name))
				deviceInfo.append(self.addDeviceInfo("mediatype", 		self.device.media_controller.status.metadata_type))
				deviceInfo.append(self.addDeviceInfo("thumbnail", 		self.device.media_controller.thumbnail))
				deviceInfo.append(self.addDeviceInfo("volume", 			str(float(self.device.status.volume_level) * 100)))
				deviceInfo.append(self.addDeviceInfo("current",                 self.device.media_controller.status.current_time))

				duration = self.device.media_controller.status.duration
				if duration is None:
					duration = -1
				deviceInfo.append(self.addDeviceInfo("duration", 		duration))
				
				if self.thumbnail is not self.device.media_controller.thumbnail and self.device.media_controller.thumbnail is not None:
					os.system("wget {1} -O /usr/share/openhab/webapps/images/{0}.png".format(self.device.name, self.device.media_controller.thumbnail))
					#os.system("/usr/bin/convert /usr/share/openhab/webapps/images/{0}.png -resize 128x128 /usr/share/openhab/webapps/images/{0}.png".format(self.device.name))
					self.thumbnail = self.device.media_controller.thumbnail
				
		publish.multiple(deviceInfo)
Esempio n. 46
0
def sendFromCache(brokerRemoteIP, clientID, cachefile):
    """This function send cache file contens to broker"""

    logger.debug('Reading cache file %s', cachefile)

    with open(cachefile + ".csv", "r") as csvfile:
        f = csv.reader(csvfile, delimiter=';')
        count = 0
        try:
            msgs = list()
            for row in f:
                msgs.append((row[0], row[1], 0, False))
                count += 1

            mqtt.multiple(msgs, hostname=brokerRemoteIP, client_id= clientID, will=None, auth=None, tls=None)
            logger.warning("%i lines sent, removing cachefile: %s",
                           count, cachefile)
            os.remove(cachefile + ".csv")

        except Exception, err:
            logger.warning('Error trying to send cache: %s', str(err))
Esempio n. 47
0
    def publish_to_historian(self, to_publish_list):
        _log.debug("publish_to_historian number of items: {}"
                   .format(len(to_publish_list)))
        current_time = self.timestamp()

        if self._last_error:
            # if we failed we need to wait 60 seconds before we go on.
            if self.timestamp() < self._last_error + 60:
                _log.debug('Not allowing send < 60 seconds from failure')
                return

        to_send = []
        for x in to_publish_list:
            topic = x['topic']

            # Construct payload from data in the publish item.
            # Available fields: 'value', 'headers', and 'meta'
            payload = x['value']

            to_send.append({'topic': topic,
                            'payload': payload,
                            'qos': self.mqtt_qos,
                            'retain': self.mqtt_retain})

        try:
            publish.multiple(to_send,
                             hostname=self.mqtt_hostname,
                             port=self.mqtt_port,
                             client_id=self.mqtt_client_id,
                             keepalive=self.mqtt_keepalive,
                             will=self.mqtt_will,
                             auth=self.mqtt_auth,
                             tls=self.mqtt_tls,
                             protocol=self.mqtt_protocol)
            self.report_all_handled()
        except Exception as e:
            _log.warning("Exception ({}) raised by publish: {}".format(
                e.__class__.__name__,
                e.message))
            self._last_error = self.timestamp()
Esempio n. 48
0
 def run(self):
     reline = re.compile("<BR>\s*(\S+=.+?)<BR>")
     refield = re.compile(",\s+")
     last = None
     while True:
         while True:
             now = datetime.datetime.utcnow().second
             if last != now:
                 last = now
                 break
             sleep(0.1)
         try:
             response = requests.get("http://"+self.smappee+"/gateway/apipublic/reportInstantaneousValues")
             report = response.json()["report"]
             payload = "time="+str(datetime.datetime.utcnow()).replace(" ","T")+"Z"
             for line in re.findall(reline, report):
                 for field in re.split(refield, line):
                     payload += ","+field
             msgs = [ { "topic": self.topic, "payload": payload, "qos": self.qos, "retain": self.retain } ]
             publish.multiple(msgs, hostname=self.host, port=self.port, client_id=self.client_id, auth=self.auth)
         except Exception, e:
             logger.warning(e)
             pass
Esempio n. 49
0
def publish_thread():
    log.debug('Start publish_thread()')
    while True:
        try:
            gps_lastpos = cs.CSClient().get(settings.GPS_TOPIC).get('data')
            gps_pos = {'longitude': gps_lastpos.get('longitude'),
                       'latitude': gps_lastpos.get('latitude')}

            # Single Topic Publish example
            # QOS 0: The client will deliver the message once, with no confirmation.
            publish.single(topic=settings.GPS_TOPIC, payload=json.dumps(gps_pos), qos=0,
                           hostname=settings.MQTT_SERVER, port=settings.MQTT_PORT)

            time.sleep(1)

            # Multiple Topics Publish example
            modem_temp = cs.CSClient().get(settings.MODEM_TEMP_TOPIC).get('data', '')
            wan_connection_state = cs.CSClient().get(settings.WAN_CONNECTION_STATE_TOPIC).get('data')

            # Using tuples to define multiple messages,
            # the form must be: ("<topic>", "<payload>", qos, retain)
            # QOS 1: The client will deliver the message at least once, with confirmation required.
            # QOS 2: The client will deliver the message exactly once by using a four step handshake.
            msgs = [(settings.MODEM_TEMP_TOPIC, modem_temp, 1, False),
                    (settings.WAN_CONNECTION_STATE_TOPIC, wan_connection_state, 2, False)]

            publish.multiple(msgs=msgs, hostname=settings.MQTT_SERVER, port=settings.MQTT_PORT)

            time.sleep(1)

            # Publish the package.ini file as an example
            file_name = 'package.ini'
            publish_file(file_name, os.path.join(os.getcwd(), file_name))

            time.sleep(10)
        except Exception as ex:
            log.error('Exception in publish_thread(). ex: {}'.format(ex))
Esempio n. 50
0
def actoboard_data():
    # mandatory form data
    heads = {'device' : request.form['device'],
             'signal' : request.form['signal'],
             'data' : request.form['data'],
             'time' : request.form['time']}
    # slots in form data
    slots = {}
    for item in request.form:
        if item.startswith("slot_"):
            slots[item[5:]] = request.form[item]
    # format a time_iso string
    time_iso = datetime.fromtimestamp(float(heads['time']),
                                      tz=pytz.utc).isoformat()
    # jsons = dict heads + dict slots + time_iso
    jsons = heads.copy()
    jsons['time_iso'] = time_iso
    jsons.update(slots)
    # to MQTT
    start_path = "sigfox/actoboard/modems/%s/" % heads['device']
    msgs = [{'topic': start_path+"signal", 'payload': heads['signal'],
             'retain': True},
            {'topic': start_path+"time", 'payload': heads['time'],
             'retain': True},
            {'topic': start_path+"time_iso", 'payload': time_iso,
             'retain': True},
            {'topic': start_path+"data", 'payload': heads['data'],
             'retain': True},
            {'topic': start_path+"json", 'payload': json.dumps(jsons),
             'retain': True}]
    # add slots to msgs
    for item in slots:
        msgs.append({'topic': start_path+"slots/%s" % item,
                     'payload': slots[item], 'retain': True})
    publish.multiple(msgs, hostname="mosquitto")
    return "ok"
Esempio n. 51
0
def main(argv=None):
    initLogger("Smappee")
    log.info("Initializing Smappee...")
    smappee = SmappeeMQTT()

    cfg = SafeConfigParser(
            {"client_id": "smappee-mqtt-" + str(os.getpid()), "hostname": "localhost", "port": "1883", "auth": "False",
             "retain": "False", "qos": "0"})
    cfg.optionxform = str
    cfg.read(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/smappee-mqtt.conf"))
    genIDX = cfg.get("domoticz", "consumptionIDX")
    solarIDX = cfg.get("domoticz", "solarIDX")
    excessIDX = cfg.get("domoticz", "excessIDX")
    client_id = cfg.get("mqtt", "client_id")
    host = cfg.get("mqtt", "hostname")
    port = eval(cfg.get("mqtt", "port"))
    topic = cfg.get("mqtt", "topic")
    qos = eval(cfg.get("mqtt", "qos"))
    retain = eval(cfg.get("mqtt", "retain"))
    if eval(cfg.get("mqtt", "auth")):
        auth = {"username": cfg.get("mqtt", "user"), "password": cfg.get("mqtt", "password")}
    else:
        auth = None

    log.info("Connecting to MQTT Broker on " + host + " port " + str(port))

    while True:
        try:
            smappee.run()
            gridTopic = topic + "grid"
            solarTopic = topic + "solar"
            excessTopic = topic + "excess"

            try:
                gridmsgs = [{"topic": gridTopic, "payload": """{ "idx" : """ + genIDX + """, "nvalue" : 0, "svalue" : \"""" + str(smappee.grid) + ";0\"}", "qos": qos, "retain": retain}]
                publish.multiple(gridmsgs, hostname=host, port=port, client_id=client_id, auth=auth)
            except:
                log.warning("Unable to publish message, " + gridmsgs)

            try:
                solarmsgs = [{"topic": solarTopic, "payload": """{ "idx" : """ +solarIDX + """, "nvalue" : 0, "svalue" : \"""" + str(smappee.solar) + ";0\"}", "qos": qos, "retain": retain}]
                publish.multiple(solarmsgs, hostname=host, port=port, client_id=client_id, auth=auth)
            except:
                log.warning("Unable to publish message, " + solarmsgs)

            try:
                excessmsgs = [{"topic": excessTopic, "payload": """{ "idx" : """ + excessIDX + """, "nvalue" : 0, "svalue" : \"""" + str(smappee.excess) + ";0\"}", "qos": qos, "retain": retain}]
                publish.multiple(excessmsgs, hostname=host, port=port, client_id=client_id, auth=auth)
            except:
                log.warning("Unable to publish message, " + excessmsgs)
            time.sleep(5)
        except:
            log.error("Error updating and publishing message")
Esempio n. 52
0
import json
import paho.mqtt.publish as publish
from datetime import datetime
import sys

reload(sys)
sys.setdefaultencoding('utf8')



total = 50001

list = []
for i in xrange(0, total):
    dict = {"date":"24/7/2012","lineItem":"11111","quantity":"1","customerNumber":"1","poNumber":"PO1"}
    #dict = {"count": i}
    bytes = bytearray(msgpack.packb(dict))
    list.append({'topic':'/purchase', 'payload': bytes, 'qos':0})


start = datetime.now()

publish.multiple(list, hostname = 'localhost', port = 1883);

end = datetime.now();
delta = end - start
print delta.seconds, delta.microseconds
print  1000000* total/ ((delta.seconds/1000000)+ delta.microseconds)
# dict = {"date":"24/7/2012","lineItem":"11111","quantity":"1","customerNumber":"1","poNumber":"PO1"}
# print msgpack.packb(dict)
Esempio n. 53
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2014 Roger Light <*****@*****.**>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Distribution License v1.0
# which accompanies this distribution.
#
# The Eclipse Distribution License is available at
#   http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
#    Roger Light - initial implementation

# This shows an example of using the publish.multiple helper function.

import context  # Ensures paho is in PYTHONPATH
import paho.mqtt.publish as publish

msgs = [{'topic': "paho/test/multiple", 'payload': "multiple 1"}, ("paho/test/multiple", "multiple 2", 0, False)]
publish.multiple(msgs, hostname="test.mosquitto.org")
Esempio n. 54
0
import paho.mqtt.publish as publish
from datetime import datetime
import json

now = datetime.now()
payload = dict(hours=now.hour, minutes=now.minute, seconds=now.second)

msgs = [
    {'topic':   '/send_command/home/livingroom/set_time',
     'payload': json.dumps(payload)},
]

publish.multiple(msgs, hostname="localhost")
Esempio n. 55
0
def sendData(d):
    """ This function send data recoverd by sensor to broker """

    """
    Check if remote broker is alive
    Check if exists a cache file
    Send cache data to broker then send last data
    If no broker, append data to cache file


    Must remove non required keys before send json:
    required_fields = ['name', 'last_name', 'phone_number', 'email']
    dict2 = {key:value for key, value in dict1.items() if key in required_fields}

        'results': [{'dname': 'temperature',
                  'dvalue': 25.5,
                  'time': '2015-09-09 16:22:28'},
                 {'dname': 'humidity',
                  'dvalue': 50.0,
                  'time': '2015-09-09 16:22:28'}],


    MySQL server and MQTTWARN are waiting this JSON:

    { "org" : "sens.solutions", "place" : "pool", "what" : "sensors", "sensor" : "air", "type" : "humidity", "value" : 48.7, "timestamp" : "2015-08-04 04:59:49" }

    """

    cachefile = os.path.join(d['path'], d['logpath'], (d['name'] + d['cache_suffix']))
    d['topic'] = d['org'] + "/" + d['location'] + "/" + d['type'] + "/" + d['name']
    logger.debug("Client ID: %s opening connection to: %s", d['clientID'], d['brokerRemoteIP'])

    """ TODO: rewrite in more pythonish way:
        try mqtt.connect:
            send = mqtt.publish
        except:
            send = senToCache

        We have to take care of diferents argument. Use someting linke:
        We can use the **kwargs argument to accept an arbitrary number of named options:
            def render(context, **kwargs):
                ... template = kwargs['template'] if 'template' in kwargs else 'my_default_template'
                ... # do something with your template
                ... print template
                ...
            render() 'my_default_template'
            render(template='custom_template') 'custom_template'
        - See more at: http://www.abidibo.net/blog/2015/04/09/pythons-excess-arguments/#sthash.PbG99nyx.dpuf
        """
    """
    try:
        mqttc = mqtt.Client(d['clientID'])
        mqttc.connect(d['brokerRemoteIP'], 1883)
        conn_ok = True
    except KeyboardInterrupt:
        pass
    except Exception, err:
        conn_ok = False
        logger.warning('Error: %s, %s', str(err), d['brokerRemoteIP'])
    """

    conn_ok = True
        #
    #print "Cachefile: " + cachefile

    if os.path.isfile(cachefile + ".csv") and conn_ok:
        logger.warning("There's a cache file loading it")
        sendFromCache(d['brokerRemoteIP'], d['clientID'], cachefile)
    # mqttc.connect(d['brokerRemoteIP'], 1883)

    l = list()
    for result in d['results']:
        required_fields = ['org', 'place', 'type', 'name']
        result2 = {key:value for key, value in d.items() if key in required_fields}
        result.update(result2)
        d['message'] = json.dumps(result, sort_keys=True)
        d['newtopic'] = d['topic'] + "/" + result['dname']
        l.append((d['newtopic'],d['message'],0, False))
        
    if conn_ok:
        mqtt.multiple(l, hostname=d['brokerRemoteIP'])
        # rewrite this part using code from experiments/mypaho.py
        #mqttc.publish(d['topic'] + "/" + result['dname'], d['message'])
        #logger.debug('Topic: %s/%s : %s | Client ID: %s', d['topic'], result['dname'], d['message'], d['clientID'])
    else:
        sendToCache(cachefile, d['newtopic'], d['message'])
Esempio n. 56
0
 def publish_multiple(self, topic, msg):
     publish.multiple(topic, msg, hostname=self.hostname,
                      port=self.port, client_id=self.client_id,
                      keepalive=self.keepalive, will=self.will,
                      auth=self.auth, tls=self.tls, qos=self.qos)
Esempio n. 57
0
 def run(self):
     publish.multiple(self.msgs, self.hostname, self.port)
# The Eclipse Distribution License is available at 
#   http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
#    Roger Light - initial implementation
  
# This shows an example of using the publish.single helper function.

#http://nullege.com/codes/show/src%40p%40a%40paho-mqtt-0.9%40examples%40pub-single.py/32/paho.mqtt.publish.single/python
  
import sys
import paho.mqtt.publish as publish
### Single payload.
#without payload.  
publish.single("/fromlaptop", payload=None, qos=0, retain=False, hostname="m12.cloudmqtt.com",
    port=19757, client_id="", keepalive=60, will=None, auth={'username':"******", 'password':"******"}, tls=None)
#with payload
publish.single("/fromlaptop", payload="shashilaptop", qos=0, retain=False, hostname="m12.cloudmqtt.com",
    port=19757, client_id="", keepalive=60, will=None, auth={'username':"******", 'password':"******"}, tls=None)


# With multiple topics in a publish

# first set the list with the different topics and 

msgs = [{'topic':"/fromLTMultiple", 'payload':"multiple 1"},
    ("/fromLTDifferenttopic", "multiple 2", 0, False)]

publish.multiple(msgs, hostname="m12.cloudmqtt.com", port=19757, client_id="", keepalive=60,
    will=None, auth={'username':"******", 'password':"******"}, tls=None)
	msg["date"] = timestamp[0:10]
	msg["time"] = timestamp[11:19]
	msg["app"] = "ProbeCube_COPY"
	msg["device_id"] = "PC_" + str(items["Channel_id"])
	msg["SiteName"] = items["SiteName"]
	msg["gps_lat"] = str(items["LatLng"]["lat"])
	msg["gps_lon"] = str(items["LatLng"]["lng"])
	msg["PM2_5"] = items["RawData"]["field5"]
	msg["Temperature"] = items["RawData"]["field1"]
	msg["Humidity"] = items["RawData"]["field2"]
	msg["s_0"] = str(items["RawData"]["entry_id"])
	try:
		s = "|ver_format=3|fmt_opt=1|app=ProbeCube_COPY"

		for key in msg.iterkeys():
			s = s + "|" + key + "=" + msg[key].encode('utf-8')

		#time.sleep(0.2)
		#mqtt_client.publish(MQTT_TOPIC, s)
        	msg2 = {}
        	msg2["topic"] = MQTT_TOPIC
        	msg2["payload"] = s
        	msg2["qos"] = 1
        	msgs.append(msg2)
	except:
		print "Unexpected error:", sys.exc_info()[0]


publish.multiple(msgs, MQTT_SERVER)
mqtt_client.disconnect()
Esempio n. 60
0
      # Check if changed and above delay for the sensor
      if (changed and (time.time()-last_change[gpio] > delay) ):
        logger.info("Sending %s %s." % (gpio, input))
        state[gpio] = input
        last_change[gpio] = time.time()
        append_message(messages, hostname + '/' + type + str(gpio), input, changed)

      # Check if above max_idle_time
      if (time.time()-last_change[gpio] > max_idle_time):
        logger.info("Max_idle_time hit for %s: %s" % (gpio, input))
        state[gpio] = input
        last_change[gpio] = time.time()
        append_message(messages, hostname + '/' + type + str(gpio), input, changed)
        continue
      #else:
      #  logger.debug("Not time to send %s yet. Delay: %s. Max idle: %s. Since last update of last_change[%s]: %.0f." \
      #      % (input, delay, max_idle_time, gpio, (time.time()-last_change[gpio])))
  
  # Send all
  if changed:
    logger.debug(messages)

    try:
      publish.multiple(messages, hostname=mosquittoserver, port=1883, client_id="", keepalive=60)
      changed=False
    except Exception as err:
      logger.error("*** Error sending message *** %s." % err)

  time.sleep(activity_delay)