Ejemplo n.º 1
0
def dumpRecordData(*_):
    col = [None] * len(header)
    dataS = {
        'epoch': dt.datetime.now().timestamp(),
        'date_time': dt.datetime.now(),
        'date': dt.datetime.now().date().isoformat(),
        'time': dt.datetime.now().time().isoformat(),
        'year': dt.datetime.now().year,
        'month': dt.datetime.now().month,
        'week_num': (dt.datetime.now().isocalendar())[1],
        'day': dt.datetime.now().day,
        'hour': dt.datetime.now().hour,
        'minute': dt.datetime.now().minute,
        'second': dt.datetime.now().second,
        'weight': round(weightScale.getWeightKg(), 2),
        'temperature': round(temperature.getTemperature(), 2),
        'humidity': round(temperature.getHumidity(), 2),
        'name': configJson['idName'],
        'core_temp': piStat.getCPUTemp(),
        'free_space': piStat.getFreeSpaceStat()
    }
    for colName in header:
        index = header.index(colName)
        col[index] = dataS[colName.lower()]
    csvFile.addRow(dumpFile, col)
Ejemplo n.º 2
0
def main(max_temperature):
    #ログファイル
    pod = opPod.OperatePod()

    start = time.time()
    elapse = 0

    temperature = 0
    #max 120 min
    while temperature < max_temperature:

        temperature = temper.getTemperature()

        print(temperature, max_temperature)

        if temperature <= max_temperature:
            print("turn on")
            pod.turn_on()
        elif temperature >= max_temperature:
            print("turn off")
            pod.turn_off()
            break
        time.sleep(30)
        elapse = time.time()

    pod.turn_off()
    pod.end()

    #log.close()
    print("設定温度に到達しました")
Ejemplo n.º 3
0
def main():
    cursor = db.cursor()
    cursor.execute("SELECT * from Products")
    data = cursor.fetchone()
    if data is None:
        print("Logged in wrong")
    else:
        print(str(data))
    target = 15
    maxTemp = 20
    LEDColour.setup(target, maxTemp, True)
    while True:
        temp = round(temperature.getTemperature(), 1)  # get temperature
        doorOpen = doorStatus.getDoorStatus()
        changeLED.changeLED(LEDColour.getLEDColour(temp))
        time.sleep(1)
        updateTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
        with open("../data.json", "w") as outfile:
            json.dump(
                {
                    "time": updateTime,
                    "temp": temp,
                    "target": target,
                    "doorOpen": doorOpen,
                    "products": [
                        {"pid": 1, "name": "sandwich", "date": "14-01-2016"},
                        {"pid": 2, "name": "cucumber", "date": "15-01-2016"},
                    ],
                },
                outfile,
                sort_keys=True,
                indent=4,
                separators=(",", ": "),
            )
Ejemplo n.º 4
0
def main(running_time, max_temperature):
    check_interval = 10
    #ログファイル
    log = open(
        "log/" + datetime.datetime.now().strftime("%m-%d_%H-%M") + ".txt", 'w')

    log.write("start稼働,間隔,設定温度=" + str(running_time) + "," +
              str(check_interval) + "," + str(max_temperature) + "\n")

    pod = opPod.OperatePod()

    start = time.time()
    elapse = 0

    while elapse - start <= running_time:
        temperature = temper.getTemperature()
        log.write("時間:" + str(elapse - start) + "/温度:" + str(temperature) +
                  "℃\n")
        if temperature <= max_temperature:
            pod.turn_on()
        elif temperature >= max_temperature:
            pod.turn_off()
        time.sleep(check_interval)
        elapse = time.time()

        print("temperature", temperature, "elapse-start", elapse - start)

    pod.end()
    log.close()
Ejemplo n.º 5
0
def main():
    LEDColour.test()
    LEDColour.setup(15, 20, True)
    while (True):
        #temp = temp + 0.01 # test value as get temperature doesnt work
        temp = round(temperature.getTemperature(), 1)
        RGB = LEDColour.getLEDColour(temp)
        changeLED.changeLED(RGB)
        time.sleep(0.2)
Ejemplo n.º 6
0
def read_temperature_value():
    logger.info("Invoking this function will read the Temperature_Moisture Value")
    try:
        while True:
            temperatureValue = temperature.getTemperature()
            logger.info(temperatureValue)
	    temperature_db(temperatureValue)
            temperatureJson = json.dumps(json.loads('{"thingName":"Temperature", "value":'+str(temperatureValue)+'}'))
            awsIOTMQTTTemperatureClient.publish(publishTopic, temperatureJson, 0)
	    time.sleep(1)

    except KeyboardInterrupt:
        print("CTRL-C!! Exiting...")
Ejemplo n.º 7
0
def main():
    cursor = db.cursor()
    cursor.execute("SELECT * from Products")
    data = cursor.fetchone()
    if data is None:
        print("Logged in wrong")
    else:
        print(str(data))
    target = 15
    maxTemp = 20
    LEDColour.setup(target, maxTemp, True)
    while (True):
        temp = round(temperature.getTemperature(), 1)  #get temperature
        doorOpen = doorStatus.getDoorStatus()
        changeLED.changeLED(LEDColour.getLEDColour(temp))
        time.sleep(1)
        updateTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
        with open('../data.json', 'w') as outfile:
            json.dump(
                {
                    'time':
                    updateTime,
                    'temp':
                    temp,
                    'target':
                    target,
                    'doorOpen':
                    doorOpen,
                    'products': [
                        {
                            'pid': 1,
                            'name': "sandwich",
                            'date': "14-01-2016"
                        },
                        {
                            'pid': 2,
                            'name': "cucumber",
                            'date': "15-01-2016"
                        },
                    ]
                },
                outfile,
                sort_keys=True,
                indent=4,
                separators=(',', ': '))
Ejemplo n.º 8
0
def get_token():
    """
    Callback route when the user has accepted to share his data.
    Once the auth has arrived Withings servers come back with
    an authentication code and the state code provided in the
    initial call
    """
    code = request.args.get('code')
    state = request.args.get('state')

    payload = {
        'grant_type': 'authorization_code',
        'client_id': CLIENT_ID,
        'client_secret': CUSTOMER_SECRET,
        'code': code,
        'redirect_uri': CALLBACK_URI
    }

    r_token = requests.post(f'{ACCOUNT_URL}/oauth2/token', data=payload).json()

    access_token = r_token.get('access_token', '')
    refresh_token = r_token.get('refresh_token', '')

    payload = {
        'action': 'requesttoken',
        'grant_type': 'refresh_token',
        'client_id': CLIENT_ID,
        'client_secret': CUSTOMER_SECRET,
        'refresh_token': refresh_token
    }
    r_refresh_token = requests.get(f'{WBSAPI_URL}/v2/oauth2',
                                   params=payload).json()
    access_token = r_refresh_token.get('access_token', '')
    print(r_refresh_token)
    print(r_refresh_token['body']['access_token'])

    access_token = r_refresh_token['body']['access_token']

    # GET Some info with this token
    headers = {'Authorization': 'Bearer ' + access_token}
    payload = {'action': 'getdevice'}

    # List devices of returned user
    r_getdevice = requests.get(f'{WBSAPI_URL}/v2/user',
                               headers=headers,
                               params=payload).json()

    payload = {
        'action': 'getmeas',
        'meastype': 71,
    }
    user_temp = requests.get(f'{WBSAPI_URL}/measure',
                             headers=headers,
                             params=payload).json()

    latest_measurement = user_temp["body"]["measuregrps"][0]["measures"][0]

    val = latest_measurement["value"]
    unit = latest_measurement["unit"]
    latest_temp = val * 10**unit

    try:
        temperature = latest_temp
    except Exception as e:
        print('Please provide your temperature as an argument.')
        exit()

    username, password = readUsernamePassword()
    try:
        jsessionID = login(username, password)
    except Exception as e:
        print('Your login credentials are invalid.')
        exit()

    isCheck = readIsCheck()
    if isCheck:
        tempResponseText = getTemperature(jsessionID)
    else:
        tempResponseText = submitTemperature(jsessionID, temperature)
        print('Submitted temperature of %s°C' % temperature)

    tempData = parseTemperatureTable(tempResponseText)
    printData(tempData)

    return user_temp
def main(text):
    #nancy_notify('Virtual Assistant Started')
    #text = ""
    #while text != "terminate":
    #if text == "":
    #    speak('On your mark sir')
    #else:
    #    speak('ready sir')

    #text = "youtube results ok jaanu title song"

    if text == 'mic':
        speak('listening')
        print('listening')
        text = listen().lower()
        nancy_notify(text)
        print(text)

    elif text == '':
        text = input('Enter command => ')
        if text == 'q':
            exit(1)

    update_log(text)

    if text in ["who are you", "introduce yourself"]:
        speak('I am Nancy, your personal assistant.')
        return

    elif "describe yourself" in text:
        speak("I am Nancy, your personal assistant. I use python's speech recognition module "
                          "to understand voice input, and google's text to speech technology to give output.")
        return

    elif "toss a coin" in text:
        if choice(range(1, 11)) % 2 == 0:
            speak('It is tails')
        else:
            speak('It is heads')
        return

    elif text in ["throw a dice", "throw a die"]:
        speak(str(choice(range(1, 7))))
        return

    elif text == "connection problem":
        nancy_notify('connection problem Nancy exiting...')
        exit()

    elif text in ['stop', 'pause']:
        speak('Suspending')
        return 'pause'

    elif text in ["didn't get you", "terminate"]:
        if text == "terminate":
            nancy_notify('Virtual Assistant Exited')
            speak("Bye Bye")
            exit(1)
        else:
            speak(text)
            # continue

    '''
    elif text in ["stop", "go to sleep"]:
        speak('Okay sir')
        stop = StopApp()
        stop.mainloop()
        continue
    '''

    #speak('fetching results please wait')

    if 'folder' in text or 'directory' in text:#match(r'^.*(folder)|(directory) .*$', text):
        speak(nautilus.gen_folder_path(text))

    elif 'drive' in text:#search(r'drive', text):
        speak(nautilus.gen_drive_path(text))

    elif 'meaning' in text or 'define' in text:#search(r'(meaning)|(define)', text):
        speak(getMeaning(text))

    elif 'temperature' in text:#search(r'temperature', text):
        speak(getTemperature(text))

    elif 'run' in text or 'execute' in text:#search(r'(run)|(execute)', text):
        speak(nautilus.open_gnome(text))

    elif 'browse' in text:#search(r'(browse)', text):
        speak(get_address(text))

    elif 'google' in text or 'search' in text:# search(r'(google)|(search)', text):
        speak(get_result(text))

    elif 'download audio' in text:#search(r'download\s(audio)|(song)', text):
        speak(page_link(' '.join(text.split()[2:])))

    elif 'youtube results' in text:#search(r'download\s(video)|(mp4)', text):
        speak(youtube_link(text[text.find('youtube results of')+len('youtube results of')+1:]))

    elif 'download lyrics' in text:#search(r'download\s(lyrics)', text):
        speak(lyrics_down(text))

    else:
        speak(nautilus.gen_file_path(text))
Ejemplo n.º 10
0
Archivo: Neo.py Proyecto: luisvh/pi
 def getTemperature(self):
     return t.getTemperature()