Ver Fonte

new method names, automatic update, added status, fixed bugs

Bernadette Elena Hammerle há 4 anos atrás
pai
commit
0b53cef944
3 ficheiros alterados com 47 adições e 132 exclusões
  1. 35 113
      src/App.js
  2. 6 6
      src/Tables.js
  3. 6 13
      src/database_interface.py

+ 35 - 113
src/App.js

@@ -1,6 +1,4 @@
 import React, { Component } from 'react';
-//import persons from './persons';
-//import ReactDOM from 'react-dom';
 import './App.css';
 import Tables from './Tables';
 
@@ -8,6 +6,8 @@ import Tables from './Tables';
 class App extends Component {
   constructor(props){
     super(props);
+    this.apiUrl = "http://localhost:5000";
+    this.name = null;
     this.state = {
       persons: []
     };
@@ -17,140 +17,62 @@ class App extends Component {
 
   // is called once when loading the page
   componentDidMount() {
-      //fetch("http://192.168.8.100:3001/persons")
-      fetch("http://localhost:5000/users")
-      .then(response => {
-          if (response.ok) {
-                  return response;
-          } else {
-              let errorMessage = "${response.status(${response.statusText})",
-              error = new Error(errorMessage);
-              throw(error);
-          }
-      })
+    this.reloadLocations();
+    setInterval(this.updateLocation, 10000);
+  }
+  
+  reloadLocations = () => {
+    fetch(this.apiUrl + "/users")
       .then(response => response.json())
-      .then(json =>{
-         console.log(json["users"]);
-         this.setState({ persons: json["users"] })
+      .then(data =>{
+         console.log(data["users"]);
+         this.setState({ persons: data["users"] })
       }).catch(error => {
         console.log(error);
     });
-      
   }
-
-
-  /*change = () => {
-    const newPersons = [...this.state.persons];
-    const id = 0;
-    newPersons.map( person => {
-      if (id == person.id) {
-        const axios = require('axios');
-        let longitude = Math.floor((Math.random() * 150) + 1);
-        let latitude = Math.floor((Math.random() * 150) + 1); 
-    
-        //axios.put('http://192.168.8.100:3001/persons/0/', {
-        axios.put('http://localhost:3001/persons/0/', {
-            longitude: longitude,
-            latitude: latitude,
-            shortName: "VEN",
-            name: "Martin",
-            speed: 1,
-            color: "#ddd"
-        }).catch(error => {
-            console.log(error);
-        });
-      }
-      
-    })
-    this.componentDidMount()
-    
-  }*/
   
-  getLocation = (name) => {
+  receivedPosition = (position) => {
     const axios = require('axios');
-    const newPersons = [...this.state.persons];
-    
-    if (navigator.geolocation) { //check if geolocation is available
-      navigator.geolocation.getCurrentPosition(function(position){
-        console.log(position);
-        console.log({"longitude": position.coords.longitude, "latitude": position.coords.latitude, "timestamp": position.timestamp, "name": name})
-        
-        axios.put('http://localhost:5000/report-location', {
-          "longitude": position.coords.longitude,
-          "latitude": position.coords.latitude,
-          "timestamp": position.timestamp,
-          "name": name}).catch(error => {
-            console.log(error);
-        });
-        
-        newPersons.map( person => {
-          if (name == person.name) {
-            person.longitude = position.coords.longitude
-            person.latitude = position.coords.latitude
-          }
-        })
-      });   
-    }
-    this.setState({ persons: newPersons });
+    axios.put(this.apiUrl + "/report-location", {
+      "longitude": position.coords.longitude + Math.random()*10,
+      "latitude": position.coords.latitude,
+      "timestamp": position.timestamp/1000, // in seconds
+      "name": this.name
+    }).then(this.reloadLocations)
+    .catch(error => {
+        console.log(error);
+    });
   }
   
+  updateLocation = () => {
+    if (this.name!=null && navigator.geolocation) { //check if geolocation is available
+      navigator.geolocation.getCurrentPosition(this.receivedPosition);
+    }
+  }
   
 
-  
-  /*create = (id) => {
-    const axios = require('axios');
-    let longitude = Math.floor((Math.random() * 100) + 1);
-    let latitude = Math.floor((Math.random() * 100) + 1);
-    
-    if (navigator.geolocation) { //check if geolocation is available
-      navigator.geolocation.getCurrentPosition(
-        function(position){
-          console.log(position);
-          longitude = position.coords.longitude
-          latitude = position.coords.latitude
-        })
-      };   
-
-    //axios.put('http://localhost:3001/persons/0/', {
-    axios.put('http://localhost:3001/persons/0/', {
-        longitude: longitude,
-        latitude: latitude,
-        shortName: "VEN",
-        name: "Martin", // *** getAttribute
-        speed: 1,
-        color: "#ddd"
-    }).catch(error => {
-        console.log(error);
-    });
-  }*/
-
   render (){
-  //setTimeout(this.componentDidMount, 10000)
-        
     return (
       <div id="wrapper">
         <Tables persons={this.state.persons}/>
-        <div id="debug"> </div>
+
         <button
             onClick={ () => {
-              this.getLocation("Bernie");
-              }}
-              > Bernie </button>
+              this.name = "Bernie";
+            }}> Bernie </button>
         <button
             onClick={ () => {
-              this.getLocation("Martin");
-              }}
-              > Martin </button>
+              this.name = "Martin";
+            }}> Martin </button>
         <button
             onClick={ () => {
-              this.getLocation("Simon");
-              }}
-              > Simon </button>
+              this.name = "Simon";
+            }}> Simon </button>
         <button
             onClick={ () => {
-              this.getLocation("Lukas");
-              }}
-              > Lukas </button>
+              this.name = "Lukas";
+            }}> Lukas </button>
       </div>
   );
   }

+ 6 - 6
src/Tables.js

@@ -25,9 +25,9 @@ function Tables({persons}) {
         <p>{currentDate.getDate()}.{currentDate.getMonth() + 1}.{currentDate.getFullYear()}</p>
       </div>
       <div id="online">
-        {sortedpersons.filter(person => person.longitude!=null).map((person, index) => {
+        {sortedpersons.filter(person => person.online).map((person, index) => {
           return (
-              <div key={person.name} className="person" id={person.name} data-status={person.speed>0 ? "online" : "offline"} onClick={addEventlistener(person.name)}>
+              <div key={person.name} className="person" id={person.name} data-status={person.online ? "online" : "offline"} onClick={addEventlistener(person.name)}>
                   {person.longitude}-{person.latitude}-
                   <div className='rank'>{index + 1}</div>
                   <div className='color' style={{backgroundColor: person.color}}>&nbsp;</div>
@@ -39,23 +39,23 @@ function Tables({persons}) {
                     <img src='foto.png' alt={person.fullName}/>
                     <p>{person.fullName}</p>
                     <p>Geschwindigkeit: {person.speed}</p>
-                    <p>Status: {person.speed>0 ? "online" : "offline"}</p>
+                    <p>Status: {person.online ? "online" : "offline"}</p>
                   </div>
               </div>
           );
         })}
       </div> 
       <div id="offline">
-        {sortedpersons.filter(person => person.longitude===null).map(person => {
+        {sortedpersons.filter(person => !person.online).map(person => {
           return (
-              <div key={person.name} className="person" id={person.name} data-status={person.speed>0 ? "online" : "offline"} onClick={addEventlistener(person.name)}>
+              <div key={person.name} className="person" id={person.name} data-status={person.online ? "online" : "offline"} onClick={addEventlistener(person.name)}>
                   <div className='color' style={{backgroundColor: person.color}}>&nbsp;</div>
                   {person.shortName}
                   <div className='speed'>OUT</div>
                   <div className='extend'> 
                     <img src='foto.png' alt={person.fullName}/>
                     <p>{person.fullName}</p>
-                    <p>Status: {person.speed>0 ? "online" : "offline"}</p>
+                    <p>Status: {person.online ? "online" : "offline"}</p>
                   </div>
               </div>
           );

+ 6 - 13
src/database_interface.py

@@ -1,6 +1,7 @@
 from pymongo import MongoClient
 from flask import Flask, request
 from pprint import pprint
+import time 
 
 app = Flask(__name__)
 
@@ -27,21 +28,11 @@ def get_users():
             "timestamp": { "$first": "$timestamp" },
             "longitude": { "$first": "$longitude" },
             "latitude": { "$first": "$latitude" }
-        }},
-        # { "$lookup": {
-        #     "from":  "user", 
-        #     "localField": "_id", 
-        #     "foreignField": "name", 
-        #     "as": "mergedDict"
-        # }},
-        # {
-        #     "$replaceRoot": { "newRoot": { "$mergeObjects": [ { "$arrayElemAt": [ "$mergedDict", 0 ] }, "$$ROOT" ] } }
-        # },
-        # {   "$project": { "mergedDict": 0 } }
+        }}
     ]
-    # pprint(list(location.aggregate(pipeline)))
     
     lastLocations = list(location.aggregate(pipeline))
+
     users = list(user.find({}, {'_id': False}))
     for u in users:
         for userLoc in lastLocations:
@@ -50,7 +41,9 @@ def get_users():
         if "longitude" not in u:
             u["longitude"] = None
         if "latitude" not in u:
-            u["latitude"] = None    
+            u["latitude"] = None
+        
+        u["online"] = "timestamp" in u and (time.time() - u["timestamp"])<30
     
     return {"users": users}