Ejemplo n.º 1
0
def main():
    args = get_arguments()
    server = args.server
    port = int(args.port)
    topic = args.topic

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

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

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

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

    for msg in msgs:
        client.publish(service_info['protocol']['publish']['default_topic'],
                       json.dumps(msg))
        time.sleep(interval_sec)
Ejemplo n.º 3
0
            b_state.tweeting = True
            tt = threading.Thread(target=tweet, args=(time, button_size,))
            tt.start()
    else:
        print("chatter!")

def on_connect(client, userdata, rc):
    print("Connected MQTT with result code "+str(rc))
    b.isr(mraa.EDGE_FALLING, on_click, on_click)

def upload_image(filename):
    t_up = Twitter(domain='upload.twitter.com', auth=auth)
    with open(filename, "rb") as imagefile:
        imagedata = imagefile.read()
    m_id = t_up.media.upload(media=imagedata)["media_id_string"]
    print m_id
    return m_id

if __name__ == '__main__':
    # Button
    b = mraa.Gpio(14)
    b.dir(mraa.DIR_IN)
    b.mode(mraa.MODE_PULLUP)

    # MQTT
    client = MqttClient(os.environ['MQTT_URL'])
    client.on_connect = on_connect
    client.connect()
    client.loop_forever()

Ejemplo n.º 4
0
class SmartHomeController:
    device_controller = None
    mqtt_client = None
    device_serial = None
    devices = None
    loop_thread = None
    publish_thread = None

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

        print(self.devices)

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

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

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

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

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

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

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

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

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

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

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

            if not loop_thread_alive:
                sh.loop_thread.start()

            if not publish_thread_alive:
                sh.publish_thread.start()

            time.sleep(1)

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

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

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

        return search.group("serial")
Ejemplo n.º 5
0
import json
import time
from random import random
from datetime import datetime

from mqtt_client import MqttClient

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

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

while True:
    timestamp = datetime.utcnow()
    num = random() * 100
    msg = {'timestamp': timestamp.strftime("%Y-%m-%d %H:%M:%S"), 'value': num}
    print(f'Publishing: {msg}')
    client.publish(topic, json.dumps(msg))
    time.sleep(3)
Ejemplo n.º 6
0
from mqtt_client import MqttClient
from handler import Handler

mac = "xx:xx:xx:xx:xx:xx"
thing_id = "1"

ip = "xxx.xxx.xxx.xxx"
port = 1883
client_name = "Client"

#file_name = "data.txt"
minutes = 0.5

thing = BleDevice(mac, thing_id)
mqtt = MqttClient(ip, port, client_name)
handler = Handler()

thing.connect()
mqtt.connect()

handler.mqtt_setup(mqtt)
#handler.open_file(file_name)
#thing.print_svc_char()
thing.setup()
thing.set_handler(handler)

thing.get_data(minutes)

thing.disconnect()
mqtt.disconnect()
#handler.close_file()
Ejemplo n.º 7
0
        dash()
        word_space()


gpio = mraa.Gpio(13)
gpio.dir(mraa.DIR_OUT)

# boot time ring
gpio.write(1)
time.sleep(1.0)
gpio.write(0)

# MQTT
mqtt_client = MqttClient(os.environ['MQTT_URL'])
mqtt_client.on_connect = on_mqtt_connect
mqtt_client.connect()
mqtt_client.loop_start()

# Twitter
auth = OAuth(ACCESS_TOKEN, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)

t = Twitter(auth=auth)
message = "AC Control Box started at " + str(datetime.datetime.now())

while True:
    try:
        t.statuses.update(status=message)
        print "Tweeted!"
        break
    except Exception as e:
        #print "Twitter error({0}): {1}".format(e.errno, e.strerror)