示例#1
0
    def _handle(self, r):
        print(r)
        messages = {message['type']: message['value'] for message in r}

        if 'AC_temperature' in messages:
            if DEBUG: print("Setter temperatur")
            self.target_temp = messages['AC_temperature']
            if self.AC_controller is not None:
                if DEBUG: print("oppdaterer temperatur")
                # If AC-session is started, and user wants to update temperature
                self.AC_controller.update_temperature(self.target_temp)

        if "AC_timer" in messages:
            if self.AC_controller is not None:
                self.AC_controller.deactivate()
                messages["AC_enabled"] = True
            if DEBUG: print("Setter tidspunkt")
            self.target_time = messages["AC_timer"]

        if 'AC_enabled' in messages and (self.AC_controller is not None) != (messages['AC_enabled']):
            if messages['AC_enabled']:
                if DEBUG: print("Setter på AC (evt. timer)")
                # Activate AC by creating temperature object
                self.AC_controller = Temperature(self.car_control, self.target_temp, self, self.status, self.target_time)
            else:
                if self.AC_controller is not None:
                    if DEBUG: print("Deaktiverer")
                    # Deactivate AC
                    self.AC_controller.deactivate()
示例#2
0
def read_temp_process(state):
    state['update_display'] = True
    if not state['sensor']:
        try:
            state['sensor'] = W1ThermSensor()
        except Exception as e:
            print('sensor not yet plugged in')

    sensor = state['sensor']
    try:
        new_temp = Temperature(sensor.get_temperature())
        state['current_temp'] = new_temp
        print("Saved: {0}".format(str(new_temp)))
        state['isDisconnected'] = False
    except Exception as e:
        state['isDisconnected'] = True
        print('sensor unpluged')
    if not state['isDisconnected']:
        try:
            send_temp_to_firebase(state)
            # print('(firebase pushing commented out)')
        except Exception as e:
            print('problem pushing to firebase:')
            print(e)
    try:
        send_connection_status_to_firebase(state)
    except Exception as e:
        print('problem pushing isDisconnected')
        print(e)
 def fetchTempDiff(self, cities):
     for c in cities:
         historicalAvgTemp = self.calculateAvgTemp(c, self.getOldDate())
         currentAvgTemp = self.calculateAvgTemp(c, self.getCurrentDate())
         self.cityTempDiffs[c] = Temperature(
             historicalAvgTemp, currentAvgTemp,
             currentAvgTemp - historicalAvgTemp)
示例#4
0
def ProcessData():
    light = photoresistorValue()
    temp = Temperature()

    data = devTempLight(temp.getTemperature(), light.get_Voltage(),
                        datetime.datetime.now())
    jsonData = jsonpickle.encode(data, unpicklable=False)
    print(jsonData)
示例#5
0
 def record_temperature(self, patient, temp_val, method):
     temp = Temperature(temp_val, method)
     temp.rate_temperature()
     for p in self._patients:
         if p._name == patient:
             p.add_temperature(temp)
             return
     self.add_patient(Patient(patient))
示例#6
0
def Main():
    gameIntro = GameIntro()
    gameIntro.getIntro()
    player = Player()
    player.namePlayer()
    weather = Weather()
    weather.getWeather()
    print ("Today's weather forecast is %s." % (weather.weather))
    temperature = Temperature()
    temperature.getTemperature()
    print("Today's temperature will %s degrees." % (temperature.temperature))
    print("Let's get our supplies and make some lemonade.")
    price = Pricing()
    price.setprice()
    playerChoice.setPrice()
示例#7
0
df.Date = df.Date.apply(lambda x: str(x[0:4] + '-' + x[4:6] + '-' + x[6:8]))
df.Date = pd.to_datetime(df['Date'], format = '%Y-%m-%d', exact=True)
df.set_index(df['Date'])

"""Plot time series. """
"""
df.plot('Date','Average', style='-b', linewidth = 0.5)
plt.grid('on')
plt.show()
"""

#t1 = [i%365 for i in range(0, len(df.Date))]
t = np.linspace(0, len(df.Average), len(df.Average), dtype=int)


tempt = Temperature(n=62, dt = 62)
tempt.seasonality()
#tempt.fit_season()

"""Create list of seasonal function values and convert to column in dataframe."""
season = []
for i in range(len(t)):
	season.append(func(t[i], a0, a1, a2, a3))
df['Season'] = pd.Series(tempt.seasonality())

"""Plot seasonal curve with plot of temperatures."""
df.plot(x ='Date', y = ['Average', 'Season'], style=['-b', '-r'], linewidth = 0.8)
plt.grid('on')
plt.show()

"""Remove seasonal effect and store as column in dateframe."""
示例#8
0
    def loads(self, noaa_string):
        ''' load in a report (or set) from a string '''
        self.raw = noaa_string
        self.weather_station = noaa_string[4:10]
        self.wban = noaa_string[10:15]
        expected_length = int(noaa_string[0:4]) + self.PREAMBLE_LENGTH
        actual_length = len(noaa_string)
        if actual_length != expected_length:
            msg = "Non matching lengths. Expected %d, got %d" % (
                expected_length, actual_length)
            raise ish_reportException(msg)

        try:
            self.datetime = datetime.strptime(noaa_string[15:27], '%Y%m%d%H%M')
        except ValueError:
            ''' some cases, we get 2400 hours, which is really the next day, so 
      this is a workaround for those cases '''
            time = noaa_string[15:27]
            time = time.replace("2400", "2300")
            self.datetime = datetime.strptime(time, '%Y%m%d%H%M')
            self.datetime += timedelta(hours=1)

        self.report_type = ReportType(noaa_string[41:46].strip())

        self.latitude = float(noaa_string[28:34]) / self.GEO_SCALE
        self.longitude = float(noaa_string[34:41]) / self.GEO_SCALE
        self.elevation = int(noaa_string[46:51])
        ''' other mandatory fields '''
        self.wind_direction = Direction(noaa_string[60:63], Direction.RADIANS,
                                        noaa_string[63:64])
        self.wind_observation_direction_type = noaa_string[64:64]
        self.wind_speed = Speed(
            int(noaa_string[65:69]) / float(self.SPEED_SCALE),
            Speed.METERSPERSECOND, noaa_string[69:70])
        self.sky_ceiling = Distance(int(noaa_string[70:75]), Distance.METERS,
                                    noaa_string[75:76])
        self.sky_ceiling_determination = noaa_string[76:77]
        self.visibility_distance = Distance(int(noaa_string[78:84]),
                                            Distance.METERS,
                                            noaa_string[84:85])
        self.visibility_variability = noaa_string[85:86]
        self.visibility_variability_quality = noaa_string[86:87]

        self.air_temperature = Temperature(
            int(noaa_string[87:92]) / self.TEMPERATURE_SCALE, Units.CELSIUS,
            noaa_string[92:93])
        self.dew_point = Temperature(
            int(noaa_string[93:98]) / self.TEMPERATURE_SCALE, Units.CELSIUS,
            noaa_string[98:99])

        self.humidity = Humidity(str(self.air_temperature),
                                 str(self.dew_point))
        self.sea_level_pressure = Pressure(
            int(noaa_string[99:104]) / self.PRESSURE_SCALE,
            Pressure.HECTOPASCALS, noaa_string[104:104])
        ''' handle the additional fields '''
        additional = noaa_string[105:108]
        if additional == 'ADD':
            position = 108
            while position < expected_length:
                try:
                    (position, (addl_code, addl_string)) = self._get_component(
                        noaa_string, position)
                    self._additional[addl_code] = addl_string
                except ish_reportException, err:
                    ''' this catches when we move to remarks section '''
                    break
    def read_file(self):
        """
        This method will read the CSV data file and assign to the data points property a list of the data points held in
        this CSV data file

        :return: nothing
        """

        # Clear down any existing entries
        self.__dataPointsList = []
        self.__dataLogList = []

        # Used as flag to skip the first row from the CSV file which is header
        skip_header_row = False

        # Open the CSV data file for reading and read each text line in sequence until and of life
        file = open(self.filePath, "r")

        # Read each line from the CSV data file
        for line in file:

            # Check to see if the first row has been read
            if skip_header_row:

                # The values of the current row will be splited and save as a tuple
                # each value can be access by it's index
                # the number of indexes will be determined by how many columns are in the CSV data file
                row = line.split(",")

                # Store the values of the current row
                entriNo = str(row[0])
                date = str(row[1])
                timeStamp = str(row[2])
                temperature = str(row[3])
                humidity = str(row[4])
                staff_code = str(row[5])  # Added on May-2019

                # take the date and time values in order to create a datetime object
                splitDateValue = date.split(
                    "/"
                )  # format: number les then 10 ---> 5/3/2019 || bigger then 10 --> 10/10/2019
                splitTimeValue = timeStamp.split(
                    ":"
                )  #format: if the numbers are les then 10 ---> 9:1:1 if bigger --->> 11:11:11

                # this datetime object is used to get the 0 in front of the numbers that are les then 10
                date_time_object = datetime(int(splitDateValue[2]),
                                            int(splitDateValue[1]),
                                            int(splitDateValue[0]),
                                            int(splitTimeValue[0]),
                                            int(splitTimeValue[1]),
                                            int(splitTimeValue[2]))

                timeStamp = date_time_object.time(
                )  #time stamp format: less then 10 --> 01:01:00 || bigger then 10 --> 10:20:30

                scaleTemp = "C"  # temperature measuring scale
                scaleHumidity = "%"  # humidity measuring scale

                tempData = Temperature(
                    float(temperature), scaleTemp
                )  #Create a temperature object and pass the necessary attributes
                humidityData = Humidity(
                    float(humidity), scaleHumidity
                )  #Create a humidity object and pass the necessary attributes

                #Create a datapoint object and pass the necessary attributes
                data_point = DataPoint(entriNo, str(date), str(timeStamp),
                                       tempData.value, humidityData.value,
                                       staff_code)

                #Add the data point created into a list with data points
                self.dataPointsList.append(data_point.List_format())
            else:
                #When is set to True the data from the CSV file will be read
                skip_header_row = True
示例#10
0
from Lcd import Lcd
from Temperature import Temperature
from time import sleep, strftime
from datetime import datetime
import commands

DEVICE_ADDRESS = "28-00000244197d"
DEVICE_FILENAME = "/sys/bus/w1/devices/" + DEVICE_ADDRESS + "/w1_slave"

SERIAL_PORT = "/dev/ttyAMA0"
IP_ADDRESS = commands.getoutput("hostname -I").split(" ")[0]

TEMPERATURE_TEXT = "Temp: {0:.2f}"

lcd = Lcd(SERIAL_PORT)
temperature = Temperature(DEVICE_FILENAME)

if (lcd.isOpen()):
    showIp = True
    changes = 0
    text = TEMPERATURE_TEXT.format(temperature.read())
    while 1:
        lcd.clear()
        lcd.write(datetime.now().strftime("%d %b %H:%M:%S"))
        lcd.moveTo(1, 0)
        if (changes == 5):
            changes = 0
            text = IP_ADDRESS if showIp else TEMPERATURE_TEXT.format(
                temperature.read())
            showIp = not showIp
示例#11
0
from firebase_admin import firestore
from time import sleep
from Temperature import Temperature

cred = credentials.Certificate("./lab1-firebase-admin-sdk-key.json")
firebase_admin.initialize_app(cred)

db = firestore.client()
temps = db.collection(u"temps")

offset = 15
temp_range = 30

print("connection test... this may take a moment")
count = 0
for doc in temps.stream():
    count += 1
print("{0} documents already exist.".format(count))
print("Writing a new data point every second.")

from w1thermsensor import W1ThermSensor
sensor = W1ThermSensor()

while True:
    new_doc = temps.document()
    new_temp = Temperature(sensor.get_temperature())
    new_doc.set(new_temp.to_dict(firestore_timestamp=True))
    print("Saved: {0}".format(str(new_temp)))
    sleep(1)

示例#12
0
Created on 11-Oct-2014

@author: ghantasa
'''

from Temperature import Temperature
from Distance import Distance
from Memory import Memory
from Weight import Weight

if __name__ == '__main__':
    while (True):
        choice = input('Available conversions ... \n' + '1. Temperature\n' +
                       '2. Distance\n' + '3. Memory\n' + '4. Weight\n' +
                       '5. Exit\n' + 'Please enter your choice ... ')
        if choice == '1':
            t = Temperature()
            t.convert()
        elif choice == '2':
            d = Distance()
            d.convert()
        elif choice == '3':
            m = Memory()
            m.convert()
        elif choice == '4':
            w = Weight()
            w.convert()
        else:
            print('Exiting now ... Bye!')
            break
示例#13
0
    "/home/pi/Desktop/IOT_THING_RoadReviewPublisher/private.pem.key",
    "/home/pi/Desktop/IOT_THING_RoadReviewPublisher/certi.txt")
myMQTTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

device_id = 1234
spi = spidev.SpiDev()
spi.open(0, 0)

ldr = Ldr(spi)
noise = Noise(spi)
air = Air(spi)
weather = Temperature()
loc = Location()


#for motion
def dist(a, b):
    return math.sqrt((a * a) + (b * b))


def get_y_rotation(x, y, z):
    radians = math.atan2(x, dist(y, z))
    return -math.degrees(radians)


def get_x_rotation(x, y, z):
    radians = math.atan2(y, dist(x, z))
示例#14
0
from time import *  # Used for sleep method
from bluetooth import *  # Imports libraries that supports Bluetooth
from AlphaBot import AlphaBot
from Buzzer import Buzzer
from Rgb import Rgb
from Temperature import Temperature
import instructions  # Methods where String commands are translated into separate instructions

# ----------------------------------------- INITIALIZATION -------------------------------------------------------------

Ab = AlphaBot(
)  # Instance of AlphaBot created    | delivers EcliBot movement methods
b = Buzzer(
    23)  # Instance of Buzzer created      | buzzer can be switched on/off
t = Temperature(
    11,
    18)  # Instance of Temperature created | temperature can be red from sensor
rgb = Rgb(
    5, 19, 16
)  # Instance of Rgb created         | LED diode can turns red, green, blue, or off

commands = []  # List designed for storing instructions for EcliBot
step = 0  # Counter, used for keeping track the number of Strings received

GPIO.setmode(
    GPIO.BCM)  # Referring to the pins by the "Broadcom SOC channel" number
GPIO.setwarnings(False)  # Disable warnings

# ----------------------------------------- CUSTOMIZED MOVE METHODS ----------------------------------------------------

示例#15
0
from random import random
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from time import sleep
from Temperature import Temperature

cred = credentials.Certificate("./lab1-firebase-admin-sdk-key.json")
firebase_admin.initialize_app(cred)

db = firestore.client()
temps = db.collection(u"temps")

offset = 15
temp_range = 5

print("connection test... this may take a moment")
count = 0
for doc in temps.stream():
    count += 1
print("{0} documents already exist.".format(count))
print("Writing a new data point every second.")

while True:
    new_doc = temps.document()
    new_temp = Temperature(random() * temp_range + offset)
    new_doc.set(new_temp.to_dict(firestore_timestamp=True))
    print("Saved: {0}".format(str(new_temp)))
    sleep(1)

示例#16
0
def main():

    sleep(.1)

    # Pins
    GPIO.setmode(GPIO.BCM)

    GPIO.setup(BACKLIGHT_PIN, GPIO.OUT)
    GPIO.setup(PUSH_BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(SWITCH_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    GPIO.output(BACKLIGHT_PIN, 1)

    disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))
    font = ImageFont.load_default()
    disp.begin(contrast=60)
    disp.clear()
    disp.display()
    try:
      sensor = W1ThermSensor()
    except Exception as e:
      print('sensor unplug on start up')
      sensor = None
    db = firestore.client()

    GPIO.output(BACKLIGHT_PIN, 0)

    state = {}
    # Hardware Status
    state['isDisconnected'] = False
    state['isPressed'] = False
    state['isOn'] = not GPIO.input(SWITCH_PIN)
    state['update_display'] = False
    # Hardware Object Instances
    state['sensor'] = sensor
    state['font'] = font
    state['disp'] = disp
    # Temp
    state['current_temp'] = Temperature(0.0)
    # Firebase docs/collections
    state['temps_collection'] = db.collection(u"temps")
    state['prefs_document'] = db.collection(u"texting").document(u"prefs")
    state['sensor_document'] = db.collection(u"toggles").document(u"sensor")
    state['switch_document'] = db.collection(u"toggles").document(u"switch")
    state['button_document'] = db.collection(u"toggles").document(u"button")
    # Twilio Object
    state['twilio_client'] = Client(TwilioCreds().sid, TwilioCreds().auth_token)
    # Local state from firebase
    state['low_msg'] = 'temp went too low'
    state['high_msg'] = 'temp '
    state['number_to_text'] = '+16307404172'
    state['low_threshold'] = 10
    state['high_threshold'] = 30
    # Processes
    state['update_display_process'] = ''
    state['read_temp_process'] = ''
    state['send_text_if_required_process'] = ''
    state['update_state_from_firebase_process'] = ''

    state['button_document'].set({u'isPressed': GPIO.input(PUSH_BUTTON_PIN) is 1})

    def button_pressed(pin):
        if GPIO.input(PUSH_BUTTON_PIN) and state['isOn']:
            state['isPressed'] = True
            state['button_document'].set({u'isPressed': True})
        else:
            state['isPressed'] = False
            disp.clear()
            disp.display()
            state['button_document'].set({u'isPressed': False})
            GPIO.output(BACKLIGHT_PIN, 0)

    def switch_flipped(pin):
        sleep(.02)
        if not GPIO.input(SWITCH_PIN):
            print('switch is on')
            state['isOn'] = True
            state['switch_document'].set({u'isOn': True})
            start_processes()
            print('processes resumed')
        else:
            print('switch is off');
            state['isOn'] = False
            state['switch_document'].set({u'isOn': False})
            GPIO.output(BACKLIGHT_PIN, 0)
            state['disp'].clear()
            state['disp'].display()
            schedule.clear()
            print('processes halted')

    # Interrupts:
    GPIO.add_event_detect(PUSH_BUTTON_PIN, edge=GPIO.BOTH, callback=button_pressed, bouncetime=50)
    GPIO.add_event_detect(SWITCH_PIN, edge=GPIO.BOTH, callback=switch_flipped, bouncetime=200)

    def run_threaded(job_function, state):
        job_thread = threading.Thread(target=job_function, kwargs=dict(state=state))
        job_thread.start()

    def start_processes():
        schedule.every(0.005).seconds.do(run_threaded, job_function=update_display_process, state=state)
        schedule.every(1).seconds.do(run_threaded, job_function=read_temp_process, state=state)
        schedule.every(5).seconds.do(run_threaded, job_function=send_text_if_required_process, state=state)
        schedule.every(1).seconds.do(run_threaded, job_function=update_state_from_firebase_process, state=state)

    # ? Is this working? Would think this might need to be in the while loop
    #   Pretty sure it's working tho so I guess don't touch it?
    if state['isOn']:
        start_processes()

    while True:
        schedule.run_pending()
        sleep(0.005)