├── Minecraftia.ttf ├── README.md ├── dashboard.py ├── dht-firebase-oled.py ├── dht-firebase.py └── fire.py /Minecraftia.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amphancm/Raspberrypi_Firebase/9991f6df180928dcba2f7391ee84aedde5946750/Minecraftia.ttf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Raspberrypi_Firebase 2 | Raspberry pi IoT with Firebase realtime database 3 | 4 | Code 5 | dht-firebase.py ( without OLED Display) 6 | dht-firebase-oled.py ( need OLED display ) 7 | and Minecraftia.ttf is font for OLED. 8 | 9 | Web Blog https://raspberrypi4u.blogspot.com/2017/12/raspberry-pi-iot-firebase-realtimedatabase.html 10 | 11 | Developer http://softpowergroup.net/ 12 | email amphancm@gmail.com 13 | 14 | System Diagram 15 | 16 | ![alt text](https://4.bp.blogspot.com/-A8m5uY0d0K0/Wi---ccdMmI/AAAAAAAAwBA/wHkjCaRsDTAPgPh9R12gF-OS3vBxL1s-wCLcBGAs/s640/RaspberryPi_Firebase_SystemDiagram_1200.jpg) 17 | 18 | 19 | My Website 20 | http://softpowergroup.net/ 21 | 22 | My Blog 23 | https://raspberrypi4u.blogspot.com 24 | https://androidcontrol.blogspot.com 25 | 26 | email : info@softpowergroup.net 27 | amphancm@gmail.com 28 | Tel. +6681-6452400 ( Thailand ) 29 | 30 | Google+ https://plus.google.com/+SoftpowergroupNetThailand/ 31 | Facebook : https://www.facebook.com/softpowergroup 32 | 33 | 34 | -------------------------------------------------------------------------------- /dashboard.py: -------------------------------------------------------------------------------- 1 | 2 | import RPi.GPIO as GPIO 3 | from time import sleep 4 | import datetime 5 | 6 | from firebase import firebase 7 | import pigpio 8 | #import DHT22 9 | import urllib2, urllib, httplib 10 | import json 11 | import os 12 | from functools import partial 13 | 14 | # Global variables 15 | LOGGER = 1 16 | buttonTest = 23 17 | sensor_pin_number = 21; 18 | firebase = firebase.FirebaseApplication('https://YOUR_ID.firebaseio.com', None) 19 | 20 | # LOGGER 21 | def printlog(text): 22 | if(LOGGER): 23 | print(text) 24 | # LOGGER 25 | 26 | 27 | # Start script 28 | # ============================================================================ 29 | printlog("Script Started\n") 30 | 31 | #Information about temperature, humidity, cpu, disk, RAM 32 | # Initiate GPIO for pigpio 33 | pi = pigpio.pi() 34 | # Setup the sensor 35 | #dht22 = DHT22.sensor(pi, sensor_pin_number) 36 | #dht22.trigger() 37 | 38 | 39 | #def readDHT22(): 40 | # Get a new reading 41 | # dht22.trigger() 42 | # Save our values 43 | # humidity = '%.2f' % (dht22.humidity()) 44 | # temp = '%.2f' % (dht22.temperature()) 45 | # return (humidity, temp) 46 | 47 | # Return CPU temperature as a character string 48 | def getCPUtemperature(): 49 | res = os.popen('vcgencmd measure_temp').readline() 50 | return(res.replace("temp=","").replace("'C\n","")) 51 | 52 | # Return RAM information (unit=kb) in a list 53 | # Index 0: total RAM 54 | # Index 1: used RAM 55 | # Index 2: free RAM 56 | def getRAMinfo(): 57 | p = os.popen('free') 58 | i = 0 59 | while 1: 60 | i = i + 1 61 | line = p.readline() 62 | if i==2: 63 | return(line.split()[1:4]) 64 | 65 | # Return % of CPU used by user as a character string 66 | def getCPUuse(): 67 | return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\ 68 | ))) 69 | 70 | # Return information about disk space as a list (unit included) 71 | # Index 0: total disk space 72 | # Index 1: used disk space 73 | # Index 2: remaining disk space 74 | # Index 3: percentage of disk used 75 | def getDiskSpace(): 76 | p = os.popen("df -h /") 77 | i = 0 78 | while 1: 79 | i = i +1 80 | line = p.readline() 81 | if i==2: 82 | return(line.split()[1:5]) 83 | 84 | ##Date time formatting 85 | dateString = '%d/%m/%Y %H:%M:%S' 86 | 87 | 88 | def updatePiInfo(): 89 | printlog("## Updating Firebase Info.. ##") 90 | firebase.put("/Settings", "/last_update_datetime", datetime.datetime.now().strftime(dateString)) 91 | 92 | ##retrive max & min humidity (remove the %) 93 | #maxHumidity = firebase.get("/Controls/Sensors/Humidity/max_inside", None) 94 | #maxHumidity = maxHumidity[:-1] 95 | 96 | #minHumidity = firebase.get("/Controls/Sensors/Humidity/min_inside", None) 97 | #minHumidity = minHumidity[:-1] 98 | 99 | #retrieve max & min temperature (remove the C) 100 | #maxTemperature = firebase.get("/Controls/Sensors/Temperature/max_inside", None) 101 | #maxTemperature = maxTemperature[:-1] 102 | 103 | #minTemperature = firebase.get("/Controls/Sensors/Temperature/min_inside", None) 104 | #minTemperature = minTemperature[:-1] 105 | 106 | #add current value 107 | #humidity, temperature = readDHT22() 108 | #firebase.put("/Controls/Sensors", "/Humidity/current_inside", ""+humidity+"%") 109 | #firebase.put("/Controls/Sensors", "/Temperature/current_inside", ""+temperature+"C") 110 | 111 | ##check for max values 112 | #if float(humidity) > float(maxHumidity): 113 | # firebase.put("/Controls/Sensors", "/Humidity/max_inside", ""+humidity+"%") 114 | # printlog("Updated Humidity max_inside") 115 | #if float(temperature) > float(maxTemperature): 116 | # firebase.put("/Controls/Sensors", "/Temperature/max_inside", ""+temperature+"C") 117 | # printlog("Updated Temperature max_inside") 118 | 119 | ## check for min values 120 | #if float(humidity) < float(minHumidity): 121 | # firebase.put("/Controls/Sensors", "/Humidity/min_inside", ""+humidity+"%") 122 | # printlog("Updated Humidity min_inside") 123 | #if float(temperature) < float(minTemperature): 124 | # firebase.put("/Controls/Sensors", "/Temperature/min_inside", ""+temperature+"C") 125 | # printlog("Updated Temperature min_inside") 126 | 127 | #CPU INFO 128 | CPU_temp = getCPUtemperature() 129 | CPU_usage = getCPUuse() 130 | firebase.put("/PI/CPU", "/temperature", CPU_temp) 131 | printlog("CPU Temp "+CPU_temp) 132 | 133 | #RAM INFO 134 | RAM_stats = getRAMinfo() 135 | RAM_total = round(int(RAM_stats[0]) / 1000,1) 136 | RAM_used = round(int(RAM_stats[1]) / 1000,1) 137 | RAM_free = round(int(RAM_stats[2]) / 1000,1) 138 | firebase.put("/PI/RAM", "/free", str(RAM_free)+"") 139 | firebase.put("/PI/RAM", "/used", str(RAM_used)+"") 140 | firebase.put("/PI/RAM", "/total", str(RAM_total)+"") 141 | 142 | #DISK INFO 143 | DISK_stats = getDiskSpace() 144 | DISK_total = DISK_stats[0] 145 | DISK_free = DISK_stats[1] 146 | DISK_perc = DISK_stats[3] 147 | DISK_used = float(DISK_total[:-1]) - float(DISK_free[:-1]) 148 | firebase.put("/PI/DISK", "/total", str(DISK_total[:-1])) 149 | firebase.put("/PI/DISK", "/free", str(DISK_free[:-1])) 150 | firebase.put("/PI/DISK", "/used", str(DISK_used)) 151 | firebase.put("/PI/DISK", "/percentage", str(DISK_perc)) 152 | 153 | 154 | printlog(datetime.datetime.now().strftime(dateString)) 155 | #printlog("Humidity: Current["+humidity+"], Max["+maxHumidity+"], Min["+minHumidity+"]") 156 | #printlog("Temperature: Current["+temperature+"], Max["+maxTemperature+"], Min["+minTemperature+"]") 157 | printlog("CPU temperature: "+CPU_temp) 158 | printlog("RAM total["+str(RAM_total)+" MB], RAM used["+str(RAM_used)+" MB], RAM free["+str(RAM_free)+" MB]") 159 | printlog("DISK total["+str(DISK_total)+"], free["+str(DISK_free)+"], perc["+str(DISK_perc)+"]") 160 | printlog("## Update finished successfully ##") 161 | printlog("======================================================\n") 162 | 163 | 164 | 165 | 166 | # ============================================================================================ 167 | # GPIO CALLBACKS FOR PHYSICAL BUTTONS 168 | GPIO.setmode(GPIO.BOARD) 169 | 170 | switch_number_key = 'switch_number' 171 | pin_number_key = 'pin_number' 172 | 173 | def toggleControlChild(name, pin_number, control_type, channel): 174 | # First switch on/off the light in relation of the gpio state 175 | GPIO.setup(pin_number, GPIO.OUT) 176 | value = GPIO.input(pin_number) 177 | newValue = int(not value) 178 | GPIO.output(pin_number, newValue) 179 | 180 | # Then update firebase with the new state 181 | firebase.put("/Controls/"+control_type+"/"+name, "/value", newValue) 182 | 183 | 184 | 185 | # Fetch firebase switch data 186 | controls = firebase.get('/Controls', None) 187 | 188 | #for cat_name, cat_value in controls.items(): 189 | # for control_name, control_value in cat_value.items(): 190 | # if control_value.get(switch_number_key) != None or control_value.get(switch_number_key) is not None: 191 | # # Set up IN gpio pin for switch 192 | # switch_number = control_value.get(switch_number_key) 193 | # GPIO.setup(switch_number, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 194 | # # register callback for each switch retrieved 195 | # GPIO.add_event_detect(switch_number, GPIO.BOTH, callback=partial(toggleControlChild, control_name, control_value.get(pin_number_key), cat_name), bouncetime=1000) 196 | 197 | 198 | while True: 199 | try: 200 | updatePiInfo() 201 | print("") 202 | 203 | #Retrieve sleep time from firebase and continue the loop 204 | sleepTime = firebase.get("/Settings/info_update_time_interval", None) 205 | sleepTime = int(sleepTime) 206 | sleep(sleepTime) 207 | except: 208 | continue 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | -------------------------------------------------------------------------------- /dht-firebase-oled.py: -------------------------------------------------------------------------------- 1 | 2 | import RPi.GPIO as GPIO 3 | from time import sleep 4 | import datetime 5 | from firebase import firebase 6 | import Adafruit_GPIO.SPI as SPI 7 | import Adafruit_SSD1306 8 | import Adafruit_DHT 9 | 10 | from PIL import Image 11 | from PIL import ImageDraw 12 | from PIL import ImageFont 13 | 14 | import urllib2, urllib, httplib 15 | import json 16 | import os 17 | from functools import partial 18 | 19 | GPIO.setmode(GPIO.BCM) 20 | GPIO.cleanup() 21 | GPIO.setwarnings(False) 22 | 23 | # Sensor should be set to Adafruit_DHT.DHT11, 24 | # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. 25 | sensor = Adafruit_DHT.DHT11 26 | 27 | # Example using a Beaglebone Black with DHT sensor 28 | # connected to pin P8_11. 29 | pin = 4 30 | 31 | 32 | # Try to grab a sensor reading. Use the read_retry method which will retry up 33 | # to 15 times to get a sensor reading (waiting 2 seconds between each retry). 34 | humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) 35 | 36 | 37 | firebase = firebase.FirebaseApplication('https://YOUR_FIREBASE_URL.firebaseio.com/', None) 38 | 39 | 40 | # Raspberry Pi pin configuration: 41 | RST = 24 42 | # Note the following are only used with SPI: 43 | DC = 23 44 | SPI_PORT = 0 45 | SPI_DEVICE = 0 46 | 47 | # Note you can change the I2C address by passing an i2c_address parameter like: 48 | # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) 49 | disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) 50 | 51 | 52 | # Initialize library. 53 | disp.begin() 54 | 55 | # Clear display. 56 | disp.clear() 57 | disp.display() 58 | 59 | # Create blank image for drawing. 60 | # Make sure to create image with mode '1' for 1-bit color. 61 | width = disp.width 62 | height = disp.height 63 | image = Image.new('1', (width, height)) 64 | 65 | # Get drawing object to draw on image. 66 | draw = ImageDraw.Draw(image) 67 | 68 | # Draw a black filled box to clear the image. 69 | draw.rectangle((0,0,width,height), outline=0, fill=0) 70 | 71 | # Draw some shapes. 72 | # First define some constants to allow easy resizing of shapes. 73 | padding = 2 74 | shape_width = 20 75 | top = padding 76 | bottom = height-padding 77 | # Move left to right keeping track of the current x position for drawing shapes. 78 | x = padding 79 | 80 | 81 | # Load default font. 82 | font = ImageFont.load_default() 83 | font10 = ImageFont.truetype('Minecraftia.ttf', 10) 84 | font18 = ImageFont.truetype('Minecraftia.ttf', 18) 85 | font20 = ImageFont.truetype('Minecraftia.ttf', 20) 86 | font42 = ImageFont.truetype('Minecraftia.ttf', 42) 87 | 88 | # Write two lines of text. 89 | draw.text((x, top), 'Raspberry Pi', font=font, fill=255) 90 | draw.text((x, top+20), 'Firebase', font=font20, fill=255) 91 | 92 | # Display image. 93 | disp.image(image) 94 | disp.display() 95 | 96 | #firebase.put("/dht", "/temp", "0.00") 97 | #firebase.put("/dht", "/humidity", "0.00") 98 | 99 | def update_firebase(): 100 | 101 | humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) 102 | if humidity is not None and temperature is not None: 103 | sleep(5) 104 | str_temp = ' {0:0.2f} *C '.format(temperature) 105 | str_hum = ' {0:0.2f} %'.format(humidity) 106 | print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) 107 | draw.rectangle((0,0,width,height), outline=0, fill=0) 108 | #disp.clear() 109 | #disp.display() 110 | draw.text((3, top), 'Temperature/Humidity', font=font, fill=255) 111 | draw.text((x, top+16), str_temp, font=font18, fill=255) 112 | draw.text((x, top+36), str_hum, font=font18, fill=255) 113 | disp.image(image) 114 | disp.display() 115 | else: 116 | print('Failed to get reading. Try again!') 117 | sleep(10) 118 | 119 | data = {"temp": temperature, "humidity": humidity} 120 | firebase.post('/sensor/dht', data) 121 | 122 | 123 | while True: 124 | update_firebase() 125 | 126 | #sleepTime = int(sleepTime) 127 | sleep(5) 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /dht-firebase.py: -------------------------------------------------------------------------------- 1 | 2 | import RPi.GPIO as GPIO 3 | from time import sleep 4 | import datetime 5 | from firebase import firebase 6 | import Adafruit_DHT 7 | 8 | import urllib2, urllib, httplib 9 | import json 10 | import os 11 | from functools import partial 12 | 13 | GPIO.setmode(GPIO.BCM) 14 | GPIO.cleanup() 15 | GPIO.setwarnings(False) 16 | 17 | # Sensor should be set to Adafruit_DHT.DHT11, 18 | # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. 19 | sensor = Adafruit_DHT.DHT11 20 | 21 | # Example using a Beaglebone Black with DHT sensor 22 | # connected to pin P8_11. 23 | pin = 4 24 | 25 | # Try to grab a sensor reading. Use the read_retry method which will retry up 26 | # to 15 times to get a sensor reading (waiting 2 seconds between each retry). 27 | humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) 28 | 29 | 30 | firebase = firebase.FirebaseApplication('https://YOUR_FIREBASE_URL.firebaseio.com/', None) 31 | #firebase.put("/dht", "/temp", "0.00") 32 | #firebase.put("/dht", "/humidity", "0.00") 33 | 34 | def update_firebase(): 35 | 36 | humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) 37 | if humidity is not None and temperature is not None: 38 | sleep(5) 39 | str_temp = ' {0:0.2f} *C '.format(temperature) 40 | str_hum = ' {0:0.2f} %'.format(humidity) 41 | print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) 42 | 43 | else: 44 | print('Failed to get reading. Try again!') 45 | sleep(10) 46 | 47 | data = {"temp": temperature, "humidity": humidity} 48 | firebase.post('/sensor/dht', data) 49 | 50 | 51 | while True: 52 | update_firebase() 53 | 54 | #sleepTime = int(sleepTime) 55 | sleep(5) 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /fire.py: -------------------------------------------------------------------------------- 1 | 2 | import RPi.GPIO as GPIO 3 | from time import sleep 4 | import datetime 5 | from firebase import firebase 6 | import Adafruit_GPIO.SPI as SPI 7 | import Adafruit_SSD1306 8 | 9 | from PIL import Image 10 | from PIL import ImageDraw 11 | from PIL import ImageFont 12 | 13 | import urllib2, urllib, httplib 14 | import json 15 | import os 16 | from functools import partial 17 | 18 | GPIO.setmode(GPIO.BCM) 19 | GPIO.cleanup() 20 | GPIO.setwarnings(False) 21 | GPIO.setup(18,GPIO.OUT) 22 | 23 | firebase = firebase.FirebaseApplication('https://YOUR-FIREBASE-URL.firebaseio.com', None) 24 | #firebase.put("/Control", "/device1", "on") 25 | 26 | def updatePiInfo(): 27 | result = firebase.get('/Control', '/device1') 28 | print result 29 | 30 | if ( result == "on" ): 31 | #disp.clear() 32 | #disp.display() 33 | draw.rectangle((0,0,width,height), outline=0, fill=0) 34 | draw.text((x, top), ' FireBase', font=font, fill=255) 35 | draw.text((x+20, top+16), ' ON', font=font42, fill=255) 36 | disp.image(image) 37 | disp.display() 38 | print "Lights on" 39 | GPIO.output(18,GPIO.HIGH) 40 | else : 41 | if ( result == "off" ): 42 | print "Lights off" 43 | GPIO.output(18,GPIO.LOW) 44 | draw.rectangle((0,0,width,height), outline=0, fill=0) 45 | #disp.clear() 46 | #disp.display() 47 | draw.text((x, top), ' FireBase', font=font, fill=255) 48 | draw.text((x, top+16), ' OFF', font=font42, fill=255) 49 | disp.image(image) 50 | disp.display() 51 | 52 | 53 | # Raspberry Pi pin configuration: 54 | RST = 24 55 | # Note the following are only used with SPI: 56 | DC = 23 57 | SPI_PORT = 0 58 | SPI_DEVICE = 0 59 | 60 | # Note you can change the I2C address by passing an i2c_address parameter like: 61 | # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) 62 | disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) 63 | 64 | 65 | # Initialize library. 66 | disp.begin() 67 | 68 | # Clear display. 69 | disp.clear() 70 | disp.display() 71 | 72 | # Create blank image for drawing. 73 | # Make sure to create image with mode '1' for 1-bit color. 74 | width = disp.width 75 | height = disp.height 76 | image = Image.new('1', (width, height)) 77 | 78 | # Get drawing object to draw on image. 79 | draw = ImageDraw.Draw(image) 80 | 81 | # Draw a black filled box to clear the image. 82 | draw.rectangle((0,0,width,height), outline=0, fill=0) 83 | 84 | # Draw some shapes. 85 | # First define some constants to allow easy resizing of shapes. 86 | padding = 2 87 | shape_width = 20 88 | top = padding 89 | bottom = height-padding 90 | # Move left to right keeping track of the current x position for drawing shapes. 91 | x = padding 92 | 93 | 94 | # Load default font. 95 | font = ImageFont.load_default() 96 | font10 = ImageFont.truetype('Minecraftia.ttf', 10) 97 | font20 = ImageFont.truetype('Minecraftia.ttf', 20) 98 | font42 = ImageFont.truetype('Minecraftia.ttf', 42) 99 | 100 | # Write two lines of text. 101 | draw.text((x, top), ' FireBase', font=font, fill=255) 102 | draw.text((x, top+20), 'CONTROL', font=font20, fill=255) 103 | 104 | # Display image. 105 | disp.image(image) 106 | disp.display() 107 | 108 | #firebase.post("/Control/device1", "off") 109 | firebase.put("/Control", "/device1", "off") 110 | 111 | while True: 112 | updatePiInfo() 113 | #firebase.put("/Control", "/device1", "off") 114 | 115 | #Retrieve sleep time from firebase and continue the loop 116 | #sleepTime = firebase.get("/Settings/info_update_time_interval", None) 117 | #sleepTime = int(sleepTime) 118 | sleep(1) 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | --------------------------------------------------------------------------------