Самостоятельная Работа По предмету: «Индивидуал Проект»


Download 217.86 Kb.
bet3/3
Sana17.09.2023
Hajmi217.86 Kb.
#1679869
TuriСамостоятельная работа
1   2   3
Bog'liq
Individual loyxa

SmartGarden Domain

(define (domain smart-garden)


(:requirements :strips :typing :fluents)
(:predicates (water ?w)
(plant ?p)
(free ?m)
(motor ?m)
(sufficientmoisturelevel ?p)
)
(:action watering
:parameters (?m1 ?p1)
:precondition(and (motor ?m1)
(free ?m1)
(not(water ?p1))
(not(sufficientmoisturelevel ?p1))
)
:effect (and (water ?p1)
(not (free ?m1))
(sufficientmoisturelevel ?p1)
)
)
(:action afterwatering
:parameters (?m1 ?p1)
:precondition (and (not(free ?m1)) (water ?p1))
:effect (free ?m1)
)
)
SmartGarden Lighting

(define(domain metricLight)


(:requirements :strips :typing :fluents)
(:types lamp garden)
(:predicates (lamp ?l)
(garden ?g)
(on ?l)
)
(:functions
(lamp-luminescence-level ?l)
(requiredluminescencelevel ?g)
(presentluminescencelevel ?g)
(total-no-lamp-used)
(count))
(:action switch-on-lamp
:parameters (?g ?l)
:precondition (and (lamp ?l)
(garden ?g)
(< (presentluminescencelevel ?g) (requiredluminescencelevel ?g))
(not(on ?l))
)
:effect (and
(increase (presentluminescencelevel ?g) (lamp-luminescence-level ?l))
(decrease (lamp-luminescence-level ?l)(lamp-luminescence-level ?l))
(increase (total-no-lamp-used)(count))
)
)
(:action switch-off-lamp
:parameters (?g ?l)
:precondition (and (lamp ?l)
(garden ?g)
(> (presentluminescencelevel ?g) (requiredluminescencelevel ?g))
(on ?l))
:effect (and
(decrease (presentluminescencelevel ?g) (lamp-luminescence-level ?l))
(decrease (lamp-luminescence-level ?l)(lamp-luminescence-level ?l))
(decrease (total-no-lamp-used)(count))
)
)
)

Controllers

1.lamp
# -*- coding: utf-8 -*-


"""
Created on Sat Jun 22 13:16:58 2019
Script Name:lamp.py
Script parse data from outputlamp.txt to execute the steps of the lampplanner.
"""

# Open the file with read only permit

#Import all the necessary packages
from plugwise import Stick
from plugwise import Circle
import pymysql
import pandas as pd
import time
s=Stick(port="/dev/ttyUSB0")
c1,c2=Circle("000D6F0005692784",s),Circle("000D6F000416E6F4",s)

host="mydbinstance.c1arr1firswu.us-east-2.rds.amazonaws.com"


port=3306
dbname="smartGardenDB"
user="root"
password="smartgarden"

conn = pymysql.connect(host, user=user,port=port,


passwd=password, db=dbname,autocommit=True)

f = open('outputlamp.txt', "r+")


# use readlines to read all lines in the file
# The variable "lines" is a list containing all lines in the file

lines = f.readlines()


# close the file after reading the lines.
f.close()
line1 = []
checkword = 'step'
for i in range(len(lines)):
if checkword in lines[i]:
j=i
break

del lines[0:j]

for i in range(len(lines)):

# check if line is not empty


if lines[i]=='\n':
break
lines.remove(i)
line1.append(lines[i])
del line1[(len(line1)-1):]
line2=[]
line3=[]
line4=[]
line5=[]
for i in range(len(line1)):
line1[i]=line1[i].split(":")
line2.append(str(line1[i][1]))

for i in range(len(line2)):


n=(line2[i].split("\n"))
line3.append(n[0])

for i in range(len(line3)):


if line3[i]==' SWITCH-ON-LAMP GARDEN LAMP1':
c1.switch_on()
cur = conn.cursor()
#update the lamp1 status to "on" in the database
updlamp1="update lamp_status set status = 'on' where id= 1"
cur.execute(updlamp1)
elif line3[i]==' SWITCH-ON-LAMP GARDEN LAMP2':
c2.switch_on()
cur = conn.cursor()
#update the lamp2 status to "on" in the database
updlamp2="update lamp_status set status = 'on' where id= 2"
cur.execute(updlamp2)
elif line3[i]==' SWITCH-OFF-LAMP GARDEN LAMP1':
print('OFF LAMP')
c1.switch_off()
cur = conn.cursor()
#update the lamp1 status to "off" in the database
updlamp3="update lamp_status set status = 'off' where id= 1"
cur.execute(updlamp3)
elif line3[i] == ' SWITCH-OFF-LAMP GARDEN LAMP2':
c2.switch_off()
cur = conn.cursor()
#update the lamp2 status to "off" in the database
updlamp4="update lamp_status set status = 'off' where id= 2"
cur.execute(updlamp4)

2.water


# -*- coding: utf-8 -*-
"""
Created on Sat Jun 22 13:16:58 2019
Script Name:water.py
Script parse data from outputwater.txt to execute the steps of the waterplanner.
"""

# Open the file with read only permit

#Import all the necessary packages
from plugwise import Stick
from plugwise import Circle
import pymysql
import time

s=Stick(port="/dev/ttyUSB0")


c1,c2=Circle("000D6F0005692784",s),Circle("000D6F000416E6F4",s)

#Database Connection


moisturecontentold=list()
host="mydbinstance.c1arr1firswu.us-east-2.rds.amazonaws.com"
port=3306
dbname="smartGardenDB"
user="root"
password="smartgarden"

conn = pymysql.connect(host, user=user,port=port,


passwd=password, db=dbname)
cursorObject = conn.cursor()
#Read the planner output
f = open('outputwater.txt', "r+")
# use readlines to read all lines in the file
# The variable "lines" is a list containing all lines in the file

lines = f.readlines()


# close the file after reading the lines.
f.close()
line1 = []
checkword = 'step'
for i in range(len(lines)):
if checkword in lines[i]:
j=i
break

del lines[0:j]

for i in range(len(lines)):

# check if line is not empty


if lines[i]=='\n':
break
lines.remove(i)
line1.append(lines[i])
del line1[(len(line1)-1):]
line2=[]
line3=[]
line4=[]
line5=[]
for i in range(len(line1)):
line1[i]=line1[i].split(":")
line2.append(str(line1[i][1]))

for i in range(len(line2)):


n=(line2[i].split(" "))

line3.append(n[1])


line4.append(n[2])
line5.append(n[3])

for i in range(len(line2)):


if line3[i]=='WATERING':
if line5[i]=='PLANT1\n':
c1.switch_on()
updateStatement = "UPDATE PlantDatabase SET last_watered = now() WHERE Plant_ID =1"
# Execute the SQL UPDATE statement to insert the time of watering
cursorObject.execute(updateStatement)
conn.commit()
elif line5[i]=='PLANT2\n':
c2.switch_on()
updateStatement = "UPDATE PlantDatabase SET last_watered = now() WHERE Plant_ID =2"
# Execute the SQL UPDATE statement to insert the time of watering
cursorObject.execute(updateStatement)
conn.commit()
elif line3[i]=='AFTERWATERING':
if line5[i] == 'PLANT1\n':
c1.switch_off()
elif line5[i] == 'PLANT2\n':
c2.switch_off()
time.sleep(10)
c1.switch_off()
c2.switch_off()

3.waterplanner

# -*- coding: utf-8 -*-
"""
Created on Sat Jun 22 13:16:58 2019
Script Name:waterplanner.py
"""
#Import all the necessary packages
import os
import time
import subprocess
import pymysql
import pandas as pd
import openzwave
from openzwave.node import ZWaveNode
from openzwave.value import ZWaveValue
from openzwave.scene import ZWaveScene
from openzwave.controller import ZWaveController
from openzwave.network import ZWaveNetwork
from openzwave.option import ZWaveOption
import six
import datetime
import spidev # To communicate with SPI devices
from numpy import interp

global moisturecontentold


global temperature
global humidity
global moisture

global temp


global humid

moisturecontentold=list()


host="mydbinstance.c1arr1firswu.us-east-2.rds.amazonaws.com"
port=3306
dbname="smartGardenDB"
user="root"
password="smartgarden"

now = datetime.datetime.now()


time8pm = now.replace(hour=23, minute=55, second=0, microsecond=0)

# Start SPI connection


spi = spidev.SpiDev() # Created an object
spi.open(0,0)

# Read MCP3008 data


def analogInput(channel):
spi.max_speed_hz = 1350000
adc = spi.xfer2([1,(8+channel)<<4,0])
data = ((adc[1]&3) << 8) + adc[2]
return data
while True:
conn = pymysql.connect(host, user=user,port=port,
passwd=password, db=dbname)
df5=pd.read_sql('SELECT Temperature FROM Temperature_Data ORDER BY ID DESC LIMIT 1;', con=conn)
s1=df5.iat[0,0]
temperature= float(df5.iat[0,0])
df6=pd.read_sql('SELECT Relative_Humidity FROM Humidity_Data ORDER BY ID DESC LIMIT 1;', con=conn)
humidity=int(df6.iat[0,0])
Moisture = []
df=pd.read_sql('select count(distinct plant_ID) AS "TotalPlants" from PlantDatabase;', con=conn)
TotalPlants=df.iat[0,0]
for i in range(TotalPlants):
output = analogInput(i) # Reading from CH0
output = interp(output, [0, 1023], [100, 0])
output = int(output)
Moisture.append(output)
#print("Moisturefromsensor:", Moisture)
moisturecontent= list()
for k in range(TotalPlants):
id=k+1
df1 = pd.read_sql('SELECT max_temp_withstand AS "Temp" FROM PlantDatabase where Plant_ID ='+ str(id), con=conn)
temp = df1.iat[0,0]
df2 = pd.read_sql('SELECT min_humidity AS "humid" FROM PlantDatabase where Plant_ID = '+str(id), con=conn)
humid=df2.iat[0,0]
df3 = pd.read_sql('SELECT min_soilmoisture AS "moisture" FROM PlantDatabase where Plant_ID = '+str(id), con=conn)
moisture=df3.iat[0,0]
df5 = pd.read_sql('SELECT last_watered AS "lastwatered" FROM PlantDatabase where Plant_ID = '+str(id), con=conn)
last=df5.iat[0,0]
df4 = pd.read_sql('SELECT timestampdiff(HOUR,last_watered,NOW()) FROM PlantDatabase where Plant_ID = '+str(id), con=conn)
lastwatered=df4.iat[0,0]
if ((temperature>= temp) and (humidity <= humid) and (lastwatered >= 8)):
moisturecontent.append('notsufficient')
elif (Moisture[k]< moisture):
moisturecontent.append('notsufficient')
else:
moisturecontent.append('sufficient')
print(moisturecontent)

if(len(moisturecontent)==0):
continue

elif ((moisturecontent[0]=="sufficient") and (moisturecontent[1]=="sufficient")):


continue
elif(now # The written code is generated to the "out" variable.
out = """
(define (problem water-garden)
(:domain smart-garden)
(:objects plant1 plant2 motor1 motor2 )
(:init (plant plant1)
(plant plant2)
(motor motor1)
(motor motor2)
(free motor1)
(free motor2)

"""
plant_names = list()
for i in range(TotalPlants):
if (moisturecontent[i]=='sufficient'):
out += " (sufficientmoisturelevel plant{})".format(i+1)
out += """
"""
out +=""")
(:goal (and (sufficientmoisturelevel plant1)
(sufficientmoisturelevel plant2)
)))
"""
filename = "smartGarden_problem"
with open(filename, "w") as f:
f.write(out)
#Extract Steps from outputfile and turn on motor accordingly
myCmd = './ff -o smartGarden_domain.pddl -f smartGarden_problem > outputwater.txt'
os.system(myCmd)
myCmd = 'python water.py'
os.system(myCmd)
moisturecontentold = moisturecontent
time.sleep(15)


Download 217.86 Kb.

Do'stlaringiz bilan baham:
1   2   3




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling