Jelajahi Sumber

Upload of GPS Pos data works.

Thomas Chef 3 tahun lalu
induk
melakukan
6169476b7c

+ 0 - 5
app/src/main/java/com/flacksta/chef/journeygpstracker/MainActivity.kt

@@ -83,11 +83,6 @@ class MainActivity : AppCompatActivity() {
         mTrackingService = TrackingService()
         mTrackingServiceIntent = Intent(this, mTrackingService.javaClass)
         startForegroundService(mTrackingServiceIntent)
-
-        // Testing with Http POST:
-        val bec:BackendClient = BackendClient()
-        bec.rawJSON()
-
     }
 
     private fun loadFragment(fragment: Fragment) {

+ 6 - 1
app/src/main/java/com/flacksta/chef/journeygpstracker/TrackingService.kt

@@ -14,6 +14,7 @@ import android.util.Log
 import androidx.core.app.ActivityCompat
 import androidx.core.app.NotificationCompat
 import androidx.core.content.ContextCompat
+import com.flacksta.chef.journeygpstracker.backend.BackendClient
 import com.flacksta.chef.journeygpstracker.database.GpsData
 import com.flacksta.chef.journeygpstracker.database.GpsPosRepository
 import com.google.android.gms.location.*
@@ -39,11 +40,15 @@ class TrackingService : Service() {
         generateForegroundNotification()
         trackApp = JourneyGpsTrackerApplication()
         startForeground(mNotificationId, notification)
+
+        // Start background upload functions...
+        val bec: BackendClient = BackendClient()
+
         Log.i(mTag,"Requested foreground service...")
     }
 
     private fun insertPos(pos: Location) = GlobalScope.launch {
-        var d = GpsData(0, System.currentTimeMillis(), pos.latitude, pos.longitude, pos.accuracy)
+        var d = GpsData(0, pos.time, pos.latitude, pos.longitude, pos.accuracy, false)
         val repo: GpsPosRepository = trackApp.repository
         repo.insert(d)
     }

+ 68 - 53
app/src/main/java/com/flacksta/chef/journeygpstracker/backend/BackendClient.kt

@@ -1,25 +1,68 @@
 package com.flacksta.chef.journeygpstracker.backend
 
+import android.os.CountDownTimer
 import android.util.Log
+import com.flacksta.chef.journeygpstracker.JourneyGpsTrackerApplication
+import com.flacksta.chef.journeygpstracker.database.GpsData
 import com.google.gson.GsonBuilder
 import com.google.gson.JsonParser
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
+import kotlinx.coroutines.*
 import okhttp3.MediaType.Companion.toMediaTypeOrNull
 import okhttp3.RequestBody.Companion.toRequestBody
 import org.json.JSONArray
 import org.json.JSONObject
 import retrofit2.Retrofit
+import java.text.SimpleDateFormat
+import kotlin.concurrent.fixedRateTimer
 
 
+// HTTP Post stuff:
 // Info: https://johncodeos.com/how-to-make-post-get-put-and-delete-requests-with-retrofit-using-kotlin/
 
 class BackendClient {
 
-    public fun rawJSON() {
+    private lateinit var trackApp : JourneyGpsTrackerApplication
 
+    init {
+        trackApp = JourneyGpsTrackerApplication()
+        startTimer()
+    }
+
+    fun startTimer() {
+        val fixedRateTimer = fixedRateTimer(name = "hello-timer",
+                initialDelay = 10000, period = 30000) {
+
+            Log.i("Thc","Sending data....")
+            val pos : List<GpsData> = trackApp.database.gpsDataDao().getUnsentGpsPositions()
+            val rawJson:String = convertPosListToRawJson(pos)
+            Log.i("Thc","Count:" + rawJson)
+            Log.i("Thc","Thread A:"+Thread.currentThread())
+            val retVal:Boolean = sendGpsPosDataToBackendServer(rawJson)
+            Log.i("Thc","retVal post: $retVal")
+        }
+    }
+
+    fun convertPosListToRawJson(pos:List<GpsData>) : String {
+
+        val ja = JSONArray()
+
+        val simpleDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
+
+        for (p in pos) {
+            Log.i("Thc","Acc:" + p.accuracy)
+            var jo = JSONObject()
+            jo.put("latitude", p.latitude.toString())
+            jo.put("longitude", p.longitude.toString())
+            jo.put("ts", simpleDate.format(p.ts))
+            jo.put("horizAcc", p.accuracy.toString())
+            ja.put(jo)
+        }
+        return ja.toString()
+    }
+
+    fun sendGpsPosDataToBackendServer(jsonObjectString: String): Boolean = runBlocking() {
+
+        Log.i("Thc", "main runBlocking      : I'm working in thread ${Thread.currentThread().name}")
         // Create Retrofit
         val retrofit = Retrofit.Builder()
                 .baseUrl("http://chef.maya.se/gpsapi/") //registerGPSlocation.php")
@@ -28,60 +71,32 @@ class BackendClient {
         // Create Service
         val service = retrofit.create(BackendAPI::class.java)
 
-        /* From the IPhone version
-        struct GPS_POS_LOG: Codable {
-            var latitude: Double
-            var longitude: Double
-            var ts: String
-            var horizAcc: Int32
-        }*/
-
-        // Create JSON using JSONObject
-        val jsonObject = JSONObject()
-        jsonObject.put("name", "Jack")
-        jsonObject.put("salary", "3540")
-        jsonObject.put("age", "23")
-
-        val jo = JSONObject()
-        jo.put("latitude", "2.3")
-        jo.put("longitude", "2.4")
-        jo.put("ts", "2017-08-02T14:15:01")
-        jo.put("horizAcc", "67")
-
-        val ja = JSONArray()
-        ja.put(jo)
-        ja.put(jo)
-
-        // Convert JSONObject to String
-        var jsonObjectString = ja.toString()
-
         // Create RequestBody ( We're not using any converter, like GsonConverter, MoshiConverter e.t.c, that's why we use RequestBody )
         val requestBody = jsonObjectString.toRequestBody("application/json".toMediaTypeOrNull())
 
-        CoroutineScope(Dispatchers.IO).launch {
-            // Do the POST request and get response
-            val response = service.uploadGPSPositions(requestBody)
+        var retVal: Boolean = false
 
-            withContext(Dispatchers.Main) {
-                if (response.isSuccessful) {
+        // Do the POST request and get response
+        val response = service.uploadGPSPositions(requestBody)
+        Log.i("Thc", "Thread C:" + Thread.currentThread())
 
-                    // Convert raw JSON to pretty JSON using GSON library
-                    val gson = GsonBuilder().setPrettyPrinting().create()
-                    val prettyJson = gson.toJson(
-                            JsonParser.parseString(
-                                    response.body()
-                                            ?.string() // About this thread blocking annotation : https://github.com/square/retrofit/issues/3255
-                            )
-                    )
-                    Log.i("Thc", "HTTP Reply: $prettyJson")
+        if (response.isSuccessful) {
 
-
-                } else {
-
-                    Log.e("Thc","RETROFIT_ERROR:" + response.code().toString())
-
-                }
-            }
+            // Convert raw JSON to pretty JSON using GSON library
+            val gson = GsonBuilder().setPrettyPrinting().create()
+            val prettyJson = gson.toJson(
+                    JsonParser.parseString(
+                            response.body()
+                                    ?.string() // About this thread blocking annotation : https://github.com/square/retrofit/issues/3255
+                    )
+            )
+            Log.i("Thc", "HTTP Reply: $prettyJson")
+            Log.i("Thc", "Thread B:" + Thread.currentThread())
+            retVal = true
+        } else {
+            Log.e("Thc", "RETROFIT_ERROR:" + response.code().toString())
         }
+
+        retVal
     }
 }

+ 1 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/database/GpsData.kt

@@ -11,4 +11,5 @@ data class GpsData(
         @ColumnInfo(name = "latitude") val latitude: Double,
         @ColumnInfo(name = "longitude") val longitude: Double,
         @ColumnInfo(name = "accuracy") val accuracy: Float,
+        @ColumnInfo(name = "uploaded", defaultValue="False") val uploaded: Boolean
 )

+ 2 - 2
app/src/main/java/com/flacksta/chef/journeygpstracker/database/GpsDataDao.kt

@@ -9,8 +9,8 @@ import kotlinx.coroutines.flow.Flow
 @Dao
 interface GpsDataDao {
 
-    @Query("SELECT * FROM pos_table ORDER BY ts ASC")
-    fun getGpsPositions(): Flow<List<GpsData>>
+    @Query("SELECT * FROM pos_table where uploaded == 0 ORDER BY ts ASC")
+    fun getUnsentGpsPositions(): List<GpsData>
 
     @Insert(onConflict = OnConflictStrategy.IGNORE)
     suspend fun insert(gpsPos: GpsData)

+ 0 - 2
app/src/main/java/com/flacksta/chef/journeygpstracker/database/GpsPosRepository.kt

@@ -6,8 +6,6 @@ import kotlinx.coroutines.flow.Flow
 
 class GpsPosRepository(private val gpsDataDao: GpsDataDao) {
 
-    val allGpsData: Flow<List<GpsData>> = gpsDataDao.getGpsPositions()
-
     @Suppress("RedundantSuspendModifier")
     @WorkerThread
     suspend fun insert(word: GpsData) {

+ 1 - 1
app/src/main/java/com/flacksta/chef/journeygpstracker/database/GpsPosRoomDatabase.kt

@@ -10,7 +10,7 @@ import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.Dispatchers
 import kotlinx.coroutines.launch
 
-@Database(entities = [GpsData::class], version = 1, exportSchema = false)
+@Database(entities = [GpsData::class], version = 2, exportSchema = false)
 public abstract class GpsPosRoomDatabase : RoomDatabase() {