· 8 years ago · Jun 28, 2018, 03:56 PM
1import dweepy
2import sqlite3
3import time
4
5# Written by Liz from Learn Robotics (www.learnrobotics.org)
6# Version 1.0 | Last Updated: June 27, 2018
7# ---
8# Software downloaded from the Learn Robotics website is provided 'as is'
9# without warranty of any kind, either express or implied, including,
10# but not limited to, the implied warranties of fitness for a purpose,
11# or the warranty of non-infringement.
12
13
14# name of the thing as it's spelled on dweet.io
15thing = input('Enter thing name: ')
16
17#create a database for the given thing
18conn = sqlite3.connect(thing+'.sqlite')
19cur = conn.cursor()
20
21cur.execute('''
22CREATE TABLE IF NOT EXISTS Data
23 (id INTEGER UNIQUE, today DATE, sent_at TIME,
24 temperature INTEGER, humidity INTEGER)
25''')
26
27# Pick up where we left off
28start = None
29cur.execute('SELECT max(id) FROM Data' )
30try:
31 row = cur.fetchone()
32 if row is None :
33 start = 0
34 else:
35 start = row[0]
36except:
37 start = 0
38
39if start is None : start = 0
40
41count = 0
42fail = 0
43many = 0
44while True:
45
46 if ( many < 1 ) :
47 conn.commit()
48 sval = input('How many messages: (Press enter to exit) ')
49 if ( len(sval) <1 ) : break
50 many = int(sval)
51
52 start = start + 1
53
54 cur.execute('SELECT id FROM Data WHERE id=?', (start,) )
55 try:
56 print("fetching data...")
57 row = cur.fetchone()
58 if row is not None : continue
59 except:
60 row = None
61
62 many = many - 1
63
64 url = dweepy.get_latest_dweet_for(thing)
65 text = "None"
66 try:
67 #store the data as a dictionary
68 dict = url[0]
69 #print(dict)
70 longdate = dict['created']
71 #print(longdate)
72 date = longdate[:10]
73 #print(date)
74 stamptime = longdate[11:19]
75 #print(stamptime)
76 tempC = dict['content']['temp']
77 #print(tempC)
78 tempF = (int(tempC)*(9/5))+32
79 #print(tempF)
80 hum = dict['content']['humidity']
81 #print(hum)
82 except KeyboardInterrupt:
83 print('')
84 print('Program interrupted by user...')
85 break
86 except Exception as e:
87 print("Unable to retrieve device data",url)
88 print("Error",e)
89 fail = fail + 1
90 if fail > 5 : break
91 continue
92
93 cur.execute('''INSERT OR IGNORE INTO Data (id, today, sent_at, temperature, humidity)
94 VALUES ( ?, ?, ?, ?, ? )''', ( start, date, stamptime, tempC, hum))
95
96 print("reading #: ",start)
97 if count % 50 == 0 : conn.commit()
98 if count % 100 == 0 : time.sleep(1)
99 #if many == start : break;
100
101print("Done fetching!")
102
103print('Do you want to print out the current readings? ')
104printout = input('Type Y for YES or any key for NO ')
105
106if (printout == 'Y' or printout == 'y'):
107 print("Status update for",thing)
108 print("Date:",date)
109 print("Time:",stamptime)
110 print("Current temperature is...",tempC,"C")
111 print("Current temperature is...",tempF,"F")
112 print("Current humidity is...",hum)
113else:
114 print("Done!")
115
116print('open',thing+'.sqlite','to view collected data.')