Commit 6cba8116 authored by Daniel Kolibár's avatar Daniel Kolibár
Browse files

aaaaaaaaaaaaaaaaa

parent d23e157a
from machine import Pin
from time import sleep
import dht
import uasyncio
import network
import ubinascii
from umqtt.robust import MQTTClient
dht_sensor = dht.DHT11(Pin(14))
pir = Pin(13, Pin.IN)
mqtt_client = None
wlan = None
def connectToNetwork(ssid, password):
global wlan
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to wlan network: %s' %ssid)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print('connected! network config:', wlan.ifconfig())
def on_message(topic, message):
print(message)
def connectToMQTT():
global mqtt_client
SSL_PARAMS = {'server_hostname': '50ffbd7e701c480ca097875a1621692c.s1.eu.hivemq.cloud'}
mqtt_client = MQTTClient(
client_id = 'birdie_house_' + ubinascii.hexlify(network.WLAN().config('mac'),'_').decode(),
server = '50ffbd7e701c480ca097875a1621692c.s1.eu.hivemq.cloud',
port = 8883,
keepalive = 30,
ssl=True,
user='birdie',
password='tjhpnHMQb2021',
ssl_params=SSL_PARAMS
)
mqtt_client.connect()
async def readTemperatrue():
while True:
try:
await uasyncio.sleep(2)
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
print('Temperature: %3.1f C; ' %temp, 'Humidity: %3.1f %%' %hum)
except OSError as e:
print('Failed to read from DHT11 sensor: %s' %e)
async def detectMotion():
while True:
await uasyncio.sleep(1)
if pir.value():
mqtt_client.publish('birdie/rxtx/raspberry', 'TAKE_PHOTO')
await uasyncio.sleep_ms(40)
while pir.value():
pass
await uasyncio.sleep_ms(40)
else:
print('No motion detected!')
connectToNetwork("wifi-lab", "12345wifilabhouse54321")
connectToMQTT()
event_loop = uasyncio.get_event_loop()
event_loop.create_task(readTemperatrue())
event_loop.create_task(detectMotion())
event_loop.run_forever()
from machine import Pin
from time import sleep
import dht
import uasyncio
import network
import ubinascii
from umqtt.robust import MQTTClient
import json
dht_sensor = dht.DHT11(Pin(14))
pir = Pin(13, Pin.IN)
mqtt_client = None
wlan = None
HOUSE_ID = "6088716f4d60d0230034f87c"
def connectToNetwork(ssid, password):
global wlan
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to wlan network: %s' %ssid)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print('connected! network config:', wlan.ifconfig())
def on_message(topic, message):
print(message)
def connectToMQTT():
global mqtt_client
SSL_PARAMS = {'server_hostname': '50ffbd7e701c480ca097875a1621692c.s1.eu.hivemq.cloud'}
mqtt_client = MQTTClient(
client_id = 'birdie_house_' + ubinascii.hexlify(network.WLAN().config('mac'),'_').decode(),
server = '50ffbd7e701c480ca097875a1621692c.s1.eu.hivemq.cloud',
port = 8883,
keepalive = 30,
ssl=True,
user='birdie',
password='tjhpnHMQb2021',
ssl_params=SSL_PARAMS
)
mqtt_client.DEBUG = True
mqtt_client.connect()
async def readTemperatrue():
while True:
try:
await uasyncio.sleep(1)
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
print('Temperature: %3.1f C; ' %temp, 'Humidity: %3.1f %%' %hum)
except OSError as e:
print('Failed to read from DHT11 sensor: %s' %e)
async def detectMotion():
while True:
await uasyncio.sleep(1)
if pir.value():
print('Motion detected!')
x = {'houseId': HOUSE_ID, 'command': 'TAKE_PHOTO'}
mqtt_client.publish('birdie/rxtx/to/raspberry', json.dumps(x))
await uasyncio.sleep_ms(40)
while pir.value():
pass
await uasyncio.sleep_ms(40)
else:
print('No motion detected!')
connectToNetwork("wifi-lab", "12345wifilabhouse54321")
connectToMQTT()
event_loop = uasyncio.get_event_loop()
event_loop.create_task(readTemperatrue())
event_loop.create_task(detectMotion())
event_loop.run_forever()
......@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field
from typing import Optional, List
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
import json
#######################################################################################################################
......@@ -63,10 +64,10 @@ class HouseModel(BaseModel):
}
class TemperatureModel(BaseModel):
class Photo(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
houseId: PyObjectId = Field(default_factory=PyObjectId, alias="houseId")
value: float
base64Data: str
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
......@@ -75,7 +76,7 @@ class TemperatureModel(BaseModel):
"example": {
"id": "123456789012345678901234",
"houseId": "123456789012345678901234",
"temperature": 123.123
"base64Data": "djahjfkahdkfhahfaishfuhxafoaimxfjXXXX===="
}
}
......@@ -110,13 +111,18 @@ app.add_middleware(
@mqtt.on_connect()
def connect(client, flags, rc, properties):
mqtt.client.subscribe("/posluchac") #subscribing mqtt topic
mqtt.client.subscribe("birdie/rxtx/from/raspberry") #subscribing mqtt topic
print("Connected: ", client, flags, rc, properties, flush=True)
@mqtt.on_message()
async def message(client, topic, payload, qos, properties):
print("Received message: ", topic, payload.decode(), qos, properties, flush=True)
if topic == 'birdie/rxtx/from/raspberry':
recevieddata = json.loads(payload.decode())
document = {'houseId': ObjectId(recevieddata["houseId"]), 'base64Data': recevieddata["data"]}
result = await DB.photos.insert_one(document)
print('result %s' % repr(result.inserted_id))
return 0
......@@ -133,11 +139,11 @@ async def get_all_bird_houses_inside_mapbounds(leftTop_long: float, leftTop_lat:
return houses
@app.get("/temperatures/getlast", response_model=TemperatureModel)
async def get_last_temperature_of_specific_bird_house(houseId: str):
@app.get("/photo/getlast", response_model=Photo)
async def get_last_photo_of_specific_bird_house(houseId: str):
if not ObjectId.is_valid(houseId):
return JSONResponse({})
lastTemp = await DB["temperatures"].find({'houseId': ObjectId(houseId)}).sort('_id', -1).to_list(1)
lastTemp = await DB["photos"].find({'houseId': ObjectId(houseId)}).sort('_id', -1).to_list(1)
if len(lastTemp) > 0:
return lastTemp[0]
else:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment