示例#1
0
文件: app.py 项目: SinaHBN/IoT
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = database_file
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.config['MQTT_BROKER_URL'] = 'localhost'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_CLIENT_ID'] = 'mqtt-client'
app.config['MQTT_KEEPALIVE'] = 65535
app.config['MQTT_TLS_ENLABLED'] = False
app.config['MQTT_LAST_WILL_TOPIC'] = 'LastWill'
app.config['MQTT_LAST_WILL_MESSAGE'] = 'Bye!'
app.config['MQTT_LAST_WILL_QOS'] = 0

mqtt = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)


# ______________MODEL______________________________________
class TempAndHum(db.Model):
    id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True)
    temperature = db.Column(db.Float)
    humidity = db.Column(db.Float)
    datetime = db.Column(db.String,
                         default=str(
                             time.strftime("%A, %d. %B %Y %I:%M:%S %p")))

 def test_connect_with_username(self):
     self.app.config['MQTT_USERNAME'] = '******'
     self.app.config['MQTT_PASSWORD'] = '******'
     self.mqtt = Mqtt(self.app)
     self.mqtt.disconnect()
示例#3
0
from flask_mqtt import Mqtt
mqtt = Mqtt()
示例#4
0
app = Flask(__name__)

BROKERS = ["broker.hivemq.com", "mosquitto.org", "test.mosquitto.org"]
BROKER_IND = 2
BROKER = BROKERS[BROKER_IND]
PORT_BROKER = 1883

app.config['SECRET'] = 'my secret key 2'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = BROKER
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False

mqtt = Mqtt(app)
socketio = SocketIO(app)

NUMBER_CONNEXIONS = 0

PI = {
    "sensor":
    "pi",
    "locations": [
        "A532", "A533", "A503", "A507", "A406", "A432", "A433", "A434", "A400",
        "A401", "A402", "A403", "A404"
    ],
    "durations": ["5minutes", "hour", "day"]
}
mqtt.subscribe("hepia/pi/meanByLocation/5minutes")
mqtt.subscribe("hepia/pi/meanByLocation/hour")
mail = Mail(app)

#! MQTT Configurations
app.config['MQTT_BROKER_URL'] = '10.0.0.12'  # Ip addres of broker server
app.config['MQTT_BROKER_PORT'] = 1883  # default port for non-tls connection
app.config[
    'MQTT_USERNAME'] = ''  # set the username here if you need authentication for the broker
app.config[
    'MQTT_PASSWORD'] = ''  # set the password here if the broker demands authentication
app.config[
    'MQTT_KEEPALIVE'] = 5  # set the time interval for sending a ping to the broker to 5 seconds
app.config[
    'MQTT_TLS_ENABLED'] = False  # set TLS to disabled for testing purposes

time.sleep(2)
mqtt = Mqtt(app)

if (mqtt):
    print("[*] MQTT Connected OK!")
    mqtt.subscribe('application/11/device/+/rx')
    print("[*] MQTT Suscribed to application/11/device/+/rx OK!\n\n")

socketio = SocketIO(app, cors_allowed_origins="*")


#! MQTT Callback Function. When a new message arrives, this
#! data is stored in the database table (public.dustbinData)
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    dict_data = json.loads(message.payload)
    print(dict_data)
示例#6
0
from flask import Flask,url_for,request
from flask_mqtt import Mqtt
from flask import render_template
import requests
import json
import pymongo
import paho.mqtt.client as mqtt

app = Flask(__name__)

app.config['MQTT_BROKER_URL'] = '192.168.0.116'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_REFRESH_TIME'] = 1.0  
mqttr = Mqtt(app)

myclient = pymongo.MongoClient("mongodb://*****:*****@app.route('/')
def index():
    return 'Index Hello World'

@mqttr.on_connect()
def handle_connect(client, userdata, flags, rc):
    mqttr.subscribe('user1')
    mqttr.subscribe('user2')
    mqttr.subscribe('user3')

@mqttr.on_message()
def handle_mqtt_message(client, userdata, message):
    payload = message.payload.decode()
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = '192.168.1.133'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False

# Parameters for SSL enabled
# app.config['MQTT_BROKER_PORT'] = 8883
# app.config['MQTT_TLS_ENABLED'] = True
# app.config['MQTT_TLS_INSECURE'] = True
# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'

mqtt = Mqtt(app)
socketio = SocketIO(app)
mqtt.subscribe('machine_park/machine_1')
mqtt.subscribe('machine_park/machine_1/temp')


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/quicksimulation')
def quick_simulation():
    return render_template('quick_simulation.html')

示例#8
0
from flask_mqtt import Mqtt
from app import App, db
from app.models import Dht11, Gaz, Cards
import json
from flask_socketio import SocketIO
from flask import request
from flask_login import current_user

mqtt = Mqtt(App)
socketio = SocketIO(App)

# don't need it because, we have to subscribe and then ONLY read messages from card
"""""
@socketio.on('publish')
def handle_publish(json_str):
    data = json.loads(json_str)
    mqtt.publish(data['topic'], data['message'], data['qos'])
"""


@socketio.on('subscribe')
def handle_subscribe(json_str):
    data = json.loads(json_str)
    mqtt.subscribe(data['topic'])


@socketio.on('unsubscribe_all')
def handle_unsubscribe_all():
    mqtt.unsubscribe_all()

示例#9
0
app.config['SECRET'] = APP_CONFIG['secret']
app.config['TEMPLATES_AUTO_RELOAD'] = APP_CONFIG['templates_auto_reload']
app.config['MQTT_BROKER_URL'] = MQTT_CONFIG['mqtt_broker_url']
app.config['MQTT_BROKER_PORT'] = MQTT_CONFIG['mqtt_broker_port']
app.config['MQTT_USERNAME'] = MQTT_CONFIG['mqtt_username']
app.config['MQTT_PASSWORD'] = MQTT_CONFIG['mqtt_password']
app.config['MQTT_KEEPALIVE'] = MQTT_CONFIG['mqtt_keepalive']
app.config['MQTT_TLS_ENABLED'] = MQTT_CONFIG['mqtt_tls_enabled']

# Parameters for SSL enabled
#app.config['MQTT_BROKER_PORT'] = 8883
#app.config['MQTT_TLS_ENABLED'] = True
#app.config['MQTT_TLS_INSECURE'] = True
#app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'

mqtt = Mqtt(app, mqtt_logging=True)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)


### flask
@app.route('/')
def index():
    return render_template('mqttindex.html')


@app.route('/devices')
def get_devices():
    devices = Device.objects().to_json()
    return Response(devices, mimetype="application/json", status=200)
示例#10
0
from flask import Flask
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from .config import config
from ..mqtt import MQTTWrapper

socketio = SocketIO()
mqtt_client = Mqtt()
mqtt_wrapper = MQTTWrapper(mqtt_client.client, "joyit")
socketio = SocketIO()


def create_app(config_name: str = "default") -> Flask:
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    socketio.init_app(app)
    mqtt_client.init_app(app)
    socketio.init_app(app)

    # blueprints
    from . import main
    app.register_blueprint(main.bp)

    from . import websockets
    app.register_blueprint(websockets.bp)

    return app
示例#11
0
app = Flask(__name__)

app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

app.config['TEMPLATES_AUTO_RELOAD'] = True
#app.config['MQTT_BROKER_URL'] = 'broker.hivemq.com'
app.config['MQTT_BROKER_URL'] = 'test.mosquitto.org'
#app.config['MQTT_BROKER_PORT'] = 1883  # default port for non-tls connection
#app.config['MQTT_USERNAME'] = ''  # set the username here if you need authentication for the broker
#app.config['MQTT_PASSWORD'] = ''  # set the password here if the broker demands authentication
#app.config['MQTT_KEEPALIVE'] = 5  # set the time interval for sending a ping to the broker to 5 seconds
#app.config['MQTT_TLS_ENABLED'] = False  # set TLS to disabled for testing purposes

mqtt = Mqtt(app)

TOPIC_IN = 'upcu/profile/in'
TOPIC_OUT = 'upcu/profile/out'

mqtt.subscribe(TOPIC_IN)
#mqtt.subscribe(TOPIC_OUT)


@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    data = dict(topic=message.topic, payload=message.payload.decode())

    print(data)
    payload = json.loads(data['payload'])
    action = get_action_from_request(payload)
示例#12
0
class MqttClient:
    __initialized = False
    mqtt = Mqtt()

    # Mqtt setup
    @staticmethod
    def setup(app):
        if not MqttClient.__initialized:
            MqttClient.mqtt.init_app(app)
            MqttClient.mqtt.client.on_message = MqttClient.handle_mqtt_message
            MqttClient.mqtt.client.on_subscribe = MqttClient.handle_subscribe
            MqttClient.mqtt.client.on_publish = MqttClient.handle_publish
            MqttClient.__initialized = True

            @MqttClient.mqtt.on_connect()
            def handle_connect(client, userdata, flags, rc):
                print('MQTT client connected')
                MqttClient.mqtt.subscribe('device/+')

            @MqttClient.mqtt.on_disconnect()
            def handle_disconnect():
                print('MQTT client disconnected')

            @MqttClient.mqtt.on_log()
            def handle_logging(client, userdata, level, buf):
                print(level, buf)

            print('MQTT client initialized')

    @staticmethod
    def tear_down():
        if MqttClient.__initialized:
            MqttClient.mqtt.unsubscribe_all()
            if (hasattr(MqttClient.mqtt, 'client')
                    and MqttClient.mqtt.client is not None):
                MqttClient.mqtt.client.disconnect()
            print('MQTT client destroyed')

    @staticmethod
    def handle_subscribe(client, userdata, mid, granted_qos):
        print('MQTT client subscribed')

    @staticmethod
    def handle_mqtt_message(client, userdata, message):
        print("Received message!")
        print("Topic: " + message.topic)
        print("Payload: " + message.payload.decode())
        try:
            # If type is JSON
            devices.create_recording(MqttClient.get_device_id(message.topic),
                                     json.loads(message.payload.decode()))
        except Exception:
            print("ERROR!")
            error_type, error_instance, traceback = sys.exc_info()
            print("Type: " + str(error_type))
            print("Instance: " + str(error_instance))
            return

    @staticmethod
    def handle_publish(client, userdata, mid):
        print("Published message! (" + str(mid) + ")")

    @staticmethod
    def get_device_id(topic):
        device_token, device_id = topic.split("/")
        if device_token == "device":
            return int(device_id)
        else:
            raise ValueError("Topic is in invalid format")
示例#13
0
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 60
app.config['MQTT_TLS_ENABLED'] = False
app.config['MQTT_LAST_WILL_TOPIC'] = 'life'
app.config['MQTT_LAST_WILL_MESSAGE'] = 'bye'
app.config['MQTT_LAST_WILL_QOS'] = 0


# Parameters for SSL enabled
# app.config['MQTT_BROKER_PORT'] = 8883
# app.config['MQTT_TLS_ENABLED'] = True
# app.config['MQTT_TLS_INSECURE'] = True
# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'


mqtt_ws = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)

# 这里的初始化MQTT可以让纯Python代码运行起来
mqtt_client = mqtt_client.Client()
mqtt_client.connect("www.csustauto.xyz", 1883, 60)  # 连接服务器,端口为1883,维持心跳为60秒


@app.route('/')
def hello_world():
    return render_template('index.html')


# 每次访问这个路由将向chat主题,提交一次数据data
@app.route('/mqtts')
示例#14
0
app.config['MQTT_BROKER_PORT'] = 1883
# default authenthication not enabled
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
# ping intervall
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False

# Parameters for SSL disabled
# app.config['MQTT_BROKER_PORT'] = 8883
# app.config['MQTT_TLS_ENABLED'] = True
# app.config['MQTT_TLS_INSECURE'] = True
# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'

# connect client to the local broker
mqtt = Mqtt(app)

# socketIO extension for real time communication
socketio = SocketIO(app)
#-----------------------------------------------------------------------------------------------------------------------

#-------------------------------------ADDITIONAL-FUNCTIONS--------------------------------------------------------------
# build dict with kwargs
def defaultArgs(default_kw):
    "decorator to assign default kwargs"
    def wrap(f):
        def wrapped_f(**kwargs):
            kw = {}
            kw.update(default_kw)  # apply defaults
            kw.update(kwargs)  # apply from input args
            f(**kw)  # run actual function with updated kwargs
示例#15
0
class FlaskMQTTTestCase(unittest.TestCase):
    def setUp(self):

        self.app = Flask(__name__)

    def test_simple_connect(self):
        self.mqtt = Mqtt(self.app)
        self.mqtt._disconnect()

    def test_connect_with_username(self):
        self.app.config['MQTT_USERNAME'] = '******'
        self.app.config['MQTT_PASSWORD'] = '******'
        self.mqtt = Mqtt(self.app)
        self.mqtt._disconnect()

    def test_subscribe(self):
        self.mqtt = Mqtt(self.app)
        self.subscribe_handled = False
        self.unsubscribe_handled = False

        @self.mqtt.on_subscribe()
        def handle_subscribe(client, userdata, mid_, granted_qos):
            self.subscribe_handled = True

        @self.mqtt.on_unsubscribe()
        def handle_unsubscribe(client, userdata, mid_):
            self.unsubscribe_handled = True

        ret, mid = self.mqtt.subscribe('home/test')
        self.assertEqual(ret, MQTT_ERR_SUCCESS)
        wait()

        ret, mid = self.mqtt.unsubscribe('home/test')
        self.assertEqual(ret, MQTT_ERR_SUCCESS)
        wait()

        self.assertTrue(self.subscribe_handled)
        self.assertTrue(self.unsubscribe_handled)

    def test_qos(self):
        self.mqtt = Mqtt(self.app)

        # subscribe to a topic with qos = 1
        self.mqtt.subscribe('test', 1)
        self.assertEqual(1, len(self.mqtt.topics))
        self.assertEqual(('test', 1), self.mqtt.topics['test'])

        # subscribe to same topic, overwrite qos
        self.mqtt.subscribe('test', 2)
        self.assertEqual(1, len(self.mqtt.topics))
        self.assertEqual(('test', 2), self.mqtt.topics['test'])

        # unsubscribe
        self.mqtt.unsubscribe('test')
        self.assertEqual(0, len(self.mqtt.topics))

    def test_topic_count(self):
        self.mqtt = Mqtt(self.app)

        ret, mid = self.mqtt.subscribe('test')
        self.assertEqual(1, len(self.mqtt.topics))

        ret, mid = self.mqtt.subscribe('test')
        self.assertEqual(1, len(self.mqtt.topics))

        self.mqtt.unsubscribe('test')
        self.assertEqual(0, len(self.mqtt.topics))

        self.mqtt.unsubscribe('test')
        self.assertEqual(0, len(self.mqtt.topics))

        ret, mid = self.mqtt.subscribe('test1')
        ret, mid = self.mqtt.subscribe('test2')
        self.assertEqual(2, len(self.mqtt.topics))
        self.mqtt.unsubscribe_all()
        self.assertEqual(0, len(self.mqtt.topics))
        self.mqtt._disconnect()

    def test_publish(self):

        self.mqtt = Mqtt(self.app)
        self.handled_message = False
        self.handled_topic = False
        self.handled_publish = False

        @self.mqtt.on_message()
        def handle_message(client, userdata, message):
            self.handled_message = True

        @self.mqtt.on_publish()
        def handle_publish(client, userdata, mid):
            self.handled_publish = True

        self.mqtt.subscribe('home/test')
        wait()
        self.mqtt.publish('home/test', 'hello world')
        wait()

        self.assertTrue(self.handled_message)
        # self.assertTrue(self.handled_topic)
        self.assertTrue(self.handled_publish)

    def test_on_topic(self):

        self.mqtt = Mqtt(self.app)
        self.handled_message = False
        self.handled_topic = False

        @self.mqtt.on_message()
        def handle_message(client, userdata, message):
            self.handled_message = True

        @self.mqtt.on_topic('home/test')
        def handle_on_topic(*args, **kwargs):
            self.handled_topic = True

        @self.mqtt.on_connect()
        def handle_connect(*args, **kwargs):
            self.mqtt.subscribe('home/test')

        wait()
        self.mqtt.publish('home/test', 'hello world')
        wait()

        self.assertFalse(self.handled_message)
        self.assertTrue(self.handled_topic)

    def test_logging(self):
        self.mqtt = Mqtt(self.app)

        @self.mqtt.on_log()
        def handle_logging(client, userdata, level, buf):
            self.assertIsNotNone(client)
            self.assertIsNotNone(level)
            self.assertIsNotNone(buf)

        self.mqtt.publish('test', 'hello world')

    def test_disconnect(self):
        self.mqtt = Mqtt()
        self.connected = False

        @self.mqtt.on_connect()
        def handle_connect(*args, **kwargs):
            self.connected = True

        @self.mqtt.on_disconnect()
        def handle_disconnect(*args, **kwargs):
            self.connected = False

        self.assertFalse(self.connected)
        self.mqtt.init_app(self.app)
        wait()
        self.assertTrue(self.connected)
        self.mqtt._disconnect()
        wait()
        self.assertFalse(self.connected)
app.config['MQTT_BROKER_PORT'] = 1883
# default authenthication not enabled
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
# ping intervall
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False

# Parameters for SSL disabled
# app.config['MQTT_BROKER_PORT'] = 8883
# app.config['MQTT_TLS_ENABLED'] = True
# app.config['MQTT_TLS_INSECURE'] = True
# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'

# connect client to the local broker
mqtt = Mqtt(app)

# socketIO extension for real time communication
socketio = SocketIO(app)
#-----------------------------------------------------------------------------------------------------------------------

#-------------------------------------ADDITIONAL-FUNCTIONS--------------------------------------------------------------
# build dict with kwargs
def defaultArgs(default_kw):
    "decorator to assign default kwargs"
    def wrap(f):
        def wrapped_f(**kwargs):
            kw = {}
            kw.update(default_kw)  # apply defaults
            kw.update(kwargs)  # apply from input args
            f(**kw)  # run actual function with updated kwargs
示例#17
0
app.config['MQTT_TLS_ENABLED'] = False
app.config['MQTT_LAST_WILL_TOPIC'] = 'home/lastwill'
app.config['MQTT_LAST_WILL_MESSAGE'] = 'bye'
app.config['MQTT_LAST_WILL_QOS'] = 2

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database/accessories.db'
app.config['SECRET_KEY'] = 'mysecret'
db = SQLAlchemy(app)

# Parameters for SSL enabled
# app.config['MQTT_BROKER_PORT'] = 8883
# app.config['MQTT_TLS_ENABLED'] = True
# app.config['MQTT_TLS_INSECURE'] = True
# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'

mqtt = Mqtt(app)
socketio = SocketIO(app)


class Accessorie(db.Model):
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    Name = db.Column(db.String(20), nullable=False)
    Topic = db.Column(db.String(100), nullable=False, unique=True)
    # Image = db.Column(db.String(50), nullable=False,)

    Image_ID = db.Column(db.Integer, db.ForeignKey('image.id'))

    def __repr__(self):
        return '%r' % (self.Name)

示例#18
0
db.session.commit()

user = User.query.first()
if not user:
    user_1 = User(email="*****@*****.**", controller_id=1, password=generate_password_hash("password", method='sha256'))
    user_2 = User(email="*****@*****.**", controller_id=2, password=generate_password_hash("password", method='sha256'))
    db.session.add(user_1)
    db.session.add(user_2)
    db.session.commit()

app.config['MQTT_BROKER_URL'] = 'broker.hivemq.com'
app.config['MQTT_BROKER_PORT'] = 1883
SUBSCRIBE_MQTT_TOPIC = 'my-smart-devices/#'
PUBLISH_MQTT_TOPIC = 'my-smart-devices'

mqtt = Mqtt(app)
socketio = SocketIO(app)

users_online_controller_id = {}


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


# Send initial MQTT message in order to simulate some devices
devices_id_list = ['1', '2']
mqtt.publish(
    topic=f'{PUBLISH_MQTT_TOPIC}/{random.choice(devices_id_list)}/boiler_temp',
    payload=random.randrange(0, 100),
示例#19
0
app.config['MQTT_PASSWORD'] = ''  # set the password here if the broker demands authentication
app.config['MQTT_KEEPALIVE'] = 5  # set the time interval for sending a ping to the broker to 5 seconds
app.config['MQTT_TLS_ENABLED'] = False  # set TLS to disabled for testing purposes



app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'

# MongoDB Config
app.config['MONGODB_DB'] = 'mysmartdatabase'
app.config['MONGODB_HOST'] = 'localhost'
app.config['MONGODB_PORT'] = 27017

# Create database connection object
mqtt = Mqtt()
mqtt.init_app(app)

db = MongoEngine(app)

class Role(db.Document, RoleMixin):
    name = db.StringField(max_length=80, unique=True)
    description = db.StringField(max_length=255)

class User(db.Document, UserMixin):
    email = db.StringField(max_length=255)
    password = db.StringField(max_length=255)
    active = db.BooleanField(default=True)
    confirmed_at = db.DateTimeField()
    picture = db.StringField()
    userID = db.StringField()
'''
	This file creates a ReST API server for accepting the images
	and processing them		
'''
from flask import Flask, request
from flask_mqtt import Mqtt
from people_recognizer import recognize_person
import time, os, fnmatch, shutil

app = Flask(__name__)
app.config['MQTT_BROKER_URL'] = '10.145.140.20'
app.config['MQTT_BROKER_PORT'] = 1883
client = Mqtt(app)


@app.route('/')
def api_root():
    return 'This is the root of the image processing api'


@app.route('/processImage', methods=['GET', 'POST'])
def api_images():
    if request.method == 'GET':
        return 'GET method of processImage. Dummy response. Will be implemented in future.'
    elif request.method == 'POST':
        t = time.localtime()
        timestamp = time.strftime('%b-%d-%Y_%H%M%s', t)
        image_name = ('images/image-' + timestamp + '.png')
        with open(image_name, 'wb') as f:
            f.write(request.data)
            print('[INFO] Image received and saved')
示例#21
0
app.config['MQTT_BROKER_URL'] = 'dev20.gcp'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_CLIENT_ID'] = 'flask_mqtt'
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
app.config['MQTT_CLEAN_SESSION'] = True

# Parameters for SSL enabled
# app.config['MQTT_BROKER_PORT'] = 8883
# app.config['MQTT_TLS_ENABLED'] = True
# app.config['MQTT_TLS_INSECURE'] = True
# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'

mqtt = Mqtt(app, connect_async=True)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)

gdata = dict(topic='sensors/time/null', payload='null')
adata = dict(topic='sensors/auth/null', payload='null')


@app.route('/')
def index():
    mqtt.publish('sensors/time/hello', 'hello world')
    return render_template('index.html')


@app.route('/pub', methods=['POST', 'GET'])
def pub():
# Logging config
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.getLogger('socketio').setLevel(logging.WARNING)
logging.getLogger('engineio').setLevel(logging.WARNING)

eventlet.monkey_patch()
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = 'detector-mqtt'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
app.config['MQTT_CLEAN_SESSION'] = True

mqtt = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)


@app.route('/')
def index():
    return render_template('index.html')


# Prevent caching everywhere
@app.after_request
def add_header(r):
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
示例#23
0
AWS_MOSQUITTO = '3.84.42.130'
AZURE_MOSQUITTO = '40.86.204.73'
security_pin = None

# Flask app constructor
app = Flask(__name__, template_folder="templates")
app.config.update(
    SECRET_KEY='iotSecret_key',
    SQLALCHEMY_DATABASE_URI='postgresql+psycopg2://iotadmin:JerryBetaLocal13'
    '@iot-database.postgres.database.azure.com/iot-server',
    MQTT_BROKER_URL='3.84.42.130',
    MQTT_BROKER_PORt=1883,
    MQTT_KEEPALIVE=60)
socketio = SocketIO(app)
mqtt = Mqtt(app)
db = SQLAlchemy(app)


# <<<   Database Model Definitions  >>>
class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128), nullable=False)
    pw_hash = db.Column(db.String(256), nullable=False)

    is_authenticated = False
    is_active = False
    is_anonymous = False

    def __init__(self, username, password):
示例#24
0
from flask import Flask
from flask import render_template, request
from flask_mqtt import Mqtt
import sqlite3, json, datetime

app = Flask(__name__)
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = '127.0.0.1'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
mqtt = Mqtt(app)
mqtt.subscribe('garden/#')

UI_IP = '127.0.0.1'
UI_PORT = 8180
UI_BASE_URL = 'http://garden.stobi.local/'
IGNORE_PORTS = True

last_read_values = {
    'air_temperature': 0,
    'air_humidity': 0,
    'light': 0,
    'soil_moisture': 0,
    'watering_sys_stat': 'unknow'
}

DB_FILE = "garden-ui.sqlite"
示例#25
0
 def test_simple_connect(self):
     self.mqtt = Mqtt(self.app)
     self.mqtt.disconnect()
示例#26
0
app = Flask(__name__)  #create the server application
app.config['SECRET_KEY'] = 'ecowet'  #not sure what this is for yet
app.config['TEMPLATES_AUTO_RELOAD'] = False
app.config['MQTT_BROKER_URL'] = MQTT_HOST  # use the free broker from HIVEMQ
app.config[
    'MQTT_BROKER_PORT'] = MQTT_PORT  # default port for non-tls connection
app.config[
    'MQTT_USERNAME'] = MQTT_USERNAME  # set the username here if you need authentication for the broker
app.config[
    'MQTT_PASSWORD'] = MQTT_PASSWORD  # set the password here if the broker demands authentication
app.config[
    'MQTT_KEEPALIVE'] = 5  # set the time interval for sending a ping to the broker to 5 seconds
app.config[
    'MQTT_TLS_ENABLED'] = MQTT_TLS_ENABLED  # set TLS to disabled for testing purposes
socketio = SocketIO(app)  #create the socket IO instance for comms
mqtt = Mqtt(app)  #create the mqtt instance for mqtt comms
hostname = FLASK_HOST  #hostname where flask will run
port = FLASK_PORT  #flask port
mqtt_topic = MQTT_BOX_STATUS_TOPIC

thread = Thread()
thread_stop_event = Event()


@app.route("/")  #base route (or path/url)
def index():
    return render_template('index.html')  #display the main html file


@socketio.on('subscribe')  #defined in the javascript
def handle_subscribe(topic):
示例#27
0
class FlaskMQTTTestCase(unittest.TestCase):
    def setUp(self):

        self.app = Flask(__name__)

    def test_simple_connect(self):
        self.mqtt = Mqtt(self.app)
        self.mqtt.disconnect()

    def test_connect_with_username(self):
        self.app.config['MQTT_USERNAME'] = '******'
        self.app.config['MQTT_PASSWORD'] = '******'
        self.mqtt = Mqtt(self.app)
        self.mqtt.disconnect()

    def test_subscribe(self):
        self.mqtt = Mqtt(self.app)
        self.mqtt.subscribe('test')
        self.assertEqual('test', self.mqtt.topics[0])
        self.assertEqual(1, len(self.mqtt.topics))
        self.mqtt.subscribe('test')
        self.assertEqual(1, len(self.mqtt.topics))
        self.mqtt.unsubscribe('test')
        self.assertEqual(0, len(self.mqtt.topics))
        self.mqtt.unsubscribe('test')

        self.mqtt.subscribe('test1')
        self.mqtt.subscribe('test2')
        self.assertEqual(2, len(self.mqtt.topics))
        self.mqtt.unsubscribe_all()
        self.assertEqual(0, len(self.mqtt.topics))
        self.mqtt.disconnect()

    def test_publish(self):

        self.mqtt = Mqtt(self.app)

        @self.mqtt.on_message()
        def handle_message(client, userdata, message):
            print(message)

        @self.mqtt.on_topic('test')
        def handle_on_topic(*args, **kwargs):
            pass

        self.mqtt.subscribe('test')
        self.mqtt.publish('test', 'hello world')
        time.sleep(2)
示例#28
0
from flask.templating import render_template_string
from config import Config
from flask_restful import Api, Resource
from flask_mqtt import Mqtt
from utils import has_payload, is_valid_date, is_valid_uuid
from db_models import db, Sensor, BridgePredictions
import os

appname = "iot-clean-air"
app = Flask(appname)
api = Api(app)
base_url = "/api/v1"
host_path = "http://151.81.28.142:5000"

try:
    mqtt = Mqtt(app)  # Need broker or exception thrown
except Exception:
    print(
        f"\033[91m [ERROR] MQTT broker not found at ip {Config.MQTT_BROKER_URL} \033[00m"
    )
    pass

myconfig = Config
app.config.from_object(myconfig)


class SensorStatus(Resource):
    """Sensor status api.

        -GET request return the status of the window given the uuid.
        -POST request insert the new status of the window in the db and publish on
示例#29
0
from flask import Flask
from config import Config
from flask_login import LoginManager
from flask_mqtt import Mqtt
from pymongo import MongoClient

app = Flask(__name__)
app.config.from_object(Config)

login = LoginManager(app)

client = MongoClient("db:27017")
db = client.mymongodb

mqtt = Mqtt(app)

from app import routes
示例#30
0
from flask import Flask
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from flask_redis import FlaskRedis
import eventlet
import os, sys, eventlet, logging

eventlet.monkey_patch()

mqtt = Mqtt(connect_async=True, mqtt_logging=True)
socketio = SocketIO()
redisc = FlaskRedis(charset="utf-8", decode_responses=True)

def create_app():
    app = Flask(__name__)
    app.config['MQTT_BROKER_URL'] = os.getenv("MQTT_BROKER_URL")  
    app.config['MQTT_BROKER_PORT'] = int(os.getenv("MQTT_PORT"))
    app.config['MQTT_USERNAME'] = os.getenv("MQTT_USER")  
    app.config['MQTT_PASSWORD'] = os.getenv("MQTT_PASSWD")   
    app.config['MQTT_KEEPALIVE'] = 30  # set the time interval for sending a ping to the broker to 30 seconds
    app.config['MQTT_TLS_ENABLED'] = False  # set TLS to disabled for testing purposes
    app.config['MQTT_CLIENT_ID'] = os.getenv("MQTT_CLIENT_ID")
    app.config['REDIS_URL'] = os.getenv("REDIS_URL")
    
    app.debug = os.getenv("DEBUG")

    # have to set this manually because it wont work through app.config for some reason
    mqtt.client_id = os.getenv("MQTT_CLIENT_ID")

    app.logger.info("app config set")