示例#1
0
    def __init__(self, parent=None):
        global connected

        Ui_Dialog.__init__(self) # initialise le Qwidget principal
        QTabWidget.__init__(self)
        self.setupUi(parent) # Obligatoire
        #self.clientmqtt = mqtt.Client()
        self.clientmqtt = mqtt.Mosquitto()  # Herite de Client
        self.clientmqtt.username_pw_set(MQTT_USER,MQTT_PASSW)
        self.clientmqtt.on_connect = on_connect
        self.clientmqtt.on_message = on_message
        try:
            self.clientmqtt.connect(MQTT_SERVER, MQTT_PORT, 120) # Fonction bloquante
            self.clientmqtt.subscribe('/regchauf/mesur', 0)
            self.clientmqtt.subscribe('/regsol/mesur', 0)
        except:
            print('Pas de reseau')
            self.label_29.setText("Pas de connexion réseau")

        self.lineEdit.clearFocus()

        self.pushButton.setStyleSheet(_fromUtf8("background-color: rgb(255, 0, 0);"))
        self.counter = 0
        self.timer = QTimer()
        self.timer.start(1000)
        self.connect(self.timer, SIGNAL("timeout()"), self.timerEvent)
        self.connect(self.pushButton, SIGNAL("clicked()"), self.pushbuttonclicked)
        self.connect(self.lineEdit, SIGNAL("returnPressed()"), self.setpointChanged)
        self.connect(self.pushButton_quit, SIGNAL("clicked()"), self.closeAppli)
        self.setTabEnabled(0, True)
        self.flagtimer = False
        self.once_time = False
        self.van_tm1 = 0
        self.label_29.setStyleSheet(_fromUtf8("color: rgb(255, 0, 180);"))
示例#2
0
def mqttConnect():
    global args
    global mqttc
    try:
        mqttc = mosquitto.Mosquitto("adsbclient-%d" %
                                    (random.randint(0, 65535)))
        mqttc.on_message = mqttOnMessage
        mqttc.on_connect = mqttOnConnect
        mqttc.on_disconnect = mqttOnDisconnect
        mqttc.on_publish = mqttOnPublish
        mqttc.on_subscribe = mqttOnSubscribe

        if args.mqtt_user and args.mqtt_password:
            mqttc.username_pw_set(args.mqtt_user, password=args.mqtt_password)

        mqttc.connect(args.mqtt_host, args.mqtt_port, 60)

        thread = threading.Thread(target=mqttThread)
        thread.setDaemon(True)
        thread.start()
        return True
    except socket.error as e:
        return False

    log.info("MQTT wierdness")
示例#3
0
 def test_sucessful_publish_when_connection_active(self):
     self.client._mqtt_client = mosquitto.Mosquitto('mqttc-test-000')
     self.client._mqtt_client.publish = Mock(return_value=None)
     self.client._mqtt_client.loop = Mock(
         return_value=mosquitto.MQTT_ERR_SUCCESS)
     self.client.publish('/messages', 'hi')
     self.client._mqtt_client.publish.assert_called_once_with(
         'mqttc-test-000/messages', 'hi', 1, False)
示例#4
0
文件: Monitor.py 项目: charugaa/Tools
def main():
    client = mosquitto.Mosquitto()
    print " ## Connecting to %s" % MQTT_HOST
    client.connect(MQTT_HOST)
    client.on_message = on_message
    for q in [TOPIC_RX, TOPIC_TX, TOPIC_APP]:
        print " ## Subscribing to %s" % q
        client.subscribe(q)
    client.loop_forever()
示例#5
0
文件: nav_mqtt.py 项目: zoizer/moped
def mqtt_init():
    url_str = "mqtt://test.mosquitto.org:1883"
    url_str = "mqtt://iot.eclipse.org:1883"
    url = urllib.parse.urlparse(url_str)
    g.mqttc = mosquitto.Mosquitto()
    g.mqttc.on_message = on_message
    g.mqttc.connect(url.hostname, url.port)
    # will match /sics/moped/position/car2, for example
    g.mqttc.subscribe("/sics/moped/+/+", 0)
    g.mqttc.subscribe("/sics/moped/value", 0)
示例#6
0
def main():
    logging.info("Starting %s" % client_id)
    logging.info("INFO MODE")
    logging.debug("DEBUG MODE")

    map = {}
    if len(sys.argv) > 1:
        map_file = sys.argv[1]
    else:
        map_file = os.path.dirname(os.path.realpath(__file__))+'/map'

    f = open(map_file)
    for line in f.readlines():
        line = line.rstrip()
        if len(line) == 0 or line[0] == '#':
            continue
        remap = None
        try:
            type, topic, remap = line.split()
        except ValueError:
            type, topic = line.split()

        map[topic] = (type, remap)

    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    except:
        sys.stderr.write("Can't create UDP socket\n")
        sys.exit(1)

    userdata = {
        'sock'      : sock,
        'map'       : map,
    }
    global mqttc
    try:
        mqttc = paho.Client(client_id, clean_session=True, userdata=userdata)
    except AttributeError:
        mqttc = paho.Mosquitto(client_id, clean_session=True, userdata=userdata)
    mqttc.on_message = on_message
    mqttc.on_connect = on_connect
    mqttc.on_disconnect = on_disconnect
    mqttc.on_subscribe = on_subscribe

    mqttc.will_set("clients/" + client_id, payload="Adios!", qos=0, retain=False)

    mqttc.connect(MQTT_HOST, MQTT_PORT, 60)

    signal.signal(signal.SIGTERM, cleanup)
    signal.signal(signal.SIGINT, cleanup)

    mqttc.loop_forever()
示例#7
0
    def mqtt_send_data(self,
                       timestamp,
                       prepared_data,
                       ignore_last_update=False):
        import paho.mqtt.client as mosquitto
        import time
        import json

        topic = prepared_data['topic']
        hostname = prepared_data['hostname']
        port = prepared_data['port']
        client_id = prepared_data['client_id']
        retain = prepared_data['retain'] == 'True'
        auth = prepared_data['auth'] == 'True'
        # clean up the object
        del prepared_data['topic']
        del prepared_data['hostname']
        del prepared_data['port']
        del prepared_data['client_id']
        del prepared_data['retain']
        del prepared_data['auth']

        mosquitto_client = mosquitto.Mosquitto(client_id)
        if auth:
            self.logger.debug("Username and password configured")
            if (self.password == "unknown"):
                mosquitto_client.username_pw_set(self.user)
            else:
                mosquitto_client.username_pw_set(self.user, self.password)
        else:
            self.logger.debug("Username and password unconfigured, ignoring")
        self.logger.debug(
            "timestamp: %s. publishing on topic [%s] to hostname [%s] and " +
            "port [%s] with a client_id [%s] and retain is %s",
            timestamp.isoformat(' '), topic, hostname, port, client_id, retain)

        mosquitto_client.connect(hostname, int(port))
        mosquitto_client.publish(topic,
                                 json.dumps(prepared_data),
                                 retain=retain)

        ##        commented out as sending the data as a json object (above)
        ##        for item in prepared_data:
        ##            if prepared_data[item] == '':
        ##                prepared_data[item] = 'None'
        ##            mosquitto_client.publish(
        ##                topic + "/" + item + "/" + str(timestamp), prepared_data[item])
        ##            time.sleep(0.200)

        self.logger.debug("published data: %s", prepared_data)
        mosquitto_client.disconnect()
        return True
示例#8
0
    def connect(self):
        self.mqttc = mosquitto.Mosquitto(self.name)
        self.mqttc.on_message = self.on_message
        self.mqttc.on_connect = self.on_connect
        self.mqttc.on_disconnect = self.on_disconnect
        self.mqttc.on_publish = self.on_publish
        self.mqttc.on_subscribe = self.on_subscribe

        #Set the username and password if any
        if self.user != None:
            self.mqttc.username_pw_set(self.user, self.password)

        return self._connect()
示例#9
0
文件: nav_mqtt.py 项目: zoizer/moped
def handle_mqtt():
    while True:
        try:
            mqtt_init()

            i = 0
            rc = 0
            while rc == 0:
                rc = g.mqttc.loop(5.0)
                i += 1

            print("mqttc.loop returned %d" % rc)
            if rc == 7 or rc == 1:
                g.mqttc = mosquitto.Mosquitto()
                mqtt_init()
        except Exception as e:
            time.sleep(5000)
示例#10
0
def mqttConnect():
    global mqttc
    global args
    try:
        mqttc = mosquitto.Mosquitto("proxclient-%d" %
                                    (random.randint(0, 65535)))
        mqttc.on_message = mqttOnMessage
        mqttc.on_connect = mqttOnConnect
        mqttc.on_disconnect = mqttOnDisconnect
        mqttc.on_publish = mqttOnPublish
        mqttc.on_subscribe = mqttOnSubscribe
        #mqttc.on_log = mqttOnLog # Uncomment to enable debug messages
        mqttc.connect(args.mqtt_host, args.mqtt_port, 60)

        thread = Thread(target=mqttThread)
        thread.start()
        return True
    except socket.error, e:
        return False
示例#11
0
def mqttConnect():
    global mqttc
    global args
    try:
        # If you want to use a specific client id, use
        # mqttc = mosquitto.Mosquitto("client-id")
        # but note that the client id must be unique on the broker. Leaving the client
        # id parameter empty will generate a random id for you.
        mqttc = mosquitto.Mosquitto("airlinecolor-%d" %
                                    (random.randint(0, 65535)))
        mqttc.on_message = mqttOnMessage
        mqttc.on_connect = mqttOnConnect
        mqttc.on_disconnect = mqttOnDisconnect
        mqttc.on_publish = mqttOnPublish
        mqttc.on_subscribe = mqttOnSubscribe

        #mqttc.on_log = mqttOnLog # Uncomment to enable debug messages
        mqttc.connect(args.mqtt_host, args.mqtt_port, 60)
        if 1:
            log.info("MQTT thread started")
            try:
                mqttc.loop_start()
                while True:
                    time.sleep(60)
                log.info("MQTT thread exiting")
            except Exception as e:
                log.error("MQTT thread got exception: %s" % (e))
                print(traceback.format_exc())
        #        gQuitting = True
        #        log.info("MQTT disconnect")
        #        mqttc.disconnect();
            log.info("MQTT thread exited")
        else:
            thread = Thread(target=mqttThread)
            thread.daemon = True
            thread.start()
        return True
    except socket.error as e:
        log.error("Failed to connect MQTT broker at %s:%d" %
                  (args.mqtt_host, args.mqtt_port))
        return False

    log.info("MQTT wierdness")
示例#12
0
    def mqtt_send_data(self,
                       timestamp,
                       prepared_data,
                       ignore_last_update=False):
        import paho.mqtt.client as mosquitto
        import time
        import json

        topic = prepared_data['topic']
        hostname = prepared_data['hostname']
        port = prepared_data['port']
        client_id = prepared_data['client_id']

        # clean up the object
        del prepared_data['topic']
        del prepared_data['hostname']
        del prepared_data['port']
        del prepared_data['client_id']

        self.logger.info("timestamp: " + str(timestamp) +
                         ". publishing on topic [" + topic +
                         "] to hostname [" + hostname + "] and port [" + port +
                         "] with a client_id [" + client_id + "]")

        mosquittoClient = mosquitto.Mosquitto(client_id)
        mosquittoClient.connect(hostname, port)

        mosquittoClient.publish(topic, json.dumps(prepared_data))
        """ commented out as sending the data as a json object (above)
        for item in prepared_data:
            if prepared_data[item] =='':
                prepared_data[item] = 'None'
            mosquittoClient.publish(topic + "/" + item + "/" + str(timestamp),prepared_data[item])
            time.sleep(0.200)
        """

        self.logger.info("published data: %s", prepared_data)
        mosquittoClient.disconnect()
        return True
示例#13
0
def run(args):
    """
    Initiates the MQTT connection, and starts the main loop
    Is called by either the daemon.start() method, or the start function
    if the no-daemon option is specified.
    """
    while (True):
        try:
            logger.debug("Entering Loop")
            client = mqtt.Mosquitto(
                get_config_item("mqtt", "client_id", "MQTT2RRD Client"))
            client.on_message = on_message
            client.on_connect = on_connect

            if get_config_item("mqtt", "username", None):
                client.username_pw_set(
                    get_config_item("mqtt", "username", ""),
                    get_config_item("mqtt", "password", ""),
                )
            logger.debug("Attempting to connect to server: %s:%s" % (
                get_config_item("mqtt", "hostname", "localhost"),
                get_config_item("mqtt", "port", 1833),
            ))
            client.connect(
                get_config_item("mqtt", "hostname", "localhost"),
                port=int(get_config_item("mqtt", "port", 1883)),
                keepalive=int(get_config_item("mqtt", "keepalive", 60)),
            )
            logger.info("Connected: %s:%s" % (
                get_config_item("mqtt", "hostname", "localhost"),
                get_config_item("mqtt", "port", 1833),
            ))
            client.loop_forever()
        except Exception as e:
            logging.critical("FAIL: %s" % str(e))
            time.sleep(30)  # 30 second wait
示例#14
0
# OnLog Callback
###############################################################################
def on_log(mosq, obj, level, string):
    print_message(string)


# Primary logic for the component starts here
###############################################################################

# Primary logic for the component starts here
###############################################################################
try:
    while True:
        try:
            # create a new MQTT Client Object
            mqttc = mosquitto.Mosquitto()

            # Set event callbacks
            mqttc.on_connect = on_connect

            # Connect to MQTT using the username/password set above
            mqttc.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
            mqttc.connect(MQTT_SERVER, MQTT_SERVER_PORT)

            print_message("Connected to MQTT Server successfully")
        except Exception as ex:
            print_message("Error connecting to MQTT.")
            print_message(str(ex))
            sys.exit(1)

        try:
示例#15
0
def main():
    # Find the temperature in futureHourOffset hours
    futureHourOffset = 8

    parser = OptionParser()
    parser.add_option('-m',
                      '--mqtt-host',
                      dest='mqtt_host',
                      help="MQTT broker hostname",
                      default='127.0.0.1')
    parser.add_option('-p',
                      '--mqtt-port',
                      dest='mqtt_port',
                      type="int",
                      help="MQTT broker port number",
                      default=1883)
    #    parser.add_option('-u', '--mqtt-user', dest='mqtt_user', help="MQTT broker connect user", default='')
    #    parser.add_option('-a', '--mqtt-password', dest='mqtt_password', help="MQTT broker connect password", default='')

    parser.add_option('-v',
                      '--verbose',
                      dest='verbose',
                      action="store_true",
                      help="Verbose output")
    parser.add_option('-T',
                      '--tz',
                      dest='timezone',
                      help="Your current timezone",
                      default="Europe/Copenhagen")
    parser.add_option('-l',
                      '--lat',
                      dest='lat',
                      type="float",
                      help="Your latitude",
                      default=0)
    parser.add_option('-L',
                      '--lon',
                      dest='lon',
                      type="float",
                      help="Your longitude",
                      default=0)
    parser.add_option('-t',
                      '--topic',
                      dest='topic',
                      help="The topic to publish the temperature to",
                      default="home/temperature/outside%dhrs" %
                      (futureHourOffset))

    (options, args) = parser.parse_args()

    os.environ["TZ"] = options.timezone
    time.tzset()

    mqttc = mosquitto.Mosquitto("weather-%d" % (random.randint(0, 65535)))
    mqttc.on_message = mqttOnMessage
    mqttc.on_connect = mqttOnConnect
    mqttc.on_disconnect = mqttOnDisconnect
    mqttc.on_publish = mqttOnPublish
    mqttc.on_subscribe = mqttOnSubscribe

    if options.lat == 0 and options.lon == 0:
        sys.stderr.write(
            "I have no ide of where you are, use -l LAT -L LON to override (only works for Sweden though).\n"
        )
        sys.exit(0)

    try:
        mqttc.connect(options.mqtt_host, options.mqtt_port, 60)
    except socket.error as e:
        sys.stderr.write(
            "Could not connect to MQTT broker at %s, use -m HOST to override.\n"
            % options.mqtt_host)
        sys.exit(0)

    try:
        mqttc.loop_start()
        while True:
            # Get current time with time zone
            now = datetime.datetime.now(tz.tzlocal())
            if 0:
                # Testing: simulate time in the future
                now += datetime.timedelta(hours=14)
            future = now + datetime.timedelta(hours=futureHourOffset)
            if now.hour >= 0 and now.hour < 6:
                tod = "night"
            elif now.hour >= 6 and now.hour < 12:
                tod = "morning"
            elif now.hour >= 12 and now.hour < 18:
                tod = "day"
            elif now.hour >= 18 and now.hour <= 23:
                tod = "evening"

            series = getSMHIWeather(options.lat, options.lon)
            if not series:
                sys.stderr.write("Weather loading failed\n")
                time.sleep(5 * 60)
            else:
                for w in series:
                    utc = parse(w["validTime"])
                    utc = utc.replace(tzinfo=tz.tzutc())
                    # Convert time zone
                    local = utc.astimezone(tz.tzlocal())
                    if local < future and local + datetime.timedelta(
                            hours=1) >= future:
                        if not w or not "parameters" in w:
                            print "[%s] Error in response : %s" % (now, w)
                        else:
                            for p in w["parameters"]:
                                if p["name"] == "t":
                                    temp = float(p["values"][0])
                                    if temp > -5 and temp < 5:
                                        temp = "%.1f" % temp
                                    else:
                                        temp = "%d" % temp

                                    print "[%s] It's %s time, in %d hours the temperature will be %s degrees celcius" % (
                                        now, tod, futureHourOffset, temp)

                                    mqttc.publish(options.topic,
                                                  temp,
                                                  retain=True)
                                    mqttc.publish("home/temperature/forecast",
                                                  temp,
                                                  retain=True)  # Temporary

                time.sleep(30 * 60)
    except Exception as e:
        sys.stderr.write("Got exception: %s" % (e))
        print traceback.format_exc()
示例#16
0
 def mqtt_client(self):
     if self._mqtt_client is None:
         self._mqtt_client = mosquitto.Mosquitto(self.client_id)
     return self._mqtt_client
示例#17
0
        if ((mov_tot - initial_mov) > smart_alarm_threshold):
            global alarm_clock_lock
            #LOCK
            if alarm_clock_lock == 0:
                alarm_clock_lock = 1
                print "ALARM FROM SMART CLOCK"
                sound_clock()
                #UNLOCK
                alarm_clock_lock = 0

        time.sleep(5)


if __name__ == '__main__':

    client = mosquitto.Mosquitto("Raspberry")
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(broker_ip, port=1883, keepalive=60, bind_address="")
    client.loop_start()

    while (True):

        req = urllib2.Request(url_status)
        resp = urllib2.urlopen(req)
        dweet = resp.read()
        dweet2 = json.loads(dweet)
        stat = dweet2["with"][0]["content"]["status"]

        if (stat == 1) & (status == 0):
示例#18
0
    print("mid: " + str(mid))


def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))


def on_log(mosq, obj, level, string):
    print(string)


# If you want to use a specific client id, use
# mqttc = mosquitto.Mosquitto("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = mosquitto.Mosquitto("motor")
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
mqttc.connect("192.168.0.100", 1883, 60)
mqttc.publish("speak", "motor ready")

while True:
    mqttc.loop()

    #pelan-pelan makin pelan
    if PWML > 0:
        PWML = PWML - 2
示例#19
0
def init():
    if mqtt_mosquitto_exists:
        L.l.info("INIT, Using mosquitto as mqtt client")
    elif mqtt_paho_exists:
        L.l.info("INIT, Using paho as mqtt client")
    else:
        L.l.critical("No mqtt client enabled via import")
        raise Exception("No mqtt client enabled via import")

    # not a good ideea to set a timeout as it will crash pigpio_gpio callback
    # socket.setdefaulttimeout(10)
    try:
        global client_connecting
        if client_connecting:
            L.l.warning(
                'Mqtt client already in connection process, skipping attempt to connect until done'
            )
            return
        host_list = [
            #[model_helper.get_param(Constant.P_MQTT_HOST_3), int(model_helper.get_param(Constant.P_MQTT_PORT_3))],
            [
                model_helper.get_param(Constant.P_MQTT_HOST_1),
                int(model_helper.get_param(Constant.P_MQTT_PORT_1))
            ],
            #[model_helper.get_param(Constant.P_MQTT_HOST_2), int(model_helper.get_param(Constant.P_MQTT_PORT_2))]
            #[model_helper.get_param(constant.P_MQTT_HOST_3), int(model_helper.get_param(constant.P_MQTT_PORT_3))]
        ]
        P.topic = str(model_helper.get_param(Constant.P_MQTT_TOPIC))
        P.topic_main = str(model_helper.get_param(Constant.P_MQTT_TOPIC_MAIN))
        if mqtt_paho_exists:
            P.mqtt_client = mqtt.Client()
        elif mqtt_mosquitto_exists:
            P.mqtt_client = mqtt.Mosquitto()

        global client_connected
        global initialised
        for host_port in host_list:
            client_connecting = True
            host = host_port[0]
            port = host_port[1]
            L.l.info(
                'MQTT publisher module initialising, host={} port={}'.format(
                    host, port))
            client_connected = False
            retry_count = 0
            while (not client_connected) and (
                    retry_count < Constant.ERROR_CONNECT_MAX_RETRY_COUNT):
                try:
                    if mqtt_mosquitto_exists:
                        P.mqtt_client.on_connect = on_connect_mosquitto
                    if mqtt_paho_exists:
                        P.mqtt_client.on_connect = on_connect_paho
                    P.mqtt_client.on_subscribe = on_subscribe
                    P.mqtt_client.on_unsubscribe = on_unsubscribe
                    # mqtt_client.username_pw_set('user', 'pass')
                    P.mqtt_client.loop_start()
                    P.mqtt_client.connect(host=host, port=port, keepalive=60)
                    seconds_lapsed = 0
                    while not client_connected and seconds_lapsed < 10:
                        time.sleep(1)
                        seconds_lapsed += 1
                    if client_connected:
                        # mqtt_client.on_message = receiver.on_message
                        P.mqtt_client.message_callback_add(
                            P.topic_main, receiver.on_message)
                        P.mqtt_client.on_disconnect = on_disconnect
                        thread_pool.add_interval_callable(
                            receiver.thread_run, run_interval_second=10)
                        # mqtt_client.loop_start()
                        initialised = True
                        client_connecting = False
                    else:
                        L.l.warning('Timeout connecting to mqtt')
                        retry_count += 1
                except socket.error as ex:
                    L.l.error(
                        'mqtt client not connected, err {}, pause and retry {}'
                        .format(ex, retry_count))
                    retry_count += 1
                    time.sleep(Constant.ERROR_CONNECT_PAUSE_SECOND)
                finally:
                    client_connecting = False
                    global last_connect_attempt
                    last_connect_attempt = utils.get_base_location_now_date()
            if client_connected:
                break
            else:
                L.l.warning('Unable to connect to mqtt server {}:{}'.format(
                    host, port))
        if not client_connected:
            L.l.critical(
                'MQTT connection not available, all connect attempts failed')
    except Exception as ex:
        L.l.error('Exception on mqtt init, err={}'.format(ex))
示例#20
0
 def setUp(self):
     self.client = TestClient(name='test-000')
     self.mqttc = mosquitto.Mosquitto('mqttc-test-000')
     self.default_broker = TestClient.MQTTHOST
     self.default_port = TestClient.MQTTPORT
     self.default_timeout = TestClient.TIMEOUT
示例#21
0
        #encoded ='ert'
        # for x in encoded:

        return encoded.decode('ascii')


def on_publish(mosq, userdata, mid):
    print('Publish')
# Disconnect after our message has been sent.
#   mosq.disconnect()


# Specifying a client id here could lead to collisions if you have multiple
# clients sending. Either generate a random id, or use:
#client = mosquitto.Mosquitto()
client = mqtt.Mosquitto("image-send")
client.on_connect = on_connect
client.on_publish = on_publish
client.connect("192.168.2.50", 1883, 60)

#f = open("Tulips.jpg")
#imagestring = f.read()
#byteArray = bytes(imagestring)
print(convertImageToBase64())
publishEncodedImage(convertImageToBase64())
client.publish("photo", convertImageToBase64(), 0)
# If the image is large, just calling publish() won't guarantee that all
# of the message is sent. You should call one of the mosquitto.loop*()
# functions to ensure that happens. loop_forever() does this for you in a
# blocking call. It will automatically reconnect if disconnected by accident
# and will return after we call disconnect() above.
示例#22
0
import time
import paho.mqtt.client as mqtt


# message callback, write image to file
def on_message(mosq, obj, msg):
    print("on_message got called")
    with open('/bem/out.jpg', 'wb') as fd:
        fd.write(msg.payload)


# set up MQTT client
print "getphoto.py running at ", time.asctime(time.localtime(time.time()))
# get server ip:
with open("credentials.txt", "r") as f:
    serveripcred = f.readline().rstrip()

client = mqtt.Mosquitto("image-rec")
client.connect(
    serveripcred)  # paste in the IP of the MQTT server (this device)
client.subscribe("photo", 0)
client.on_message = on_message

client.loop_forever()
print("getphoto.py code should never get here")

#while True:
#	client.loop(15)
#	time.sleep(2)
示例#23
0

def on_subscribe(mosq, obj, mid, granted_qos):
    print('Subscribed: {}, QoS: {}'.format(str(mid), str(granted_qos)))


def on_log(mosq, obj, level, string):
    print(string)


# username = '******'
# password = '******'
host_url = 'your cloud broker url'
host_port = 'your cloud broker port'  # do not type string, but change to integer

mqttc = mqtt.Mosquitto()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe

# Uncomment to enable debug messages
#mqttc.on_log = on_log

# Parse CLOUDMQTT_URL (or fallback to localhost)
url_str = os.environ.get('CLOUDMQTT_URL', host_url)
url = urlparse(url_str)

# Connect
# username = '******'
# password = '******'
示例#24
0
#!/usr/bin/env python

import paho.mqtt.client as paho
import random
import time, json

mqttc = paho.Mosquitto()
mqttc.username_pw_set('username', 'password')
mqttc.connect("mqtt.com", 1883)

mqttc.loop_start()

while True:
    try:
        value = "%.1f" % random.uniform(10, 50)
        lat = "%.1f" % random.uniform(10, 50)
        lon = "%.1f" % random.uniform(10, 50)
        elev = "%.1f" % random.uniform(10, 50)
        #temperature = random.randint(0,100)    #random no generator
        ds = ['temp', 'humidity'
              ]  #, 'battery', 'pressure', 'heartbeats', 'humid', 'test1']
        ds1 = ['temp', 'humidity']
        ds_name = random.choice(ds)
        ds_name1 = random.choice(ds1)
        topic = 'telemetry/8daa3270000b49039975b2684408982e/' + ds_name
        topic2 = 'telemetry/8daa3270000b49039975b2684408982e/' + ds_name1
        topic3 = 'telemetry/5acbe5a0b5c5460d8d6de4d3d4722a8f/battery'
        topic4 = 'telemetry/d13bf91190154eb392b8fb68a24a457f/' + ds_name
        #topic = 'telemetry/43054a2418ac421790ae425d2b84aee5/' + ds_name
        payload = json.dumps({
            "context": {
示例#25
0
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)

GPIO.setup(ACTUATOR,GPIO.OUT)
GPIO.output(ACTUATOR, False)

#broker configurations
IP = '192.168.0.103'
PORT = 1884
TOPIC_ACT = "impress/demo"
TOPIC_SUB = "impress/action"
CLIENT_NAME = 'RASPBERRY'

 # Connect to MQTT broker.
client = client.Mosquitto(CLIENT_NAME)
client.connect(IP,PORT,60)


class Th(Thread):

        def __init__ (self, num):
                Thread.__init__(self)
                self.num = num
                def on_connect(client, data, rc):
                    client.subscribe(TOPIC_SUB)
                   print("Connection returned result: " + str(rc))
                def on_message(client, userdata, msg):
                    message = str(msg.payload)
                    arrMessage = message.split(";")
                    print(arrMessage[0]);
示例#26
0
    consumer_sret='N7SWj2hiVLMRLKs0NIw9JxDPlvJ05TzJ5CndtVofyCW908Sl3a',
    access_token_key='2806636166-2NdgLd2is06uxxaCweuSgPd0Vnn9PZnwJ383kI5',
    access_secret='mAVkd1swPcXwLleUOaWIBWN38TYwzngjwcm9zZWx4488w')


def onMessage(mosq, obj, msg):
    if msg.topic == "PowerStrip/statusreport":
        print msg.payload
        api.PostUpdate(msg.payload)


def onPublish(mosq, obj, mid):
    pass


cli = mq.Mosquitto('TweetCenter')
cli.on_message = onMessage
cli.on_publish = onPublish

cli.connect("10.0.0.20", 1883, 15)

cli.subscribe("PowerStrip/statusreport", 0)


class checkTweet(threading.Thread):
    def __init__(self):
        # Tkinter canvas
        threading.Thread.__init__(self)
        self.start()

    def callback(self):