示例#1
0
    def test_now(self):
        dt_now = datetime.now()
        now = udatetime.now()

        self.assertIsInstance(now, datetime)
        self.assertEqual(now.year, dt_now.year)
        self.assertEqual(now.month, dt_now.month)
        self.assertEqual(now.day, dt_now.day)
        self.assertEqual(now.hour, dt_now.hour)
        self.assertEqual(now.minute, dt_now.minute)
        self.assertEqual(now.second, dt_now.second)
示例#2
0
    def test_now(self):
        dt_now = datetime.now()
        now = udatetime.now()

        self.assertIsInstance(now, datetime)
        self.assertEqual(now.year, dt_now.year)
        self.assertEqual(now.month, dt_now.month)
        self.assertEqual(now.day, dt_now.day)
        self.assertEqual(now.hour, dt_now.hour)
        self.assertEqual(now.minute, dt_now.minute)
        self.assertEqual(now.second, dt_now.second)
示例#3
0
    def __init__(self, user, code=None, created=None, expires=None):
        self.user = user

        if created is None:
            created = udatetime.now()

        if expires is None:
            expires = datetime.timedelta(hours=1).seconds

        if code is None:
            code = util.random_id()

        self.code = code
        self.created = created
        self.expires = expires
示例#4
0
    def save(self, user):
        """
        Save a user object.
        """
        with self.redis.pipeline() as pipe:
            pipe.hmset(user.key, user.to_redis())
            if "username" in user.changed():
                pipe.hdel(USER_INDEX_KEY, user.old("username"))
                pipe.zrem(USERS_BY_USERNAME, user.old_sortby)

            delta = udatetime.now() - BEGINNING_OF_TIME
            score = delta.seconds

            pipe.zadd(USERS_BY_USERNAME, score, user.sortby)
            pipe.hset(USER_INDEX_KEY, user.username, user.key)
            pipe.execute()
示例#5
0
 def _udatetime():
     return udatetime.now()
示例#6
0
 def udatetime_now():
     udatetime.now()
示例#7
0
 def udatetime_now():
     udatetime.now()

def sendMessageToServer(message):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((REMOTE_HOST, PORT))
        print("Connected")
        s.sendall(message.encode('ascii'))
        print("Message " + message + " sent")
        s.settimeout(2)
        serverMessage = s.recv(1024).decode("utf-8")
        s.close()
        return serverMessage


if __name__ == "__main__":
    timestamp = udatetime.to_string(udatetime.now())

    ### INITIALISE CSV
    file = open("LOG_" + timestamp + ".csv", "a+")
    writer = csv.writer(file, dialect='excel', lineterminator='\n')
    if file.tell() == 0:
        writer.writerow(["TIME", "TEMP", "HUMIDITY", "CO2"])
        file.flush()

    # header for API requests
    headers = {'Content-Type': 'application/json'}

    ### INITIALISE CONFIG TOKEN
    with open("config.json", "r") as configFile:
        config = json.load(configFile)
示例#9
0
def TH_thread(config, temp_optimal, hum_optimal):
    thsensor = si7021.si7021(1)

    # Memory backlog
    backlog_record = []
    # File backlog
    file = open("TH_{}.csv".format(config['room_id']),
                "a+",
                newline='',
                encoding="utf-8")
    writer = csv.writer(file, dialect='excel', lineterminator='\n')
    if (file.tell() == 0):
        writer.writerow(["TIME", "TEMPERATURE", "HUMIDITY"])
        file.flush()
    #file.close()
    # header for API requests
    headers = {'Content-Type': 'application/json'}
    # Check if token is available
    if config['token'] == '':
        config['token'] = userLogin(config['user'], config['pwd'])
    headers['token'] = config['token']
    TH_URL = URL + 'sleep/send_room_data'

    sys_temp_active = False
    sys_hum_active = False

    while (True):
        # Wait 30 seconds
        sleep(30)
        # Read data from sensors
        temperature = thsensor.read_temperature()
        humidity = thsensor.read_humidity()

        if sys_temp_active == False:
            if temperature < temp_optimal - 2.5:
                # Throw Low Temp -> heat up the room
                ifttt_req = requests.post(IFTTT_URL + "{LowTemp}" + IFTTT_KEY)
                sendMessageToServer("LT")
                turnLed(19, True)
                sys_temp_active = True

            if temperature > temp_optimal + 2.5:
                # Throw High Temp -> cool down the room
                ifttt_req = requests.post(IFTTT_URL + "{HighTemp}" + IFTTT_KEY)
                sendMessageToServer("HT")
                turnLed(19, True)
                sys_temp_active = True

        else:
            if temp_optimal - 1.5 < temperature < temp_optimal + 1.5:
                # Back to normal -> Shut down temp activity
                ifttt_req = requests.post(IFTTT_URL + "{ShutTemp}" + IFTTT_KEY)
                sendMessageToServer("TO")
                turnLed(19, False)
                sys_temp_active = False

        if sys_hum_active == False:
            if humidity < hum_optimal - 20:
                # Throw Low Humidity -> humidify the room
                ifttt_req = requests.post(IFTTT_URL + "{LowHumidity}" +
                                          IFTTT_KEY)
                sendMessageToServer("LH")
                turnLed(26, True)
                GPIO.output(26, GPIO.HIGH)
                sys_hum_active = True

            if humidity > hum_optimal + 20:
                # Throw High Humidity -> dehumidify the room
                ifttt_req = requests.post(IFTTT_URL + "{HighHumidity}" +
                                          IFTTT_KEY)
                sendMessageToServer("HH")
                turnLed(26, True)
                GPIO.output(26, GPIO.HIGH)
                sys_hum_active = False

        else:
            if hum_optimal - 20 < humidity < hum_optimal + 20:
                # Back to normal -> shut down humidity activity
                ifttt_req = requests.post(IFTTT_URL + "{ShutHumidity}" +
                                          IFTTT_KEY)
                sendMessageToServer("HO")
                turnLed(26, False)
                GPIO.output(26, GPIO.LOW)
                sys_hum_active = False

        ### IFTTT request
        # iftttreq = requests.post(url=IFTTT_URL + IFTTT_EVENT + IFTTT_KEY, data={'temperature': temperature, 'humidity': humidity})
        # print("****IFTTT REQUEST STATUS: " + iftttreq.status_code + " \n Temperature = " + temperature + " \n Humidity = " + humidity + "****")

        # Assemble data
        timestamp = udatetime.to_string(udatetime.now())
        data = {}
        # Check if token is available
        if config['token'] == '':
            config['token'] = userLogin(config['user'], config['pwd'])
        data['token'] = config['token']
        data['input'] = {
            'room_id': config['room_id'],
            'timestamp': timestamp,
            'temperature': json.dumps(temperature),
            'humidity': json.dumps(humidity)
        }

        # Il file csv per ora lo lasciamo fuori quindi viene fatto indipendentemente dalla connessione o meno
        #file = open("TH.csv","a", encoding = "utf-8")
        #writer = csv.writer(file)
        writer.writerow([timestamp, temperature, humidity])
        file.flush()
        #file.close()
        #file = open("TH.csv","r+", encoding = "utf-8")
        #file.read()

        # Send data to server
        try:
            print("Sending T {0:2.5} H {1:2.5} at time {2:}".format(
                temperature, humidity, timestamp))
            req = requests.post(url=TH_URL, headers=headers, json=data)

            # Check request result
            if req.status_code != 200:
                print("Req status {}:saving TH record on backlog".format(
                    req.status_code))
                backlog_record.append(data)
            else:
                while len(backlog_record) > 0 and requests.post(
                        url=TH_URL, headers=headers,
                        json=backlog_record[0]).status_code == 200:
                    del backlog_record[0]
        except requests.exceptions.ConnectionError:
            print("Connection refused: saving TH record on backlog")
            backlog_record.append(data)
        except KeyboardInterrupt:
            file.close()
            break
示例#10
0
def noise_thread(config):
    # Memory backlog
    backlog_record = []
    # File backlog
    file = open("NOI_{}.csv".format(config['room_id']),
                "a+",
                newline='',
                encoding="utf-8")
    writer = csv.writer(file, dialect='excel', lineterminator='\n')
    if (file.tell() == 0):
        writer.writerow(["TIME", "NOISE"])
        file.flush()
    #file.close()

    # header for API requests
    headers = {'Content-Type': 'application/json'}
    # Check if token is available
    if config['token'] == '':
        config['token'] = userLogin(config['user'], config['pwd'])
    headers['token'] = config['token']
    NOI_URL = URL + 'sleep/send_room_data'

    # Init sensor
    #create the spi  bus
    spi_n = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
    #create the chip select
    cs_n = digitalio.DigitalInOut(
        board.D5)  # non sappiamo a quale board collegarlo
    cs_n.direction = digitalio.Direction.OUTPUT
    cs_n.value = True
    #create mcp object
    mcp_n = MCP.MCP3008(spi_n, cs_n)
    #create an analog input channel
    #chan_n = AnalogIn(mcp_n, MCP.P0)#non sapppiamo a che pin collegato
    sensore_n = SPW2430(mcp_n)

    while (True):
        # Wait 30 seconds
        #sleep(30)
        noise = 0
        counter = 0
        tStart = perf_counter()
        while (perf_counter() < (tStart + 30)):
            noise = noise + sensore_n.read_noise()
            counter = counter + 1
        noise = noise / counter

        # Assemble data
        timestamp = udatetime.to_string(udatetime.now())
        # saving data inside the csv file
        #file = open("noise.csv","a", encoding = "utf-8")
        #writer = csv.writer(file)
        writer.writerow([timestamp, noise])
        file.flush()
        #file.close()
        #file = open("noise.csv","r+", encoding = "utf-8")
        #file.read()

        data = {}
        # Check if token is available
        if config['token'] == '':
            config['token'] = userLogin(config['user'], config['pwd'])
        data['input'] = {
            'room_id': config['room_id'],
            'timestamp': timestamp,
            'noise': json.dumps(noise)
        }
        data['token'] = config['token']
        # Send data to server
        try:
            print("Sending NOI {0:4.5} at time {1:}".format(noise, timestamp))
            req = requests.post(url=NOI_URL, headers=headers, json=data)

            # Check request result
            if req.status_code != 200:
                print("Req status {}:saving NOISE record on backlog".format(
                    req.status_code))
                backlog_record.append(data)
            else:
                while len(backlog_record) > 0 and requests.post(
                        url=NOI_URL, headers=headers,
                        json=backlog_record[0]).status_code == 200:
                    del backlog_record[0]
        except requests.exceptions.ConnectionError:
            print("Connection refused: saving NOISE record on backlog")
            backlog_record.append(data)
        except KeyboardInterrupt:
            file.close()
            break
示例#11
0
def light_thread(config):
    # Memory backlog
    backlog_record = []
    # File backlog
    file = open("LHT_{}.csv".format(config['room_id']),
                "a+",
                newline='',
                encoding="utf-8")
    writer = csv.writer(file, dialect='excel', lineterminator='\n')
    if (file.tell() == 0):
        writer.writerow(["TIME", "LIGHT"])
        file.flush()
    #file.close()

    IFTTT_EVENT = '{getLight}'

    # header for API requests
    headers = {'Content-Type': 'application/json'}
    # Check if token is available
    if config['token'] == '':
        config['token'] = userLogin(config['user'], config['pwd'])
    headers['token'] = config['token']
    LH_URL = URL + 'sleep/send_room_data'

    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
    #create the chip select
    cs = digitalio.DigitalInOut(board.D5)
    mcp = MCP.MCP3008(spi, cs)
    #create an analog input channel on pin 0
    #chan = AnalogIn(mcp, MCP.P1)
    sensore = GA1A12S202(mcp)
    while (True):
        # Come misura della luce prenderei la stessa che aveva usato nel vecchio main che una media di quelle
        # ottenute in 30 secondi (fa 60 prove con uno sleep di 0.5)
        light = 0.0
        for _ in range(60):
            light = light + sensore.read_light()
            sleep(0.5)
        light = light / 60.0

        ### IFTTT request
        iftttreq = requests.post(url=IFTTT_URL + IFTTT_EVENT + IFTTT_KEY,
                                 data={'value1': light})
        # print("****IFTTT REQUEST STATUS: " + iftttreq.status_code + "\n Light = " + light + "****")

        # Assemble data
        timestamp = udatetime.to_string(udatetime.now())
        # Csv file
        #file = open("light.csv","a", encoding = "utf-8")
        #writer = csv.writer(file)
        writer.writerow([timestamp, light])
        file.flush()
        #file.close()
        #file = open("light.csv","r+", encoding = "utf-8")
        #file.read()
        data = {}
        # Check if token is available
        if config['token'] == '':
            config['token'] = userLogin(config['user'], config['pwd'])
        data['token'] = config['token']
        data['input'] = {
            'room_id': config['room_id'],
            'timestamp': timestamp,
            'light': json.dumps(light)
        }
        # Send data to server
        try:
            print("Sending LHT {0:4.5} at time {1:}".format(light, timestamp))
            req = requests.post(url=LH_URL, headers=headers, json=data)

            # Check request result
            if req.status_code != 200:
                print("Req status {}:saving LIGHT record on backlog".format(
                    req.status_code))
                backlog_record.append(data)
            else:
                while len(backlog_record) > 0 and requests.post(
                        url=LH_URL, headers=headers,
                        json=backlog_record[0]).status_code == 200:
                    del backlog_record[0]
        except requests.exceptions.ConnectionError:
            print("Connection refused: saving LIGHT record on backlog")
            backlog_record.append(data)
        except KeyboardInterrupt:
            file.close()
            break
示例#12
0
def carbon_thread(config, co2_optimal):
    # Memory backlog
    backlog_record = []
    # File backlog
    file = open("CARB_{}.csv".format(config['room_id']),
                "a+",
                newline='',
                encoding="utf-8")
    writer = csv.writer(file, dialect='excel', lineterminator='\n')
    if (file.tell() == 0):
        writer.writerow(["TIME", "CO2"])
        file.flush()
    #file.close()

    # header for API requests
    headers = {'Content-Type': 'application/json'}
    # Check if token is available
    if config['token'] == '':
        config['token'] = userLogin(config['user'], config['pwd'])
    headers['token'] = config['token']
    CO_URL = URL + 'sleep/send_room_data'
    # Setup GPIO switch for sensor reset
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(20, GPIO.IN)

    #with SMBusWrapper(1) as bus:

    i2c_bus = busio.I2C(board.SCL, board.SDA, frequency=100000)
    sgp = sgp30(i2c_bus)  #Sgp30(bus, baseline_filename = "sgpbaseline.txt")
    if (GPIO.input(20) == 1):
        sgp_calibrate(sgp)
    else:
        with open("sgpbaseline.txt", "r") as base:
            baseline = json.load(base)
            base.close()
        print("get baseline from file")
        sgp.set_iaq_baseline(baseline[0], baseline[1])

    #sgp.read_measurements()
    sgp.iaq_measure()
    # Warm up the sensor
    for _ in range(20):
        sleep(1)
        #sgp.read_measurements()
        sgp.iaq_measure()

    IFTTT_EVENT = '{HighCarbon}'

    sys_carbon_active = False

    while (True):
        # Wait 1 second to keep sensor active
        for _ in range(30):
            sleep(1)
            # Read data from sensors
            co2, _ = sgp.iaq_measure()  #read_measurements()
            #co2 = getattr(co2, "data")[0]
        # Assemble data
        timestamp = udatetime.to_string(udatetime.now())

        # Recalibrate sensor if necessary
        tnow = datetime.now()
        tset = [
            datetime(tnow.year, tnow.month, tnow.day, hour=11, minute=58),
            datetime(tnow.year, tnow.month, tnow.day, hour=12, minute=2)
        ]
        if ((tnow > tset[0]) & (tnow > tset[1])):
            sgp_calibrate(sgp)

        #File csv
        #file = open("CO2.csv","a", encoding = "utf-8")
        #writer = csv.writer(file)
        writer.writerow([timestamp, co2])
        file.flush()
        #file.close()
        #file = open("CO2.csv","r+", encoding = "utf-8")
        #file.read()

        data = {}
        # Check if token is available
        if config['token'] == '':
            config['token'] = userLogin(config['user'], config['pwd'])
        data['token'] = config['token']
        data['input'] = {
            'room_id': config['room_id'],
            'timestamp': timestamp,
            'co2': json.dumps(co2)
        }

        if sys_carbon_active == False:
            if co2 > co2_optimal + 1500:
                # Throw high co2 -> ventilate the room
                ifttt_req = requests.post(IFTTT_URL + IFTTT_EVENT + IFTTT_KEY)
                sendMessageToServer("HC")
                sys_carbon_active = True

        else:
            if co2 < co2_optimal:
                # Back to normal -> shutdown carbon control
                sys_carbon_active = False
                ifttt_req = requests.post(IFTTT_URL + "{ShutCarbon}" +
                                          IFTTT_KEY)
                sendMessageToServer("CO")

        ### IFTTT REQUEST
        # iftttreq = requests.post(url=IFTTT_URL + IFTTT_EVENT + IFTTT_KEY, data={'CO2': json.dumps(co2)})
        # print("****IFTTT REQUEST STATUS: " + iftttreq.status_code + "\n CO2: " + co2 + "****")

        # Send data to server
        try:
            print("Sending CO2 {0:} at time {1:}".format(co2, timestamp))
            req = requests.post(url=CO_URL, headers=headers, json=data)

            # Check request result
            if req.status_code != 200:
                print("Req status {}:saving CO2 record on backlog".format(
                    req.status_code))
                backlog_record.append(data)
            else:
                while len(backlog_record) > 0 and requests.post(
                        url=CO_URL, headers=headers,
                        json=backlog_record[0]).status_code == 200:
                    del backlog_record[0]
        except requests.exceptions.ConnectionError:
            print("Connection refused: saving CO2 record on backlog")
            backlog_record.append(data)
        except KeyboardInterrupt:
            file.close()
            break