예제 #1
0
from twilio.rest import Client

logging.getLogger('twilio.http_client').setLevel(logging.WARNING)

mongo = MongoClient(os.environ['MONGODB_URI'], connect=False)
app = Celery(broker=os.environ['MONGODB_URI'])

SMTP_PASSWORD = os.getenv('smtpPassword')
SMTP_EMAIL = '*****@*****.**'

account_sid = os.getenv('twilioAccount')
auth_token = os.getenv('twilioToken')
client = Client(account_sid, auth_token)

mongo.db = mongo.get_database()

logger = get_task_logger(__name__)

port = 465
context = ssl.create_default_context()


def age(born):
    today = datetime.date.today()
    return today.year - born.year - ((today.month, today.day) <
                                     (born.month, born.day))


def create_notification(test_id, kind):
    notification = mongo.db.notifications.insert_one(
예제 #2
0
"""
    FreeIOT Parse Package Initial Script

    Author: Noah Gao
    Updated at: 2018-02-23
"""
import os
from pymongo import MongoClient

mongo = MongoClient(host=os.environ.get("MONGO_HOST") or "localhost",
                    port=int(os.environ.get("MONGO_PORT")) or 27017)
mongo.db = mongo[os.environ.get("MONGO_DBNAME") or "test"]
def main():
    global last_temp

    # initialize the lastMinute variable to the current time to start
    last_minute = datetime.datetime.now().minute
    # on startup, just use the previous minute as lastMinute
    last_minute -= 1
    if last_minute == 0:
        last_minute = 59

    # select {0, 90, 180, 270}, if you need to rotate the HAT
    sense.set_rotation(180);

    # infinite loop to continuously check weather values
    while 1:
        # The temp measurement smoothing algorithm's accuracy is based
        # on frequent measurements, so we'll take measurements every 5 seconds
        # but only upload on measurement_interval
        current_second = datetime.datetime.now().second
        # are we at the top of the minute or at a 5 second interval?
        if (current_second == 0) or ((current_second % 5) == 0):
            # ========================================================
            # read values from the Sense HAT
            # ========================================================
            # Calculate the temperature. The get_temp function 'adjusts' the recorded temperature adjusted for the
            # current processor temp in order to accommodate any temperature leakage from the processor to
            # the Sense HAT's sensor. This happens when the Sense HAT is mounted on the Pi in a case.
            # If you've mounted the Sense HAT outside of the Raspberry Pi case, then you don't need that
            # calculation. So, when the Sense HAT is external, replace the following line (comment it out  with a #)
            calc_temp = get_temp()
            # with the following line (uncomment it, remove the # at the line start)
            # calc_temp = sense.get_temperature_from_pressure()
            # or the following line (each will work)
            # calc_temp = sense.get_temperature_from_humidity()
            # ========================================================
            # At this point, we should have an accurate temperature, so lets use the recorded (or calculated)
            # temp for our purposes
            temp_c = round(calc_temp, 1)
            temp_f = round(c_to_f(calc_temp), 1)
            humidity = round(sense.get_humidity(), 0)
            # convert pressure from millibars to inHg before posting
            pressure = round(sense.get_pressure() * 0.0295300, 1)
            print("Temp: %sF (%sC), Pressure: %s inHg, Humidity: %s%%" % (temp_f, temp_c, pressure, humidity))

            # display the temp using the HAT's LED light
            msg = "%sC"% (temp_c)
            sense.show_message(msg, scroll_speed=0.1, text_colour=b)

            # get the current minute
            current_minute = datetime.datetime.now().minute
            # is it the same minute as the last time we checked?
            if current_minute != last_minute:
                # reset last_minute to the current_minute
                last_minute = current_minute
                # is minute zero, or divisible by 10?
                # we're only going to take measurements every MEASUREMENT_INTERVAL minutes
                if (current_minute == 0) or ((current_minute % MEASUREMENT_INTERVAL) == 0):
                    # get the reading timestamp
                    now = datetime.datetime.now()
                    print("\n%d minute mark (%d @ %s)" % (MEASUREMENT_INTERVAL, current_minute, str(now)))
                    # set last_temp to the current temperature before we measure again
                    last_temp = temp_f

                    # ========================================================
                    # Upload the weather data to Weather Underground
                    # ========================================================
                    # is weather upload enabled (True)?
                    if WEATHER_UPLOAD:
                        # From http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol
                        print("Uploading data to Weather Underground")
                        # build a weather data object
                        weather_data = {
                            "action": "updateraw",
                            "ID": wu_station_id,
                            "PASSWORD": wu_station_key,
                            "dateutc": "now",
                            "tempf": str(temp_f),
                            "humidity": str(humidity),
                            "baromin": str(pressure),
                        }
                        try:
                            upload_url = WU_URL + "?" + urlencode(weather_data)
                            response = urllib2.urlopen(upload_url)
                            html = response.read()
                            print("Server response:", html)
                            # do something
                            response.close()  # best practice to close the file
                        except:
                            print("Exception:", sys.exc_info()[0], SLASH_N)
                    else:
                        print("Skipping Weather Underground upload")
                    
                    # ========================================================
                    # Upload weather data to my mongoDB
                    # ========================================================
                    # is my mongoDB upload enabled (True)?
                    if MONGODB_UPLOAD:
                        # our weather data
                        weather_maindata = {
                            "temperature": str(temp_c),
                            "humidity": str(humidity),
                            "pressure": str(pressure),
                            "device": os.uname()[1],
                            "uploadDatetime" : datetime.datetime.now().replace(microsecond=0).isoformat(),
                        }
                        try:
                            # connection
                            print("uploading data to my mongoDB")
                            client = MongoClient(mongoConfig.MONGODB_URL)
                            db = client.db(mongoConfig.DB_NAME)
                            db.collection('weather_data')
                            # post
                            result = db.reviews.insert_one(weather_data)
                            print("mongoDB response:", result)
                        except:
                            print("Exception:", sys.exc_info()[0], SLASH_N)
                    else:
                        print("Skipping mongoDB upload")

        # wait a second then check again
        # You can always increase the sleep value below to check less often
        time.sleep(1)  # this should never happen since the above is an infinite loop

    print("Leaving main()")
def configure_mongo():
    client = MongoClient(os.environ.get('DB_URL'))
    client.db = client[os.environ.get('DB_NAME')]
    return client
예제 #5
0
def configure_mongo(config):
    client = MongoClient(config.get('mongo', 'uri'))
    client.db = client[config.get('mongo', 'db')]
    return client
예제 #6
0
from functools import update_wrapper

app = Flask(__name__)
# https://github.com/acoomans/flask-autodoc
auto = Autodoc(app)

# Detect If Running in Development mode or on server
if "ENV" in os.environ:
    app.debug = False
else:
    app.debug = True

mongo = MongoClient(
    "mongodb://*****:*****@ds043057.mongolab.com:43057/heroku_app24455461"
)
mongo.db = mongo['heroku_app24455461']


def crossdomain(origin=None,
                methods=None,
                headers=None,
                max_age=21600,
                attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
예제 #7
0
from .dataManager import DatabaseManager, DataSource, NDNWMDaily
from pymongo import MongoClient

mongo = MongoClient("mongodb://*****:*****@ds043057.mongolab.com:43057/heroku_app24455461")
mongo.db = mongo['heroku_app24455461']
예제 #8
0
파일: main.py 프로젝트: jumpjumpdog/MQTT
"""
    MQTT Adapter Module
"""
import os
import json
import paho.mqtt.client as paho
from Base.base import BaseAdapter
from tool import equipmentQuery, getEqpByID, online
from pymongo import MongoClient
import time
import json
import random

mongo = MongoClient("localhost", 27017)
mongo.db = mongo["freeiot"]
temperature_col = mongo.db["temperature"]
temperature_topic = "temperature"

online_eqps = []
eqps_t = {}


def init_online_eqps():
    eqps = equipmentQuery()
    for eqp in eqps:
        online_eqps.append(eqp['id'])
        max_t = int(eqp['max_t'])
        min_t = int(eqp['min_t'])
        eqps_t[eqp['id']] = [max_t, min_t, (max_t + min_t) / 2]