-
Notifications
You must be signed in to change notification settings - Fork 1
/
test2_streamlit_app.py
214 lines (169 loc) · 8.26 KB
/
test2_streamlit_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import requests
import json
import serial
import time
import streamlit as st
import plotly.express as px
import pandas as pd
import threading
from lib.sms import send_sms
import requests
# Define your OpenAI API key
openai_api_key = 'EXPAMPLE - KEY HERE'
# Function to send sensor data to OpenAI API and get a response
def get_openai_response(prompt):
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {openai_api_key}',
}
data = {
'model': 'gpt-4',
'messages': [{'role': 'system', 'content': 'You are an intelligent assistant for farmers.'},
{'role': 'user', 'content': prompt}]
}
response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()['choices'][0]['message']['content']
else:
raise Exception(f"OpenAI API request failed with status code {response.status_code}: {response.text}")
# Function to listen for incoming data from the LoRa Waziup board
def listen_for_lora_data():
try:
# Replace 'COM4' with your LoRa board's serial port
ser = serial.Serial('COM4', baudrate=9600, timeout=5)
# Give the board some time to initialize
time.sleep(1)
if ser.inWaiting() > 0:
incoming_data = ser.readline().decode('utf-8').strip()
sensor_data = json.loads(incoming_data)
return sensor_data
# Close the serial connection
ser.close()
except Exception as e:
print(f"Error: {e}")
return None
# Function to handle user questions based on sensor data
def answer_user_question(question, sensor_data, crop_type, language):
if language == 'English':
prompt = f"Given the following sensor data for {crop_type}: {sensor_data}, please answer the following question: {question}"
elif language == 'Kiswahili':
prompt = f"Ukipatiwa takwimu zifuatazo za sensa kwa {crop_type}: {sensor_data}, tafadhali jibu swali lifuatalo: {question}"
return get_openai_response(prompt)
# Function to listen for incoming SMS
def listen_for_sms():
try:
# Replace 'COM3' with your modem's serial port
ser = serial.Serial('COM3', baudrate=9600, timeout=5)
while True:
# Give the modem some time to initialize
time.sleep(1)
# Check for incoming SMS
ser.write(b'AT+CMGL="REC UNREAD"\r')
time.sleep(0.5)
response = ser.read(ser.inWaiting()).decode()
if "CMGL" in response:
# Extract phone number and message from the response
lines = response.split("\n")
for line in lines:
if line.startswith("+CMGL"):
parts = line.split(",")
phone_number = parts[2].strip('"')
message_index = parts[0].split()[1]
elif not line.startswith("AT") and line.strip() != "":
user_question = line.strip()
if user_question:
try:
response = answer_user_question(user_question, predefined_data, crop_type, language)
send_sms(api_url, username, password,phone_number, response)
except Exception as e:
print(f"Error: {e}")
# Delete the message
ser.write(f'AT+CMGD={message_index}\r'.encode())
time.sleep(0.5)
ser.read(ser.inWaiting()).decode()
except Exception as e:
print(f"Error: {e}")
# Streamlit interface
st.title("AGRISENSE - Smart IoT Farming 🚀")
# Sidebar for language selection
language = st.sidebar.selectbox("Select Language", ["English", "Kiswahili"])
# Input fields for sensor data with default values
soil_moisture = st.number_input('Soil Moisture (%)', min_value=0, max_value=100, value=45)
temperature = st.number_input('Temperature (°C)', min_value=-50, max_value=100, value=22)
humidity = st.number_input('Humidity (%)', min_value=0, max_value=100, value=60)
crop_type = st.text_input('Crop Type', value='maize')
phone_number = st.text_input('Phone Number', value='+255745676969')
# Initial predefined sensor data
predefined_data = {
'soil_moisture': soil_moisture,
'temperature': temperature,
'humidity': humidity
}
# Button to process data and get recommendations
if st.button('Get Recommendations'):
sensor_data = {
'soil_moisture': soil_moisture,
'temperature': temperature,
'humidity': humidity
}
if language == 'English':
prompt = f"The following data has been collected from sensors for {crop_type}: {sensor_data}. Based on this data, please explain its implications for the farmer and provide specific recommendations on what actions to take if necessary."
elif language == 'Kiswahili':
prompt = f"Takwimu zifuatazo zimekusanywa kutoka kwa sensa kwa {crop_type}: {sensor_data}. Kulingana na takwimu hizi, tafadhali eleza athari zake kwa mkulima na toa mapendekezo maalum ya hatua za kuchukua ikiwa ni lazima."
try:
response = get_openai_response(prompt)
st.success("Response from AgrisenseAI:")
st.write(response)
api_url = "http://sms.reubenwedson.site/api/sms/v1/text/single"
username = "username"
password = "password"
# Send the response via SMS
response2v = send_sms(api_url, username, password,phone_number, response)
st.success(f"SMS sent successfully!{response2v} in {phone_number}")
except Exception as e:
st.error(f"Error: {e}")
# Create a DataFrame from predefined sensor data
df = pd.DataFrame([predefined_data])
# Reshape the DataFrame for Plotly
df_melted = df.melt(var_name='Sensor', value_name='Value')
# Create a bar chart using Plotly
fig = px.bar(df_melted, x='Sensor', y='Value', title='Sensor Data Visualization')
st.plotly_chart(fig)
# Chat input for user questions
user_question = st.chat_input("Ask a question based on the data:")
if user_question:
try:
response = answer_user_question(user_question, predefined_data, crop_type, language)
st.success("Response from AgrisenseAI:")
st.write(response)
except Exception as e:
st.error(f"Error: {e}")
# Start the SMS listener thread
sms_listener_thread = threading.Thread(target=listen_for_sms)
sms_listener_thread.daemon = True
sms_listener_thread.start()
# Continuous loop to listen for incoming IoT data
st.write("Listening for incoming IoT data...")
while True:
lora_data = listen_for_lora_data()
if lora_data:
st.write("Incoming IoT data:", lora_data)
if language == 'English':
prompt = f"The following data has been collected from sensors for {crop_type}: {lora_data}. Based on this data, please explain its implications for the farmer and provide specific recommendations on what actions to take if necessary."
elif language == 'Kiswahili':
prompt = f"Takwimu zifuatazo zimekusanywa kutoka kwa sensa kwa {crop_type}: {lora_data}. Kulingana na takwimu hizi, tafadhali eleza athari zake kwa mkulima na toa mapendekezo maalum ya hatua za kuchukua ikiwa ni lazima."
try:
response = get_openai_response(prompt)
st.success("Response from OpenAI:")
st.write(response)
# Send the response via SMS
response2v = send_sms(phone_number, response)
st.success(f"SMS sent successfully!{response2v} in {phone_number}")
# Update the bar chart with the new data
df = pd.DataFrame([lora_data])
df_melted = df.melt(var_name='Sensor', value_name='Value')
fig = px.bar(df_melted, x='Sensor', y='Value', title='Sensor Data Visualization')
st.plotly_chart(fig)
except Exception as e:
st.error(f"Error: {e}")
time.sleep(10) # Adjust the sleep interval as needed