Kaynağa Gözat

added mongodb and python database interface

Bernadette Elena Hammerle 4 yıl önce
ebeveyn
işleme
da05968a11
3 değiştirilmiş dosya ile 121 ekleme ve 15 silme
  1. 25 13
      src/App.js
  2. 2 2
      src/Tables.js
  3. 94 0
      src/database_interface.py

+ 25 - 13
src/App.js

@@ -17,7 +17,8 @@ class App extends Component {
 
   // is called once when loading the page
   componentDidMount() {
-      fetch("http://192.168.8.100:3001/persons")
+      //fetch("http://192.168.8.100:3001/persons")
+      fetch("http://localhost:5000/users")
       .then(response => {
           if (response.ok) {
                   return response;
@@ -29,8 +30,8 @@ class App extends Component {
       })
       .then(response => response.json())
       .then(json =>{
-         console.log(json);
-         this.setState({ persons: json })
+         console.log(json["users"]);
+         this.setState({ persons: json["users"] })
       }).catch(error => {
         console.log(error);
     });
@@ -38,7 +39,7 @@ class App extends Component {
   }
 
 
-  change = () => {
+  /*change = () => {
     const newPersons = [...this.state.persons];
     const id = 0;
     newPersons.map( person => {
@@ -47,7 +48,8 @@ class App extends Component {
         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://192.168.8.100:3001/persons/0/', {
+        axios.put('http://localhost:3001/persons/0/', {
             longitude: longitude,
             latitude: latitude,
             shortName: "VEN",
@@ -62,14 +64,25 @@ class App extends Component {
     })
     this.componentDidMount()
     
-  }
+  }*/
   
   getLocation = (name) => {
+    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
@@ -82,11 +95,9 @@ class App extends Component {
   }
   
   
-  getAttribute = (id, attr) => {
 
-  }
   
-  create = (id) => {
+  /*create = (id) => {
     const axios = require('axios');
     let longitude = Math.floor((Math.random() * 100) + 1);
     let latitude = Math.floor((Math.random() * 100) + 1);
@@ -100,6 +111,7 @@ class App extends Component {
         })
       };   
 
+    //axios.put('http://localhost:3001/persons/0/', {
     axios.put('http://localhost:3001/persons/0/', {
         longitude: longitude,
         latitude: latitude,
@@ -110,10 +122,10 @@ class App extends Component {
     }).catch(error => {
         console.log(error);
     });
-  }
+  }*/
 
   render (){
-  setTimeout(this.componentDidMount, 10000)
+  //setTimeout(this.componentDidMount, 10000)
         
     return (
       <div id="wrapper">
@@ -121,12 +133,12 @@ class App extends Component {
         <div id="debug"> </div>
         <button
             onClick={ () => {
-              alert(this.getAttribute(2, "name"));
+              this.getLocation("Bernie");
               }}
               > Bernie </button>
         <button
             onClick={ () => {
-              this.change();
+              this.getLocation("Martin");
               }}
               > Martin </button>
         <button

+ 2 - 2
src/Tables.js

@@ -25,7 +25,7 @@ function Tables({persons}) {
         <p>{currentDate.getDate()}.{currentDate.getMonth() + 1}.{currentDate.getFullYear()}</p>
       </div>
       <div id="online">
-        {sortedpersons.filter(person => person.speed>0).map((person, index) => {
+        {sortedpersons.filter(person => person.longitude!=null).map((person, index) => {
           return (
               <div key={person.name} className="person" id={person.name} data-status={person.speed>0 ? "online" : "offline"} onClick={addEventlistener(person.name)}>
                   {person.longitude}-{person.latitude}-
@@ -46,7 +46,7 @@ function Tables({persons}) {
         })}
       </div> 
       <div id="offline">
-        {sortedpersons.filter(person => person.speed<1).map(person => {
+        {sortedpersons.filter(person => person.longitude===null).map(person => {
           return (
               <div key={person.name} className="person" id={person.name} data-status={person.speed>0 ? "online" : "offline"} onClick={addEventlistener(person.name)}>
                   <div className='color' style={{backgroundColor: person.color}}>&nbsp;</div>

+ 94 - 0
src/database_interface.py

@@ -0,0 +1,94 @@
+from pymongo import MongoClient
+from flask import Flask, request
+from pprint import pprint
+
+app = Flask(__name__)
+
+client = MongoClient("192.168.17.90", 27017)
+db = client["react_database"]
+user = db["user"]
+location = db["location"]
+
+
+@app.route("/report-location", methods=["PUT"])
+def report_location():
+    gpsData = request.json
+    location.insert_one(gpsData)
+    
+    return ('', 204)
+
+@app.route("/users", methods=["GET"])
+def get_users():
+    
+    pipeline = [
+        { "$sort": { "name": 1, "timestamp": -1 } },
+        { "$group": {
+            "_id": "$name",
+            "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:
+            if u["name"]==userLoc["_id"]:
+                u.update(userLoc)
+        if "longitude" not in u:
+            u["longitude"] = None
+        if "latitude" not in u:
+            u["latitude"] = None    
+    
+    return {"users": users}
+
+@app.after_request
+def after_request(response):
+    response.headers.add('Access-Control-Allow-Origin', '*')
+    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
+    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
+    return response
+
+
+if __name__=="__main__":
+    if user.find().count()<3:
+        user.insert_many([
+            {
+              "shortName": "VEN",
+              "fullName": "Martin Venzl",
+              "name": "Martin",
+              "color": "#ddd",
+            },
+            {
+              "name": "Simon",
+              "fullName": "Simon Ellinger",
+              "shortName": "ELL",
+              "color": "#ffff00"
+            },
+            {
+              "name": "Lukas",
+              "fullName": "Lukas Wagner",
+              "shortName": "WAG",
+              "color": "#00ff00"
+            },
+            {
+              "name": "Bernie",
+              "fullName": "Bernadette Hammerle",
+              "shortName": "HAM",
+              "color": "#888822"
+            }
+        ])
+    
+    app.run()