All WIP scripts code from RPI + Release Linux

This commit is contained in:
ThomasFransolet 2019-04-14 02:05:57 +02:00
parent 6370257154
commit cea158fec1
54 changed files with 23454 additions and 10 deletions

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<!--
IIS configuration sections.
@ -151,7 +151,7 @@
<virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
</application>
<bindings>
<binding protocol="http" bindingInformation=":8080:localhost" />
<binding protocol="http" bindingInformation="*:8080:localhost" />
</bindings>
</site>
<site name="MyCore" id="2">
@ -160,7 +160,14 @@
</application>
<bindings>
<binding protocol="http" bindingInformation="*:25049:localhost" />
<binding protocol="https" bindingInformation="*:44395:localhost" />
</bindings>
</site>
<site name="MyCore(1)" id="3">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:25049:localhost" />
</bindings>
</site>
<siteDefaults>
@ -980,12 +987,19 @@
</location>
<location path="MyCore">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true" />
<windowsAuthentication enabled="false" />
</authentication>
</security>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600" requestTimeout="23:00:00" />
<httpCompression>
<dynamicTypes>
<add mimeType="text/event-stream" enabled="false" />
</dynamicTypes>
</httpCompression>
</system.webServer>
</location>
<location path="MyCore(1)">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>

View File

@ -4,7 +4,7 @@
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:25049",
"sslPort": 44395
"sslPort": 0
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
@ -14,6 +14,7 @@
"launchBrowser": true,
"launchUrl": "api/test",
"environmentVariables": {
"ASPNETCORE_URLS": "http://*:5000/",
"ASPNETCORE_ENVIRONMENT": "Development"
}
},

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
{
"runtimeOptions": {
"additionalProbingPaths": [
"C:\\Users\\thoma\\.dotnet\\store\\|arch|\\|tfm|",
"C:\\Users\\thoma\\.nuget\\packages",
"C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder"
]
}
}

View File

@ -0,0 +1,7 @@
{
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
}
}

View File

@ -0,0 +1,29 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>MyCore</name>
</assembly>
<members>
<member name="M:MyCore.Controllers.IOTController.Get(System.Int32)">
<summary>
Retrieve all SmartPrinterMessage
</summary>
</member>
<member name="M:MyCore.Controllers.IOTController.PostToDB(System.Int32,MyCore.Models.SmartPrinterMessage[])">
<summary>
It's the method to post data from mqtt broker to Database (Thanks Rpi!)
</summary>
</member>
<member name="M:MyCore.Controllers.MQTTController.GetToPublishMqtt">
<summary>
It's a mqtt publish test ! :)
</summary>
</member>
<member name="M:MyCore.Controllers.ValuesController.Get">
<summary>
It's a test ! :)
</summary>
<param name="id">id test</param>
</member>
</members>
</doc>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
{
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
}
}

View File

@ -0,0 +1,29 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>MyCore</name>
</assembly>
<members>
<member name="M:MyCore.Controllers.IOTController.Get(System.Int32)">
<summary>
Retrieve all SmartPrinterMessage
</summary>
</member>
<member name="M:MyCore.Controllers.IOTController.PostToDB(System.Int32,MyCore.Models.SmartPrinterMessage[])">
<summary>
It's the method to post data from mqtt broker to Database (Thanks Rpi!)
</summary>
</member>
<member name="M:MyCore.Controllers.MQTTController.GetToPublishMqtt">
<summary>
It's a mqtt publish test ! :)
</summary>
</member>
<member name="M:MyCore.Controllers.ValuesController.Get">
<summary>
It's a test ! :)
</summary>
<param name="id">id test</param>
</member>
</members>
</doc>

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@ -0,0 +1,19 @@
{
"ConnectionStrings": {
"BookstoreDb": "mongodb://localhost:27017",
"MyCoreDb": "mongodb://localhost:27017"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"SecuritySettings": {
"Secret": "azertyuiopqsdfgh",
"Issuer": "MyCore",
"Audience": "the client of your app",
"IdType": "Name",
"TokenExpiryInHours": 2
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\MyCore" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</location>
</configuration>
<!--ProjectGuid: 017065F0-FC61-4566-A432-F414FC217AAA-->

View File

@ -0,0 +1,16 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Généré par la classe MSBuild WriteCodeFragment.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("MyCore")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("MyCore")]
[assembly: System.Reflection.AssemblyTitleAttribute("MyCore")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

View File

@ -0,0 +1,13 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Généré par la classe MSBuild WriteCodeFragment.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("MyCore.Views")]
[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute("2.1")]
[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute("MVC-2.1")]
[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute("MVC-2.1", "Microsoft.AspNetCore.Mvc.Razor.Extensions")]

View File

@ -0,0 +1,20 @@
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\libhostpolicy.so
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\libhostfxr.so
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\MyCore
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\MyCore.deps.json
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\MyCore.runtimeconfig.json
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\MyCore.runtimeconfig.dev.json
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\MyCore.dll
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\MyCore.pdb
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\bin\Release\netcoreapp2.1\linux-arm\MyCore.xml
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.csprojAssemblyReference.cache
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.csproj.CoreCompileInputs.cache
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.RazorAssemblyInfo.cache
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.RazorAssemblyInfo.cs
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\UserSecretsAssemblyInfo.cs
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.AssemblyInfoInputs.cache
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.AssemblyInfo.cs
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.RazorTargetAssemblyInfo.cache
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.dll
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.xml
C:\Users\thoma\OneDrive\Documents\Travail\MyCore\MyCore\obj\Release\netcoreapp2.1\linux-arm\MyCore.pdb

View File

@ -0,0 +1,29 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>MyCore</name>
</assembly>
<members>
<member name="M:MyCore.Controllers.IOTController.Get(System.Int32)">
<summary>
Retrieve all SmartPrinterMessage
</summary>
</member>
<member name="M:MyCore.Controllers.IOTController.PostToDB(System.Int32,MyCore.Models.SmartPrinterMessage[])">
<summary>
It's the method to post data from mqtt broker to Database (Thanks Rpi!)
</summary>
</member>
<member name="M:MyCore.Controllers.MQTTController.GetToPublishMqtt">
<summary>
It's a mqtt publish test ! :)
</summary>
</member>
<member name="M:MyCore.Controllers.ValuesController.Get">
<summary>
It's a test ! :)
</summary>
<param name="id">id test</param>
</member>
</members>
</doc>

View File

@ -0,0 +1,10 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Généré par la classe MSBuild WriteCodeFragment.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute("6d53b0c4-74d6-41aa-8816-2ec3cf42767a")]

Binary file not shown.

172
RPI Code/BME280/bme280.py Normal file
View File

@ -0,0 +1,172 @@
#!/usr/bin/python
#--------------------------------------
# ___ ___ _ ____
# / _ \/ _ \(_) __/__ __ __
# / , _/ ___/ /\ \/ _ \/ // /
# /_/|_/_/ /_/___/ .__/\_, /
# /_/ /___/
#
# bme280.py
# Read data from a digital pressure sensor.
#
# Official datasheet available from :
# https://www.bosch-sensortec.com/bst/products/all_products/bme280
#
# Author : Matt Hawkins
# Date : 25/07/2016
#
# http://www.raspberrypi-spy.co.uk/
#
#--------------------------------------
import smbus
import time
from ctypes import c_short
from ctypes import c_byte
from ctypes import c_ubyte
DEVICE = 0x76 # Default device I2C address
bus = smbus.SMBus(1) # Rev 2 Pi, Pi 2 & Pi 3 uses bus 1
# Rev 1 Pi uses bus 0
def getShort(data, index):
# return two bytes from data as a signed 16-bit value
return c_short((data[index+1] << 8) + data[index]).value
def getUShort(data, index):
# return two bytes from data as an unsigned 16-bit value
return (data[index+1] << 8) + data[index]
def getChar(data,index):
# return one byte from data as a signed char
result = data[index]
if result > 127:
result -= 256
return result
def getUChar(data,index):
# return one byte from data as an unsigned char
result = data[index] & 0xFF
return result
def readBME280ID(addr=DEVICE):
# Chip ID Register Address
REG_ID = 0xD0
(chip_id, chip_version) = bus.read_i2c_block_data(addr, REG_ID, 2)
return (chip_id, chip_version)
def readBME280All(addr=DEVICE):
# Register Addresses
REG_DATA = 0xF7
REG_CONTROL = 0xF4
REG_CONFIG = 0xF5
REG_CONTROL_HUM = 0xF2
REG_HUM_MSB = 0xFD
REG_HUM_LSB = 0xFE
# Oversample setting - page 27
OVERSAMPLE_TEMP = 2
OVERSAMPLE_PRES = 2
MODE = 1
# Oversample setting for humidity register - page 26
OVERSAMPLE_HUM = 2
bus.write_byte_data(addr, REG_CONTROL_HUM, OVERSAMPLE_HUM)
control = OVERSAMPLE_TEMP<<5 | OVERSAMPLE_PRES<<2 | MODE
bus.write_byte_data(addr, REG_CONTROL, control)
# Read blocks of calibration data from EEPROM
# See Page 22 data sheet
cal1 = bus.read_i2c_block_data(addr, 0x88, 24)
cal2 = bus.read_i2c_block_data(addr, 0xA1, 1)
cal3 = bus.read_i2c_block_data(addr, 0xE1, 7)
# Convert byte data to word values
dig_T1 = getUShort(cal1, 0)
dig_T2 = getShort(cal1, 2)
dig_T3 = getShort(cal1, 4)
dig_P1 = getUShort(cal1, 6)
dig_P2 = getShort(cal1, 8)
dig_P3 = getShort(cal1, 10)
dig_P4 = getShort(cal1, 12)
dig_P5 = getShort(cal1, 14)
dig_P6 = getShort(cal1, 16)
dig_P7 = getShort(cal1, 18)
dig_P8 = getShort(cal1, 20)
dig_P9 = getShort(cal1, 22)
dig_H1 = getUChar(cal2, 0)
dig_H2 = getShort(cal3, 0)
dig_H3 = getUChar(cal3, 2)
dig_H4 = getChar(cal3, 3)
dig_H4 = (dig_H4 << 24) >> 20
dig_H4 = dig_H4 | (getChar(cal3, 4) & 0x0F)
dig_H5 = getChar(cal3, 5)
dig_H5 = (dig_H5 << 24) >> 20
dig_H5 = dig_H5 | (getUChar(cal3, 4) >> 4 & 0x0F)
dig_H6 = getChar(cal3, 6)
# Wait in ms (Datasheet Appendix B: Measurement time and current calculation)
wait_time = 1.25 + (2.3 * OVERSAMPLE_TEMP) + ((2.3 * OVERSAMPLE_PRES) + 0.575) + ((2.3 * OVERSAMPLE_HUM)+0.575)
time.sleep(wait_time/1000) # Wait the required time
# Read temperature/pressure/humidity
data = bus.read_i2c_block_data(addr, REG_DATA, 8)
pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)
temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)
hum_raw = (data[6] << 8) | data[7]
#Refine temperature
var1 = ((((temp_raw>>3)-(dig_T1<<1)))*(dig_T2)) >> 11
var2 = (((((temp_raw>>4) - (dig_T1)) * ((temp_raw>>4) - (dig_T1))) >> 12) * (dig_T3)) >> 14
t_fine = var1+var2
temperature = float(((t_fine * 5) + 128) >> 8);
# Refine pressure and adjust for temperature
var1 = t_fine / 2.0 - 64000.0
var2 = var1 * var1 * dig_P6 / 32768.0
var2 = var2 + var1 * dig_P5 * 2.0
var2 = var2 / 4.0 + dig_P4 * 65536.0
var1 = (dig_P3 * var1 * var1 / 524288.0 + dig_P2 * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * dig_P1
if var1 == 0:
pressure=0
else:
pressure = 1048576.0 - pres_raw
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = dig_P9 * pressure * pressure / 2147483648.0
var2 = pressure * dig_P8 / 32768.0
pressure = pressure + (var1 + var2 + dig_P7) / 16.0
# Refine humidity
humidity = t_fine - 76800.0
humidity = (hum_raw - (dig_H4 * 64.0 + dig_H5 / 16384.0 * humidity)) * (dig_H2 / 65536.0 * (1.0 + dig_H6 / 67108864.0 * humidity * (1.0 + dig_H3 / 67108864.0 * humidity)))
humidity = humidity * (1.0 - dig_H1 * humidity / 524288.0)
if humidity > 100:
humidity = 100
elif humidity < 0:
humidity = 0
return temperature/100.0,pressure/100.0,humidity
def main():
(chip_id, chip_version) = readBME280ID()
print ("Chip ID :", chip_id)
print ("Version :", chip_version)
temperature,pressure,humidity = readBME280All()
print ("Temperature : ", temperature, "C")
print ("Pressure : ", pressure, "hPa")
print ("Humidity : ", humidity, "%")
if __name__=="__main__":
main()

View File

@ -0,0 +1,5 @@
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN)
print GPIO.input(4)

View File

@ -0,0 +1,82 @@
#!/usr/bin/env python
import requests
import signal
import time
import json
import paho.mqtt.client as mqtt
broker="localhost"
#username="oilkfgjy"
#password="lEyZb90q49Rf"
# defining the api-endpoint
API_ENDPOINT = 'http://192.168.0.17:3000/api/iot/0'
delay = 5000
mqttc = mqtt.Client('Mqtt_To_Http_Interceptor')
#mqttc.username_pw_set(username, password)
mqttc.connect(broker, 1883)
TOKEN_URL = 'http://192.168.0.17:3000/api/token?username=Thomas&password=MonsieurMagic'
r = requests.post(TOKEN_URL)
if r.status_code == 200 :
token = r.text
print('we have a token!')
hed = {'Authorization': "Bearer " + token +"f", 'Content-Type': "application/json"}
print(hed)
def on_message(mosq, obj, msg):
print(msg.topic)
if msg.topic == '3DPrinterSensors' :
print(str(msg.payload, "utf-8"))
print(API_ENDPOINT)
# Add increment and test = if data length >= 10, push to DB via Http
# Add Verification on token.. if status code == 401 forbidden then get token and call again the service
jsonData = json.dumps([{'Time': '14/04/19', 'Temperature': 26.5, 'Pressure': 1004.3, 'Smoke': 100}])
anotherR = requests.post(API_ENDPOINT,data=jsonData, headers=hed)
print (anotherR.text)
print(anotherR.status_code)
# Extracting data in json format
#data = r.json()
elif msg.topic == 'SmartGarden' :
print(str(msg.payload, "utf-8"))
# data to be sent to api
data = {'api_dev_key':'',
'api_option':'paste',
'api_paste_code':source_code,
'api_paste_format':'python'}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)
else:
print("Unknown topic")
mqttc.on_message=on_message
#####
print("connecting to broker ",broker)
mqttc.loop_start() #start loop to process received messages
print("subscribing ")
mqttc.subscribe("SmartGarden")#subscribe
mqttc.subscribe("3DPrinterSensors")#subscribe
signal.pause()
mqttc.loop_forever()

View File

@ -0,0 +1,53 @@
# Simple demo of reading each analog input from the ADS1x15 and printing it to
# the screen.
# Author: Tony DiCola
# License: Public Domain
import time
# Import the ADS1x15 module.
import Adafruit_ADS1x15
# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()
# Or create an ADS1015 ADC (12-bit) instance.
#adc = Adafruit_ADS1x15.ADS1015()
# Note you can change the I2C address from its default (0x48), and/or the I2C
# bus by passing in these optional parameters:
#adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1)
# Choose a gain of 1 for reading voltages from 0 to 4.09V.
# Or pick a different gain to change the range of voltages that are read:
# - 2/3 = +/-6.144V
# - 1 = +/-4.096V
# - 2 = +/-2.048V
# - 4 = +/-1.024V
# - 8 = +/-0.512V
# - 16 = +/-0.256V
# See table 3 in the ADS1015/ADS1115 datasheet for more info on gain.
GAIN = 1
print('Reading ADS1x15 values, press Ctrl-C to quit...')
# Print nice channel column headers.
print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} |'.format(*range(4)))
print('-' * 37)
# Main loop.
while True:
# Read all the ADC channel values in a list.
values = [0]*4
for i in range(4):
# Read the specified ADC channel using the previously set gain value.
values[i] = adc.read_adc(i, gain=GAIN)
# Note you can also pass in an optional data_rate parameter that controls
# the ADC conversion time (in samples/second). Each chip has a different
# set of allowed data rate values, see datasheet Table 9 config register
# DR bit values.
#values[i] = adc.read_adc(i, gain=GAIN, data_rate=128)
# Each value will be a 12 or 16 bit signed integer value depending on the
# ADC (ADS1015 = 12-bit, ADS1115 = 16-bit).
# Print the ADC values.
print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} |'.format(*values))
# Pause for half a second.
time.sleep(0.5)

View File

@ -0,0 +1,38 @@
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) # GPIO Numbers instead of board numbers
RELAIS_1_GPIO = 27
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT) # GPIO Assign mode
# here you would put all your code for setting up GPIO,
# we'll cover that tomorrow
# initial values of variables etc...
counter = 0
try:
# here you put your main loop or block of code
while True:
# count up to 9000000 - takes ~20s
time.sleep(3)
print ("Hellooooo")
if counter % 2 ==0:
GPIO.output(RELAIS_1_GPIO, GPIO.LOW) # out
else:
GPIO.output(RELAIS_1_GPIO, GPIO.HIGH) # out
counter += 1
print ("Target reached: %d" % counter)
except KeyboardInterrupt:
# here you put any code you want to run before the program
# exits when you press CTRL+C
print ("\n", counter) # print value of counter
except:
# this catches ALL other exceptions including errors.
# You won't get any error messages for debugging
# so only use it once your code is working
print ("Other error or exception occurred!")
finally:
GPIO.cleanup() # this ensures a clean exit

View File

@ -0,0 +1,261 @@
import smbus
import time
import json
from ctypes import c_short
from ctypes import c_byte
from ctypes import c_ubyte
import paho.mqtt.client as mqtt
import socket
broker="localhost"
#username="oilkfgjy"
#password="lEyZb90q49Rf"
mqttc = mqtt.Client("SmartGarden_PiZero")
#mqttc.username_pw_set(username, password)
DEVICE = 0x76 # Default device I2C address
bus = smbus.SMBus(1) # Rev 2 Pi, Pi 2 & Pi 3ses bus 1
# Rev 1 Pi uses bus 0
def get_ip_address():
ip_address = '';
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8",80))
ip_address = s.getsockname()[0]
s.close()
return ip_address
def getShort(data, index):
# return two bytes from data as a signed 16-bit value
return c_short((data[index+1] << 8) + data[index]).value
def getUShort(data, index):
# return two bytes from data as an unsigned 16-bit value
return (data[index+1] << 8) + data[index]
def getChar(data,index):
# return one byte from data as a signed char
result = data[index]
if result > 127:
result -= 256
return result
def getUChar(data,index):
# return one byte from data as an unsigned char
result = data[index] & 0xFF
return result
def readBME280ID(addr=DEVICE):
# Chip ID Register Address
REG_ID = 0xD0
(chip_id, chip_version) = bus.read_i2c_block_data(addr, REG_ID, 2)
return (chip_id, chip_version)
def readBME280All(addr=DEVICE):
# Register Addresses
REG_DATA = 0xF7
REG_CONTROL = 0xF4
REG_CONFIG = 0xF5
REG_CONTROL_HUM = 0xF2
REG_HUM_MSB = 0xFD
REG_HUM_LSB = 0xFE
# Oversample setting - page 27
OVERSAMPLE_TEMP = 2
OVERSAMPLE_PRES = 2
MODE = 1
# Oversample setting for humidity register - page 26
OVERSAMPLE_HUM = 2
bus.write_byte_data(addr, REG_CONTROL_HUM, OVERSAMPLE_HUM)
control = OVERSAMPLE_TEMP<<5 | OVERSAMPLE_PRES<<2 | MODE
bus.write_byte_data(addr, REG_CONTROL, control)
# Read blocks of calibration data from EEPROM
# See Page 22 data sheet
cal1 = bus.read_i2c_block_data(addr, 0x88, 24)
cal2 = bus.read_i2c_block_data(addr, 0xA1, 1)
cal3 = bus.read_i2c_block_data(addr, 0xE1, 7)
# Convert byte data to word values
dig_T1 = getUShort(cal1, 0)
dig_T2 = getShort(cal1, 2)
dig_T3 = getShort(cal1, 4)
dig_P1 = getUShort(cal1, 6)
dig_P2 = getShort(cal1, 8)
dig_P3 = getShort(cal1, 10)
dig_P4 = getShort(cal1, 12)
dig_P5 = getShort(cal1, 14)
dig_P6 = getShort(cal1, 16)
dig_P7 = getShort(cal1, 18)
dig_P8 = getShort(cal1, 20)
dig_P9 = getShort(cal1, 22)
dig_H1 = getUChar(cal2, 0)
dig_H2 = getShort(cal3, 0)
dig_H3 = getUChar(cal3, 2)
dig_H4 = getChar(cal3, 3)
dig_H4 = (dig_H4 << 24) >> 20
dig_H4 = dig_H4 | (getChar(cal3, 4) & 0x0F)
dig_H5 = getChar(cal3, 5)
dig_H5 = (dig_H5 << 24) >> 20
dig_H5 = dig_H5 | (getUChar(cal3, 4) >> 4 & 0x0F)
dig_H6 = getChar(cal3, 6)
# Wait in ms (Datasheet Appendix B: Measurement time and current calculation)
wait_time = 1.25 + (2.3 * OVERSAMPLE_TEMP) + ((2.3 * OVERSAMPLE_PRES) + 0.575) + ((2.3 * OVERSAMPLE_HUM)+0.575)
time.sleep(wait_time/1000) # Wait the required time
# Read temperature/pressure/humidity
data = bus.read_i2c_block_data(addr, REG_DATA, 8)
pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)
temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)
hum_raw = (data[6] << 8) | data[7]
#Refine temperature
var1 = ((((temp_raw>>3)-(dig_T1<<1)))*(dig_T2)) >> 11
var2 = (((((temp_raw>>4) - (dig_T1)) * ((temp_raw>>4) - (dig_T1))) >> 12) * (dig_T3)) >> 14
t_fine = var1+var2
temperature = float(((t_fine * 5) + 128) >> 8);
# Refine pressure and adjust for temperature
var1 = t_fine / 2.0 - 64000.0
var2 = var1 * var1 * dig_P6 / 32768.0
var2 = var2 + var1 * dig_P5 * 2.0
var2 = var2 / 4.0 + dig_P4 * 65536.0
var1 = (dig_P3 * var1 * var1 / 524288.0 + dig_P2 * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * dig_P1
if var1 == 0:
pressure=0
else:
pressure = 1048576.0 - pres_raw
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = dig_P9 * pressure * pressure / 2147483648.0
var2 = pressure * dig_P8 / 32768.0
pressure = pressure + (var1 + var2 + dig_P7) / 16.0
# Refine humidity
humidity = t_fine - 76800.0
humidity = (hum_raw - (dig_H4 * 64.0 + dig_H5 / 16384.0 * humidity)) * (dig_H2 / 65536.0 * (1.0 + dig_H6 / 67108864.0 * humidity * (1.0 + dig_H3 / 67108864.0 * humidity)))
humidity = humidity * (1.0 - dig_H1 * humidity / 524288.0)
if humidity > 100:
humidity = 100
elif humidity < 0:
humidity = 0
return temperature/100.0,pressure/100.0,humidity
import time
# Import the ADS1x15 module.
import Adafruit_ADS1x15
import RPi.GPIO as GPIO
#################### HERE IS THE MAIN CODE ####################
# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()
# bus by passing in these optional parameters:
#adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1)
# Choose a gain of 1 for reading voltages from 0 to 4.09V.
GAIN = 1
# GPIO Numbers instead of board numbers
GPIO.setmode(GPIO.BCM)
#Set the relay pin to 27
RELAIS_1_GPIO = 27
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT) # GPIO Assign mode
GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
def on_message(mosq, obj, msg):
print(str(msg.payload, "utf-8"))
d = json.loads(str(msg.payload, "utf-8"))
print (d['Irrigate'])
if d['Irrigate'] >= 2 :
print('Im irrigating ! :)')
GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
time.sleep(int(d['Irrigate']))
GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
else:
print("uncorrect payload")
mqttc.connect(broker, 1883)
mqttc.publish("IpAddress", get_ip_address())
mqttc.on_message=on_message
mqttc.loop_start() #start loop to process received messages
mqttc.subscribe("SmartGarden_WaterRelay")#subscribe
print('Reading ADS1x15 values, press Ctrl-C to quit...')
# Print nice channel column headers.
print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} |'.format(*range(4)))
print('-' * 37)
try:
# Main loop.
while True:
# Read all the ADC channel values in a list.
values = [0]*4
for i in range(4):
# Read the specified ADC channel using the previously set gain value.
values[i] = adc.read_adc(i, gain=GAIN)
# Note you can also pass in an optional data_rate parameter that controls
# the ADC conversion time (in samples/second). Each chip has a different
# set of allowed data rate values, see datasheet Table 9 config register
# DR bit values.
#values[i] = adc.read_adc(i, gain=GAIN, data_rate=128)
# Each value will be a 12 or 16 bit signed integer value depending on the
# ADC (ADS1015 = 12-bit, ADS1115 = 16-bit).
# Print the ADC values.
#print ("values[0] : ", values[0])
#if values[0] < 15000 :
# print ("I'm in")
# GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
#else:
# print ("I'm in 2")
# GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
temperature,pressure,humidity = readBME280All()
print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} | '.format(*values), "Temperature : ", temperature, "C", " | Pressure : ", pressure, "hPa"," | Humidity : ", humidity, "%")
valuesToSend = '{"Temperature": ' + str(temperature) + ', "Pressure": '+ str(pressure) +', "Humidity": ' + str(humidity) + ', "Water": ' + str(values[0]) + ', "Light": ' + str(values[1]) + '}'
mqttc.publish("SmartGarden", valuesToSend)
#print ("Temperature : ", temperature, "C")
#print ("Pressure : ", pressure, "hPa")
#print ("Humidity : ", humidity, "%")
# Pause for ten seconds.
time.sleep(10)
except KeyboardInterrupt:
# here you put any code you want to run before the program
# exits when you press CTRL+C
print ("It's a KeyboardInterrupt")
GPIO.output(RELAIS_1_GPIO, GPIO.HIGH) #ensure that the pump is close
except:
# this catches ALL other exceptions including errors.
# You won't get any error messages for debugging
# so only use it once your code is working
print ("Other error or exception occurred!")
finally:
GPIO.output(RELAIS_1_GPIO, GPIO.HIGH) #ensure that the pump is close
GPIO.cleanup() # this ensures a clean exit

View File

@ -0,0 +1,172 @@
#!/usr/bin/python
#--------------------------------------
# ___ ___ _ ____
# / _ \/ _ \(_) __/__ __ __
# / , _/ ___/ /\ \/ _ \/ // /
# /_/|_/_/ /_/___/ .__/\_, /
# /_/ /___/
#
# bme280.py
# Read data from a digital pressure sensor.
#
# Official datasheet available from :
# https://www.bosch-sensortec.com/bst/products/all_products/bme280
#
# Author : Matt Hawkins
# Date : 25/07/2016
#
# http://www.raspberrypi-spy.co.uk/
#
#--------------------------------------
import smbus
import time
from ctypes import c_short
from ctypes import c_byte
from ctypes import c_ubyte
DEVICE = 0x76 # Default device I2C address
bus = smbus.SMBus(1) # Rev 2 Pi, Pi 2 & Pi 3 uses bus 1
# Rev 1 Pi uses bus 0
def getShort(data, index):
# return two bytes from data as a signed 16-bit value
return c_short((data[index+1] << 8) + data[index]).value
def getUShort(data, index):
# return two bytes from data as an unsigned 16-bit value
return (data[index+1] << 8) + data[index]
def getChar(data,index):
# return one byte from data as a signed char
result = data[index]
if result > 127:
result -= 256
return result
def getUChar(data,index):
# return one byte from data as an unsigned char
result = data[index] & 0xFF
return result
def readBME280ID(addr=DEVICE):
# Chip ID Register Address
REG_ID = 0xD0
(chip_id, chip_version) = bus.read_i2c_block_data(addr, REG_ID, 2)
return (chip_id, chip_version)
def readBME280All(addr=DEVICE):
# Register Addresses
REG_DATA = 0xF7
REG_CONTROL = 0xF4
REG_CONFIG = 0xF5
REG_CONTROL_HUM = 0xF2
REG_HUM_MSB = 0xFD
REG_HUM_LSB = 0xFE
# Oversample setting - page 27
OVERSAMPLE_TEMP = 2
OVERSAMPLE_PRES = 2
MODE = 1
# Oversample setting for humidity register - page 26
OVERSAMPLE_HUM = 2
bus.write_byte_data(addr, REG_CONTROL_HUM, OVERSAMPLE_HUM)
control = OVERSAMPLE_TEMP<<5 | OVERSAMPLE_PRES<<2 | MODE
bus.write_byte_data(addr, REG_CONTROL, control)
# Read blocks of calibration data from EEPROM
# See Page 22 data sheet
cal1 = bus.read_i2c_block_data(addr, 0x88, 24)
cal2 = bus.read_i2c_block_data(addr, 0xA1, 1)
cal3 = bus.read_i2c_block_data(addr, 0xE1, 7)
# Convert byte data to word values
dig_T1 = getUShort(cal1, 0)
dig_T2 = getShort(cal1, 2)
dig_T3 = getShort(cal1, 4)
dig_P1 = getUShort(cal1, 6)
dig_P2 = getShort(cal1, 8)
dig_P3 = getShort(cal1, 10)
dig_P4 = getShort(cal1, 12)
dig_P5 = getShort(cal1, 14)
dig_P6 = getShort(cal1, 16)
dig_P7 = getShort(cal1, 18)
dig_P8 = getShort(cal1, 20)
dig_P9 = getShort(cal1, 22)
dig_H1 = getUChar(cal2, 0)
dig_H2 = getShort(cal3, 0)
dig_H3 = getUChar(cal3, 2)
dig_H4 = getChar(cal3, 3)
dig_H4 = (dig_H4 << 24) >> 20
dig_H4 = dig_H4 | (getChar(cal3, 4) & 0x0F)
dig_H5 = getChar(cal3, 5)
dig_H5 = (dig_H5 << 24) >> 20
dig_H5 = dig_H5 | (getUChar(cal3, 4) >> 4 & 0x0F)
dig_H6 = getChar(cal3, 6)
# Wait in ms (Datasheet Appendix B: Measurement time and current calculation)
wait_time = 1.25 + (2.3 * OVERSAMPLE_TEMP) + ((2.3 * OVERSAMPLE_PRES) + 0.575) + ((2.3 * OVERSAMPLE_HUM)+0.575)
time.sleep(wait_time/1000) # Wait the required time
# Read temperature/pressure/humidity
data = bus.read_i2c_block_data(addr, REG_DATA, 8)
pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)
temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)
hum_raw = (data[6] << 8) | data[7]
#Refine temperature
var1 = ((((temp_raw>>3)-(dig_T1<<1)))*(dig_T2)) >> 11
var2 = (((((temp_raw>>4) - (dig_T1)) * ((temp_raw>>4) - (dig_T1))) >> 12) * (dig_T3)) >> 14
t_fine = var1+var2
temperature = float(((t_fine * 5) + 128) >> 8);
# Refine pressure and adjust for temperature
var1 = t_fine / 2.0 - 64000.0
var2 = var1 * var1 * dig_P6 / 32768.0
var2 = var2 + var1 * dig_P5 * 2.0
var2 = var2 / 4.0 + dig_P4 * 65536.0
var1 = (dig_P3 * var1 * var1 / 524288.0 + dig_P2 * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * dig_P1
if var1 == 0:
pressure=0
else:
pressure = 1048576.0 - pres_raw
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = dig_P9 * pressure * pressure / 2147483648.0
var2 = pressure * dig_P8 / 32768.0
pressure = pressure + (var1 + var2 + dig_P7) / 16.0
# Refine humidity
humidity = t_fine - 76800.0
humidity = (hum_raw - (dig_H4 * 64.0 + dig_H5 / 16384.0 * humidity)) * (dig_H2 / 65536.0 * (1.0 + dig_H6 / 67108864.0 * humidity * (1.0 + dig_H3 / 67108864.0 * humidity)))
humidity = humidity * (1.0 - dig_H1 * humidity / 524288.0)
if humidity > 100:
humidity = 100
elif humidity < 0:
humidity = 0
return temperature/100.0,pressure/100.0,humidity
def main():
(chip_id, chip_version) = readBME280ID()
print ("Chip ID :", chip_id)
print ("Version :", chip_version)
temperature,pressure,humidity = readBME280All()
print ("Temperature : ", temperature, "C")
print ("Pressure : ", pressure, "hPa")
print ("Humidity : ", humidity, "%")
if __name__=="__main__":
main()