def main_loop(self, home_path, messages): tw = tweet() auth = tw.Create(home_path) __stream = tweepy.Stream(auth, StreamListener(messages), secure=True) while True : try: __stream.timeout = None __stream.userstream() except myExeption() : time.sleep(60) __stream = tweepy.Stream(auth,StreamListener(messages), secure=True) except myExeptionDisconnect() : time.sleep(60) __stream = tweepy.Stream(auth,StreamListener(messages), secure=True) except : time.sleep(60) __stream = tweepy.Stream(auth,StreamListener(messages), secure=True)
def send(self, db, message, home_path): bTempture = False bGraph = False if db.InTemptureName(message): bTempture = True if db.InGraphName(message): bGraph = True if not bTempture and not bGraph: return tw = tweet() tw.Create(home_path) TempGet = TempGetter() TempGet.Create(home_path) TempGet.GetTemptureFromDevices() nowtime = db.GetNowTime(message) if nowtime is None: return date_msg = "現在(" + nowtime.strftime("%Y/%m/%d %H:%M:%S") + ")の" if bTempture: notify_msg = date_msg + "温度は、" TempGet.GetTemptureFromDevices() for device in TempGet.GetDevices(): notify_msg += TempGet.GetDeviceNickName(device) + "は" + str(round(TempGet.GetDeviceTempture(device),2)) + "度、" notify_msg += "になります" tw.DoMsg(notify_msg) if bGraph: notify_msg = date_msg + "温度グラフは、こちらです" tg = tempgraph() tg.Do(home_path, nowtime.year, nowtime.month, nowtime.day, notify_msg)
query = """SELECT COUNT(status) FROM boiler_status WHERE status_time::date = '{0}';""".format(opdate.strftime('%Y-%m-%d')) cursor.execute(query) dcount = cursor.fetchall()[0][0] # If the system is on, or if it had a state change today, then run the analysis if dstatus == 'ON' or dcount > 0: # Boiler info query = """SELECT ROUND(btu, 2) AS btu, ROUND(gallons, 2) AS gallons, ROUND(kwh, 2) AS kwh, boiler_cycles, ROUND(total_boiler_runtime, 2) AS total_boiler_runtime, ROUND(avg_boiler_runtime, 2) AS avg_boiler_runtime, ROUND(min_boiler_runtime, 2) AS min_boiler_runtime, ROUND(max_boiler_runtime, 2) AS max_boiler_runtime FROM boiler_summary('{0} 00:00:00', '{0} 23:59:59')""".format(opdate.strftime('%Y-%m-%d')) cursor.execute(query) data = cursor.fetchall() btu, gallons, kwh, boiler_cycles, total_boiler_runtime, avg_boiler_runtime, min_boiler_runtime, max_boiler_runtime = data[0] # Circulator info query = """SELECT circulator_cycles, ROUND(total_circulator_runtime, 2) AS total_circulator_runtime, ROUND(avg_circulator_runtime, 2) AS avg_circulator_runtime, ROUND(min_circulator_runtime, 2) AS min_circulator_runtime, ROUND(max_circulator_runtime, 2) AS max_circulator_runtime FROM circulator_summary('{0} 00:00:00', '{0} 23:59:59')""".format(opdate.strftime('%Y-%m-%d')) cursor.execute(query) data = cursor.fetchall() circulator_cycles, total_circulator_runtime, avg_circulator_runtime, min_circulator_runtime, max_circulator_runtime = data[0] # Insert it into the db query = """INSERT INTO boiler_daily_statistics (date, btu, gallon, kwh, boiler_cycles, total_boiler_runtime, avg_boiler_runtime, min_boiler_runtime, max_boiler_runtime, circulator_cycles, total_circulator_runtime, avg_circulator_runtime, min_circulator_runtime, max_circulator_runtime, updated) VALUES ('{0}', {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, CURRENT_TIMESTAMP);""".format(opdate.strftime('%Y-%m-%d'), btu, gallons, kwh, boiler_cycles, total_boiler_runtime, avg_boiler_runtime, min_boiler_runtime, max_boiler_runtime, circulator_cycles, total_circulator_runtime, avg_circulator_runtime, min_circulator_runtime, max_circulator_runtime) cursor.execute(query) db.commit() status = """Boiler: {0}h, {1} cycles, mean of {2} min/cycle. Circulator: {3}h, {4} cycles, mean of {5} min/cycle. {6} btu, {7} gal, {8} kwh.""".format(round(total_boiler_runtime / 60, 1), boiler_cycles, round(avg_boiler_runtime, 1), round(total_circulator_runtime / 60, 1), circulator_cycles, round(avg_circulator_runtime, 1), round(btu, 0), round(gallons, 1), round(kwh, 1)) if not args.rundate: # status = """Boiler: {0}h, {1} cycles, mean of {2} min/cycle. Circulator: {3}h, {4} cycles, mean of {5} min/cycle. {6} btu, {7} kwh.""".format(round(total_boiler_runtime / 60, 1), boiler_cycles, round(avg_boiler_runtime, 1), round(total_circulator_runtime / 60, 1), circulator_cycles, round(avg_circulator_runtime, 1), round(btu, 0), round(kwh, 1)) tweet(status) else: print(status) # Close database connection cursor.close() db.close()
# print centroids center, dist = vq.kmeans(data, centroids) print center code, distance = vq.vq(data, center) print distance print code def init(M): Centroids = canopy(M,1,10) arr_M = convert_to_array(M) arr_cent = convert_to_array(Centroids) code = k_means_init(arr_M, arr_cent) # print code l = [] t1 = tweet("",1,0) l.append(t1) t2 = tweet("",2,0) l.append(t2) t3 = tweet("",5,0) l.append(t3) t4 = tweet("",6,0) l.append(t4) t5 = tweet("",15,0) l.append(t5) t6 = tweet("",17,0) l.append(t6) init(l)
center, dist = vq.kmeans(data, centroids) print center code, distance = vq.vq(data, center) print distance print code def init(M): Centroids = canopy(M, 1, 10) arr_M = convert_to_array(M) arr_cent = convert_to_array(Centroids) code = k_means_init(arr_M, arr_cent) # print code l = [] t1 = tweet("", 1, 0) l.append(t1) t2 = tweet("", 2, 0) l.append(t2) t3 = tweet("", 5, 0) l.append(t3) t4 = tweet("", 6, 0) l.append(t4) t5 = tweet("", 15, 0) l.append(t5) t6 = tweet("", 17, 0) l.append(t6) init(l)
p = argparse.ArgumentParser(prog="send_status.py") p.add_argument('-p', '--piname', dest="piname", required=True, help="The name of the pi being monitored.") args = p.parse_args() db = psycopg2.connect(host=dbhost, database=dbname, user=dbuser) cursor = db.cursor() query = """SELECT (CURRENT_TIMESTAMP - timestamp) < interval '5 minutes' AS success, notified FROM pi_checkin WHERE pi = '{0}';""".format(args.piname) try: cursor.execute(query) success, notified = cursor.fetchall()[0] if not success: if not notified: #send a tweet status = """Hey @jessebishop, {0} hasn't been heard from in over 5 minutes!""".format(args.piname) tweet(status) query = """UPDATE pi_checkin SET notified = TRUE WHERE pi = '{0}';""".format(args.piname) cursor.execute(query) else: query = """SELECT (CURRENT_TIMESTAMP - timestamp) > interval '1 day' AS check FROM pi_checkin WHERE pi = '{0}';""".format(args.piname) cursor.execute(query) check = cursor.fetchall()[0][0] if check: status = """Hey @jessebishop, {0} hasn't been heard from in over a day!""".format(args.piname) tweet(status) query = """UPDATE pi_checkin SET timestamp = CURRENT_TIMESTAMP - interval '6 minutes' WHERE pi = '{0}';""".format(args.piname) cursor.execute(query) else: query = """UPDATE pi_checkin SET notified = FALSE WHERE pi = '{0}'""".format(args.piname) cursor.execute(query) except Exception, msg:
from tweet import * from arduino import * import time arduino = Arduino('COM6') arduino.output([]) buttonPin = 8 print "INITIATE" today = 0 total = 0 while True: button = arduino.getState(buttonPin) time.sleep(0.1) if button: today += 1 total += 1 tmp = arduino.getTemp() arduino.LCD(today, total, int(round(tmp))) name = str(raw_input("Who pressed me?! ")) print tweet(name + " pressed the big red button!") time.sleep(1)
def Do(self, home_path, year, month, day, tweetmsg): seprate = os.sep filename = home_path + "%s%04d%s%02d%s%02d.json" % (os.sep,year,os.sep,month,os.sep,day) graphfilename = home_path + "%s%04d%s%02d%s%02d.png" % (os.sep,year,os.sep,month,os.sep,day) try: file = open(filename,"r") except: sys.exit(1) jsonObjects = json.load(file) file.close() x = [] xgrid = ["00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "23:59"] xgrid.sort() # keylist = jsonObjects.keys() # for timedata in keylist: # x.append(timedata) # y_temp1.append(jsonObjects[timedata]["temp1"]) # y_temp2.append(jsonObjects[timedata]["temp2"]) # 取得した時刻のラベルを設定する keylist = jsonObjects.keys() plot_temptures_min = {} plot_temptures_max = {} xgrid_temptures = {} for timedata in keylist: hourmin = timedata.split(":") hour = int(hourmin[0]) minuts = int(hourmin[1]) for curi in range(len(xgrid)): nexti = curi + 1 if nexti >= len(xgrid): nexti = curi xgrid_hourmin = xgrid[curi].split(":") xgrid_hour = int(xgrid_hourmin[0]) xgrid_minuts = int(xgrid_hourmin[1]) xgrid_next_hourmin = xgrid[nexti].split(":") xgrid_next_hour = int(xgrid_next_hourmin[0]) xgrid_next_minuts = int(xgrid_next_hourmin[1]) if xgrid[curi] not in xgrid_temptures: xgrid_temptures.update({xgrid[curi]:{"arrays":[], "min":{}, "max":{}}}) now_minuts = hour * 60 + minuts if not ((now_minuts >= xgrid_hour * 60 + xgrid_minuts) and (now_minuts < xgrid_next_hour * 60 + xgrid_next_minuts)): continue # print (timedata + ":" + str(jsonObjects[timedata])) # print ("data %d:%d" % (hour, minuts)) # print ("graph %d %d" % (xgrid_hour, xgrid_minuts)) # print ("graph next %d %d" % (xgrid_next_hour, xgrid_next_minuts)) # print (xgrid[curi] + ":" + str(jsonObjects[timedata])) xgrid_temptures[xgrid[curi]]["arrays"].append(jsonObjects[timedata]) # 最小値を更新する for tempkey in jsonObjects[timedata]: if tempkey not in plot_temptures_min: plot_temptures_min[tempkey] = [] if tempkey not in xgrid_temptures[xgrid[curi]]["min"]: xgrid_temptures[xgrid[curi]]["min"][tempkey] = jsonObjects[timedata][tempkey] continue if xgrid_temptures[xgrid[curi]]["min"][tempkey] > jsonObjects[timedata][tempkey]: xgrid_temptures[xgrid[curi]]["min"][tempkey] = jsonObjects[timedata][tempkey] # 最大値を更新する for tempkey in jsonObjects[timedata]: if tempkey not in plot_temptures_max: plot_temptures_max[tempkey] = [] if tempkey not in xgrid_temptures[xgrid[curi]]["max"]: xgrid_temptures[xgrid[curi]]["max"][tempkey] = jsonObjects[timedata][tempkey] continue if xgrid_temptures[xgrid[curi]]["max"][tempkey] < jsonObjects[timedata][tempkey]: xgrid_temptures[xgrid[curi]]["max"][tempkey] = jsonObjects[timedata][tempkey] for xgridtime in xgrid: tempKeys = plot_temptures_min.keys() for tempKey in tempKeys: plot_temptures_min[tempKey].append(0) plot_temptures_max[tempKey].append(0) for temptures in xgrid_temptures[xgridtime]["arrays"]: tempKeys = temptures.keys() for tempKey in tempKeys: plot_temptures_min[tempKey][-1] = xgrid_temptures[xgridtime]["min"][tempKey] plot_temptures_max[tempKey][-1] = xgrid_temptures[xgridtime]["max"][tempKey] tempKeys = plot_temptures_min.keys() max_length = 0 for tempKey in tempKeys: max_length = max(len(plot_temptures_min[tempKey]), max_length) for tempKey in tempKeys: for counter in range(len(plot_temptures_min[tempKey]), max_length): plot_temptures_min[tempKey].append(0) tempKeys = plot_temptures_max.keys() max_length = 0 for tempKey in tempKeys: max_length = max(len(plot_temptures_max[tempKey]), max_length) for tempKey in tempKeys: for counter in range(len(plot_temptures_max[tempKey]), max_length): plot_temptures_max[tempKey].append(0) # データをセット fig = plt.figure() tempKeys = plot_temptures_min.keys() tg = TempGetter() tg.Create(home_path) gridx = 1 for tempKey in tempKeys: ax = fig.add_subplot(2, 1, gridx) gridx = gridx + 1 xval = [parser.parse(xv) for xv in xgrid] devicename = tg.GetDeviceNickName(tempKey) if devicename is None: devicename = tempKey with plt.style.context('fivethirtyeight'): ax.plot(xval,plot_temptures_max[tempKey],linestyle="-",label="max", marker='o', linewidth = 2.0, color='red') ax.plot(xval,plot_temptures_min[tempKey],linestyle="-",label="min", marker='o', linewidth = 2.0, color='green') ax.set_ylim(0, 60) ax.set_xlabel("Time") ax.set_ylabel("Tempture") ax.legend(loc="upper right") ax.set_title("%04d/%02d/%02d(%s)" % (year,month,day, tg.GetDeviceNickNameEN(tempKey))) ax.grid() # グラフのフォーマットの設定 days = mdates.HourLocator() # every day daysFmt = mdates.DateFormatter('%H:%M') ax.xaxis.set_major_locator(days) ax.xaxis.set_major_formatter(daysFmt) fig.autofmt_xdate() plt.savefig(graphfilename) if tweetmsg is not "": tw = tweet() tw.Create(home_path) tw.DoImage(graphfilename, tweetmsg)