Skip to content

Commit

Permalink
websocket server
Browse files Browse the repository at this point in the history
  • Loading branch information
dederomagnolo committed Oct 16, 2020
1 parent 59950f8 commit 052d4e8
Show file tree
Hide file tree
Showing 10 changed files with 183 additions and 231 deletions.
50 changes: 38 additions & 12 deletions Local Station/bethere_local_station/bethere_local_station.ino
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
#define pinDHT2 13 //D7
#define pinDHT3 14 //D5
#define typeDHT DHT22
#define pumpInputRelay 2
#define pumpInputRelay 16 // D3


using namespace websockets;

Expand Down Expand Up @@ -54,7 +55,7 @@ void setup() {

// initialize output for relay and put it high
pinMode(pumpInputRelay, OUTPUT);
digitalWrite(pumpInputRelay, LOW); //bomba desligada
digitalWrite(pumpInputRelay, HIGH); //bomba desligada

// begin DHT sensors
dht.begin();
Expand Down Expand Up @@ -99,12 +100,13 @@ void setup() {
wsclient.onMessage([&](WebsocketsMessage message){
Serial.print("Message from server: ");
Serial.println(message.data());

// change state
if(message.data() == "1")
digitalWrite(pumpInputRelay, LOW);
else {
if(message.data() == "1") {
digitalWrite(pumpInputRelay, LOW);
wsclient.send("Pump on!");
} else {
digitalWrite(pumpInputRelay, HIGH);
wsclient.send("Pump off!");
}
});

Expand All @@ -129,8 +131,8 @@ void loop() {
yield();
} else {
Serial.println("reconnecting to websocket server...");
wsclient.send("Be There is alive!");
wsclient.connect(websocketServerHost, websocketServerPort, "/");
wsclient.send("Be There is alive!");
}

if(digitalRead(pumpInputRelay) == LOW) {
Expand All @@ -155,21 +157,45 @@ void loop() {
lcd.setCursor(0, 0);
lcd.print("H:");
lcd.setCursor(2, 0);
lcd.print(internalHumidity);

if (isnan(internalHumidity)) {
lcd.print("--.--");
} else {
lcd.print(internalHumidity);
}

lcd.setCursor(0 ,1);
lcd.print("T:");
lcd.setCursor(2 ,1);
lcd.print(internalTemperature);

if (isnan(internalTemperature)) {
lcd.print("--.--");
} else {
lcd.print(internalTemperature);
}

delay(200);

lcd.setCursor(8, 0);
lcd.print("H2:");
lcd.setCursor(11, 0);
lcd.print(externalHumidity);

if (isnan(externalHumidity)) {
lcd.print("--.--");
} else {
lcd.print(externalHumidity);
}

lcd.setCursor(8 ,1);
lcd.print("T2:");
lcd.setCursor(11 ,1);
lcd.print(externalTemperature);

if (isnan(externalTemperature)) {
lcd.print("--.--");
} else {
lcd.print(externalTemperature);
}

delay(200);

// Just for debug - print in serial monitor
Expand Down Expand Up @@ -206,5 +232,5 @@ void loop() {
Serial.println("Coneection Error: " + String(response));
}
}
delay(10000);
delay(2000);
}
2 changes: 1 addition & 1 deletion bethere-app/src/components/card/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@
}

.labelBig {
font-size: 20px;
font-size: 16px;
}
185 changes: 75 additions & 110 deletions bethere-app/src/components/dashboard/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import Toggle from 'react-styled-toggle';
import api from '../../services';
import * as _ from 'lodash';
import moment from 'moment';
import { ResponsiveLine } from '@nivo/line';
import { setColorId, isOdd, setMeasureId } from './utils';
import {NewCard} from '../newCard';
import {Cards} from './styles';
import {Cards, MainContainer} from './styles';
import {Graph} from './graph';

const base_channel_url = "https://api.thingspeak.com/channels/695672"
const bethereUrl = "http://localhost:4000";
Expand All @@ -27,13 +27,8 @@ export const Dashboard = () => {
const [timeLeft, setTimeLeft] = useState(null);
const [measures, setMeasures] = useState(initialState.measures);
const [chartData, setChartData] = useState([]);

const today = moment().format('YYYY-MM-DD');
const nextDay = moment().add(1, 'days').format('YYYY-MM-DD');

const queryStart = `${today}%2000:00:00`;
const queryEnd = `${nextDay}%2000:00:00`;

const [temperatureData, setTemperatureData] = useState([]);
const [humidityData, setHumidityData] = useState([]);
// Week Logics
/* const lastWeekStartDate = moment().subtract(5, 'days').format("YYYY-MM-DD"); */
/* const queryStart = `${lastWeekStartDate}%2000:00:00`; */
Expand Down Expand Up @@ -72,40 +67,58 @@ export const Dashboard = () => {
}
}

const updateFields = async (fieldNumber) => {
try {
const response = await api.get(`${base_channel_url}/fields/${fieldNumber}.json?start=${queryStart}&end=${queryEnd}`); //
const weekFeed = _.get(response, 'data.feeds');
const weekFeedSlice = _.slice(weekFeed, 50);
console.log(weekFeedSlice);
const data = [];
_.each(weekFeed, (entry, index) => {
if(isOdd(index)) {
const created_at = _.get(entry, 'created_at');
const fieldMeasure = _.get(entry, `field${fieldNumber}`);
data.push({
"x": moment(created_at).format('hh:mm:ss'),
"y": fieldMeasure && fieldMeasure !== "nan" ? Number(fieldMeasure).toFixed(2) : 31.8
});
}
});

setChartData((chartData) => [...chartData, {
"id": setMeasureId(fieldNumber),
"color": setColorId(fieldNumber),
"data": data
}]);
} catch(err) {
console.log(err);
}
}

useEffect(() => {
updateDataFromRemote();

const updateFields = async (fieldNumber) => {
const today = moment().format('YYYY-MM-DD');
const nextDay = moment().add(1, 'days').format('YYYY-MM-DD');
const queryStart = `${today}%2000:00:00`;
const queryEnd = `${nextDay}%2000:00:00`;

try {
const response = await api.get(`${base_channel_url}/fields/${fieldNumber}.json?start=${queryStart}&end=${queryEnd}`); //
const weekFeed = _.get(response, 'data.feeds');
const weekFeedSlice = _.slice(weekFeed, 50);
const data = [];
_.each(weekFeed, (entry, index) => {
if(isOdd(index)) {
const created_at = _.get(entry, 'created_at');
const fieldMeasure = _.get(entry, `field${fieldNumber}`);
data.push({
"x": moment(created_at).format('hh:mm:ss'),
"y": fieldMeasure && fieldMeasure !== "nan" ? Number(fieldMeasure).toFixed(2) : 31.8
});
}
});

setChartData((chartData) => [...chartData, {
"id": setMeasureId(fieldNumber),
"color": setColorId(fieldNumber),
"data": data
}]);
} catch(err) {
console.log(err);
}
}

updateFields(4);
updateFields(6);
/* updateFields(3);
updateFields(5); */

}, []);

useEffect(() => {
console.log(chartData);
const temperatureChartData = [chartData[0], chartData[1]];
/* const humidityChartData = [chartData[2], chartData[3]];
console.log(temperatureChartData); */
console.log(temperatureChartData);
setTemperatureData(temperatureChartData);
/* setHumidityData(humidityChartData); */
}, [chartData])

useEffect(() => {
if(timeLeft === 0){
setBlockButtonFlag(false);
Expand Down Expand Up @@ -145,10 +158,10 @@ export const Dashboard = () => {
}

return (
<div style={{height: "100%"}}>
<MainContainer>
<Header title="Dashboard"/>
<div>
<span style={{fontSize: "20px"}}>Hello! Your garden looks good today:</span>
{/* <span style={{fontSize: "20px"}}>Hello! Your garden looks good today:</span> */}
<Cards>
<NewCard
label={"Temperature (°C)"}
Expand All @@ -162,78 +175,30 @@ export const Dashboard = () => {
internalMeasure={measures.internalHumidity}
externalMeasure={measures.externalHumidity}
/>
</Cards>
<div style={{display: 'flex', flexDirection: 'row', alignItems: 'center', paddingTop: '20px'}}>
<div style={{fontSize: '20px', paddingRight: '20px'}}>
Pump
</div>
<Toggle backgroundColorChecked="#3bea64" disabled={blockButtonFlag} checked={pumpFlag} onChange={() => updatePump()}/>
<div style={{marginLeft: '10px'}}>{blockButtonFlag ? `Wait ${timeLeft} seconds to send another command` : "Available!"}</div>
</div>

<div style={{width: '85%' , height: '200px'}}>
<ResponsiveLine
data={chartData}
margin={{ top: 10, right: 10, bottom: 50, left: 10 }}
xScale={{ type: 'point' }}
yScale={{ type: 'linear', min: 'auto', max: 'auto', stacked: false, reverse: false }}
axisTop={null}
axisRight={null}
axisBottom={{
orient: 'bottom',
tickSize: 5,
tickPadding: 5,
tickRotation: 50,
legendOffset: 20,
legendPosition: 'middle'
}}
axisLeft={{
orient: 'left',
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'measure',
legendOffset: -40,
legendPosition: 'middle'
}}
colors={{ scheme: 'nivo' }}
pointSize={2}
pointColor={{ theme: 'background' }}
pointBorderWidth={8}
pointBorderColor={{ from: 'serieColor' }}
pointLabel="y"
pointLabelYOffset={-10}
useMesh={true}
legends={[
{
anchor: 'top',
direction: 'column',
justify: false,
translateX: 100,
translateY: 0,
itemsSpacing: 0,
itemDirection: 'left-to-right',
itemWidth: 80,
itemHeight: 20,
itemOpacity: 0.75,
symbolSize: 12,
symbolShape: 'circle',
symbolBorderColor: 'rgba(0, 0, 0, .5)',
effects: [
{
on: 'hover',
style: {
itemBackground: 'rgba(0, 0, 0, .03)',
itemOpacity: 1
}
}
]
<NewCard
label={"Pump Control"}
icon={"cog"}
pump={true}
children={
<div>
<Toggle
backgroundColorChecked="#3bea64"
disabled={blockButtonFlag}
checked={pumpFlag}
onChange={() => updatePump()}
/>
<div>{blockButtonFlag ? `Wait ${timeLeft} seconds to send another command` : "Available!"}</div>
</div>
}
]}
/>

</div>
>
</NewCard>
</Cards>
{chartData.length > 0 && temperatureData.length > 0 &&
<>
<Graph chartData={chartData}/>
{/* <Graph chartData={humidityData} /> */}
</>}
</div>
</div>
</MainContainer>
);
}
18 changes: 18 additions & 0 deletions bethere-app/src/components/dashboard/styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,22 @@ export const Cards = styled.div`
justify-content: center;
align-items: center;
}
`

export const MainContainer = styled.div`
padding-left: 15px;
height: 100%;
`

export const GraphContainer = styled.div`
padding-top: 40px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
@media screen and (max-width: 425px){
width: 100%;
}
`
Loading

0 comments on commit 052d4e8

Please sign in to comment.