My problem that i need help fixing is combining these two codes without breaking the first code which is InControl of automated robotic mower, and the second script is for an irrigation system. here on are the details of each code :
Script 1 Analysis
This script appears to be a Python program for controlling and monitoring a robotic lawn mower. It uses various libraries, including requests for HTTP requests, xml.etree.ElementTree for parsing XML data, and serial for serial communication.
The script has several functions:
mowerController: sends commands to the mower using HTTP requests.
getMoistureData: reads moisture data from a sensor connected via serial communication.
boundaryWireSensorValues: retrieves data from boundary wire sensors.
gpsValues: gets GPS data from the mower.
datetimeValues: gets date and time data from the mower.
saveData: saves data to a CSV file.
linearActuator: controls a linear actuator.
detectBoundary: detects boundary wire sensors and controls the mower accordingly.
setup: sets up GPIO pins and initializes the script.
The script runs in an infinite loop, checking for connectivity to the mower and executing the detectBoundary function if connected.
Script 2 Analysis
This script appears to be a Python program for calculating the average soil moisture from a CSV file and controlling irrigation valves based on the average value.
The script uses the pandas library for data manipulation and the requests library for sending HTTP requests to control the valves.
The script has two main functions:
Average: calculates the average of a list of values.
parseData: reads data from a CSV file, calculates average soil moisture for each date, and controls the irrigation valves if the average moisture is below a set threshold.
The script runs in an infinite loop, checking the time and executing the parseData function once a day.
import requests
import xml.etree.ElementTree as ET
import time
import os
import re
import serial
from datetime import datetime
import random
import RPi.GPIO as GPIO
import pandas as pdConstants
PATH = ‘/home/pi/Desktop/data/’ + datetime.now().strftime(“%T”) + ‘_data.csv’
ERROR_PATH = ‘/home/pi/Desktop/log.txt’
COLUMN = ‘CalibratedCountsVWC’
TIMER_DELAY = 86400 # 24 hoursVariables
counter = 0
pushOutPin = 3
pushInPin = 7
swPin = 29
sensorFailureCounter = 0
timer = time.time()GPIO setup
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(swPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(pushOutPin, GPIO.OUT)
GPIO.output(pushOutPin, 1)
GPIO.setup(pushInPin, GPIO.OUT)
GPIO.output(pushInPin, 1)def format_date(date_str):
return datetime.strptime(date_str, ‘%Y-%m-%d’).strftime(‘%B %d, %Y’)def mowerController(argument):
return requests.get(‘http://192.168.5.154/xml?&user=GNI_Robonect&pass=GNI&cmd=’ + argument)def csvHeader():
output = open(PATH, “a”)
header = ‘Sample Number,date,time,latt,long,Row,Row#,CalibratedCountsVWC,Temperature,ElectricalConductivity,FrontLeft_quality,FrontLeft_a,FrontLeft_n,FrontLeft_f,FrontLeft_g1,FrontLeft_g2,FrontRight_quality,FrontRight__a,FrontRight_n,FrontRight_f,FrontRight_g1,FrontRight_g2,BackLeft_quality,BackLeft_a,BackLeft_n,BackLeft_f,BackLeft_g1,BackLeft_g2,BackRight_quality,BackRight_a,BackRight_n,BackRight_f,BackRight_g1,BackRight_g2n’
output.write(header)
output.close()def connectedToRobonect():
try:
mowerController(‘gps’)
return True
except:
return Falsedef getMoistureData(ser):
global sensorFailureCounter
errorOutput = open(ERROR_PATH, “a”)
output_str = ” , , “if ser:
try:
time.sleep(2.5)
ser.write(b’?!’)
sdi_12_line = ser.readline()sdi_12_line = sdi_12_line[:-2]
m = re.search(b'[0-9a-zA-Z]$’, sdi_12_line)
sdi_12_address = m.group(0)ser.write(sdi_12_address + b’I!’)
sdi_12_line = ser.readline()
print(‘Sensor info:’, sdi_12_line.decode(‘utf-8’))values = []
ser.write(sdi_12_address + b’M!’)
sdi_12_line = ser.readline()
sdi_12_line = sdi_12_line[:-2]
m = re.search(b'[0-9]$’, sdi_12_line)
total_returned_values = int(m.group(0))
sdi_12_line = ser.readline()
ser.write(sdi_12_address + b’D0!’)
sdi_12_line = ser.readline()
sdi_12_line = sdi_12_line[1:-2]for i in range(total_returned_values):
m = re.search(b'[+-][0-9.]+’, sdi_12_line)
values.append(float(m.group(0)))
sdi_12_line = sdi_12_line[len(m.group(0)):]output_str = “%s” % (values[0] * 0.0003879 – 0.6956) + “,%s” % (values[1]) + “, %s” % (values[2])
sensorFailureCounter = 0
except Exception as e:
sensorFailureCounter += 1
if sensorFailureCounter > 3:
mowerController(‘stop’)
errorOutput.write(str(sensorFailureCounter) + ‘ Fails in a row the error is: ‘ + str(e) + ‘n’)
print(e)
output_str = ” , , ”
else:
output_str = ” , , “return output_str
def boundaryWireSensorValues(fullData=True):
r2 = mowerController(‘wire’).text
try:
sensorTree = ET.fromstring(r2)
except Exception as e:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘couldn’t read wire tree error given is ‘ + str(e) + ‘n’)
if fullData:
if sensorTree.find(‘successful’).text == ‘true’:
sensors = sensorTree.find(‘sensors’)
sensorData = []for sensor in sensors:
for data in sensor:
if data.tag != ‘description’:
sensorData.append(data.text)sensorData = ‘,’.join(map(str, sensorData))
else:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘failed to read full Sensor datan’)
sensorData = ‘Error: No Sensor Data’return sensorData
else:
if sensorTree.find(‘successful’).text == ‘true’:
return sensorTree[0][1][2].text, sensorTree[0][0][2].text
else:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘failed to read Sensor datan’)
print(‘Error: No Sensor Data’)def gpsValues():
r = mowerController(‘gps’).texttry:
gpsTree = ET.fromstring(r)
except Exception as e:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘couldn’t read wire tree error given is ‘ + str(e) + ‘n’)if gpsTree.find(‘successful’).text == ‘true’:
latitude = gpsTree[0][1].text
longitude = gpsTree[0][2].text
else:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘failed to read GPS datan’)
latitude = longitude = ‘Error: No GPS signal’return latitude, longitude
def datetimeValues():
r2 = mowerController(‘clock’).texttry:
timeTree = ET.fromstring(r2)
except Exception as e:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘couldn’t read time tree error given is ‘ + str(e) + ‘n’)if timeTree.find(‘successful’).text == ‘true’:
log_date = format_date(r2[55:65])
log_time = r2[78:86]
else:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘failed to read time datan’)
latitude = longitude = ‘Error: No time signal’return log_date, log_time
def saveData(ser):
global counter
output = open(PATH, “a”)
log_date, log_time = datetimeValues()
latitude, longitude = gpsValues()
sensorData = boundaryWireSensorValues()for x in range(3):
moistureData = getMoistureData(ser)
if moistureData != ” , , “:
break
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘failed to read sensor datan’)outputData = str(counter) + ‘,’ + log_date + ‘,’ + log_time + ‘,’ + latitude + ‘,’ + longitude + ‘,’ + str(random.randint(7, 9)) + ‘,’ + str(random.randint(1, 4)) + ‘,’ + moistureData + ‘,’ + sensorData + ‘n’
output.write(outputData)
print(outputData)counter += 1
output.close()def linearActuator(direction):
delay = 18
timer = time.time()
debounceCount = 100
counter = 0
currentState = 1
startTime = round(time.time() * 1000)
nextMillisecond = 0GPIO.output(pushOutPin, 1)
GPIO.output(pushInPin, 1)while time.time() – timer < delay:
if direction == ‘d’:
GPIO.output(pushOutPin, 1)
GPIO.output(pushInPin, 0)if round(time.time() * 1000) – startTime != nextMillisecond:
reading = GPIO.input(swPin)
if reading == currentState and counter > 0:
counter -= 1
if reading != currentState:
counter += 1if counter >= debounceCount:
counter = 0
currentState = reading
print(‘stop switch is hit’)
breaknextMillisecond = 5 * (round(time.time() * 1000) – startTime)
else:
GPIO.output(pushOutPin, 0)
GPIO.output(pushInPin, 1)GPIO.output(pushOutPin, 1)
GPIO.output(pushInPin, 1)def detectBoundary(ser):
frontL, frontR = boundaryWireSensorValues(False)frontL = int(frontL)
frontR = int(frontR)if frontR < 0 or frontL < 0:
mowerController(‘stop’)
print(‘stopped’)
time.sleep(2)mowerController(‘direct&left=50&right=50&timeout=1000’)
time.sleep(2)linearActuator(‘d’)
saveData(ser)
time.sleep(0.5)
linearActuator(‘a’)mowerController(‘direct&left=-50&right=-50&timeout=1500’)
time.sleep(2.5)mowerController(‘start’)
print(‘started’)
time.sleep(13)def parseData():
df = pd.read_csv(PATH)print(df.head())
threshold = 0.3 # Threshold to open the irrigation valve
Calculate average soil moisture for each date
averages_by_date = df.groupby(‘date’)[COLUMN].mean()
print(averages_by_date)for date, avg_moisture in averages_by_date.items():
if avg_moisture < threshold:
print(f’Date: {date}, Average Moisture: {avg_moisture} – Valve opened’)
Open the valve (adjust the URL and parameters as needed)
requests.get(‘http://192.168.5.174:80/cm?pw=a6d82bced638de3def1e9bbb4983225c&sid=0&en=1&t=20’)Initial setup
csvHeader()outputError = open(ERROR_PATH, “a”)
outputError.write(‘nn’)
outputError.write(‘n’)
outputError.write(‘ Log Data for run on ‘ + datetime.today().strftime(‘%A’) + ‘ ‘ + datetime.now().strftime(“%D %R”) + ‘ n’)
outputError.write(‘n’)
outputError.write(‘nn’)try:
ser = serial.Serial(port=’/dev/ttyUSB0′, baudrate=9600, timeout=1)
except Exception as e:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘failed to open sensor portn’)
ser = 0
print(‘failed to open port’)while True:
if connectedToRobonect():
detectBoundary(ser)
else:
errorOutput = open(ERROR_PATH, “a”)
errorOutput.write(‘couldn’t connect to robonectn’)
print(‘Not connected to Robonect’)if time.time() – timer > TIMER_DELAY:
parseData()
timer = time.time()if ser:
ser.close()
`your text
jahiem wilson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.