فهرست منبع

@task: download map

bai 3 سال پیش
والد
کامیت
5ba4cd968c
25فایلهای تغییر یافته به همراه327 افزوده شده و 68 حذف شده
  1. 4 2
      demo/build.gradle
  2. 3 0
      demo/src/main/AndroidManifest.xml
  3. 5 1
      demo/src/main/java/com/framework/app/Constants.kt
  4. 7 4
      demo/src/main/java/com/framework/app/api/Api.kt
  5. 82 0
      demo/src/main/java/com/framework/app/tools/MacUtil.kt
  6. 12 2
      demo/src/main/java/com/framework/di/Di.kt
  7. 3 0
      demo/src/main/java/com/framework/mvvm/model/db/dao/FileDao.kt
  8. 10 1
      demo/src/main/java/com/framework/mvvm/model/db/dao/ObjectDao.kt
  9. 4 1
      demo/src/main/java/com/framework/mvvm/model/db/dao/PipeDao.kt
  10. 3 0
      demo/src/main/java/com/framework/mvvm/model/db/dao/ProblemArchDao.kt
  11. 4 0
      demo/src/main/java/com/framework/mvvm/model/db/dao/ProblemEquipDao.kt
  12. 3 0
      demo/src/main/java/com/framework/mvvm/model/db/dao/QrCodeDao.kt
  13. 3 0
      demo/src/main/java/com/framework/mvvm/model/db/dao/RelationDao.kt
  14. 3 0
      demo/src/main/java/com/framework/mvvm/model/db/dao/SpaceDao.kt
  15. 2 0
      demo/src/main/java/com/framework/mvvm/model/db/entity/PipeEntity.kt
  16. 2 0
      demo/src/main/java/com/framework/mvvm/model/db/entity/ProblemArchEntity.kt
  17. 2 0
      demo/src/main/java/com/framework/mvvm/model/db/entity/ProblemEquipEntity.kt
  18. 52 5
      demo/src/main/java/com/framework/mvvm/model/repository/AdmRepository.kt
  19. 6 4
      demo/src/main/java/com/framework/mvvm/model/vo/AdmRequest.kt
  20. 4 2
      demo/src/main/java/com/framework/mvvm/model/vo/Building.kt
  21. 6 6
      demo/src/main/java/com/framework/mvvm/model/vo/FloorInfo.kt
  22. 10 0
      demo/src/main/java/com/framework/mvvm/model/vo/UploadBuilding.kt
  23. 50 24
      demo/src/main/java/com/framework/mvvm/mv/AdmViewModel.kt
  24. 2 0
      demo/src/main/java/com/sybotan/android/demo/DemoApp.kt
  25. 45 16
      demo/src/main/java/com/sybotan/android/demo/activities/PocActivity.kt

+ 4 - 2
demo/build.gradle

@@ -221,7 +221,9 @@ dependencies {
     implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
 
     implementation 'org.kodein.di:kodein-di:7.8.0'
+
     //implementation 'org.kodein.di:kodein-di-framework-android-support:7.8.0'
+    implementation 'org.kodein.di:kodein-di-framework-android-core:7.8.0'
     implementation 'org.kodein.di:kodein-di-framework-android-x:7.8.0'
     implementation 'org.kodein.di:kodein-di-framework-android-x-viewmodel:7.8.0'
 
@@ -249,8 +251,8 @@ dependencies {
     })
 
     // lifecycle
-    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
-    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
+    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0-rc01'
+    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0-rc01'
     implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0-rc01'
     implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
     implementation 'com.squareup.okhttp3:logging-interceptor:3.14.4'

+ 3 - 0
demo/src/main/AndroidManifest.xml

@@ -7,10 +7,13 @@
     <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.BLUETOOTH" /> <!-- SD卡中创建与删除文件权限 -->
+    <uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS" />
     <uses-permission
         android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
         tools:ignore="ProtectedPermissions" /> <!-- 向SDCard写入数据权限 -->
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
+        tools:ignore="ProtectedPermissions" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 摄像头 -->
     <uses-permission android:name="android.permission.CAMERA" />
     <uses-permission android:name="android.permission.CALL_PHONE" />

+ 5 - 1
demo/src/main/java/com/framework/app/Constants.kt

@@ -5,4 +5,8 @@ package com.framework.app
  */
 const val testIP = "http://192.168.0.48:8876/"
 
-const val pathDownloadMap = "adm/downloadMap?key="
+const val tencentIP = "http://82.157.28.170:8876/"
+
+const val pathDownloadMap = "adm/downloadMap?key="
+
+const val deviceId = "device_id"

+ 7 - 4
demo/src/main/java/com/framework/app/api/Api.kt

@@ -1,10 +1,7 @@
 package com.framework.app.api
 
 import com.framework.mvvm.model.data.Model
-import com.framework.mvvm.model.vo.AdmRequest
-import com.framework.mvvm.model.vo.Building
-import com.framework.mvvm.model.vo.Dict
-import com.framework.mvvm.model.vo.Frame
+import com.framework.mvvm.model.vo.*
 import retrofit2.http.Body
 import retrofit2.http.POST
 
@@ -26,5 +23,11 @@ interface Api {
      */
     @POST("adm/download")
     suspend fun getBuilding(@Body request: AdmRequest): Model<Building>
+
+    /**
+     * 上传建筑数据
+     */
+    @POST("adm/upload")
+    suspend fun uploadBuilding(@Body building: UploadBuilding): Model<Building>
 }
 

+ 82 - 0
demo/src/main/java/com/framework/app/tools/MacUtil.kt

@@ -0,0 +1,82 @@
+package com.framework.app.tools
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.content.Context
+import android.content.pm.PackageManager
+import android.net.wifi.WifiManager
+import android.os.Build
+import android.text.TextUtils
+import androidx.core.content.ContextCompat
+import com.framework.app.tools.MacUtil
+import java.lang.StringBuilder
+import java.net.NetworkInterface
+import java.net.SocketException
+
+/**
+ * Created by weimo on 2020/7/13.
+ */
+object MacUtil {
+    @SuppressLint("HardwareIds")
+    fun getMacAddress(context: Context): String? {
+        if (Build.VERSION.SDK_INT >= 23) {
+            val str = getMacMoreThanM(context)
+            if (!TextUtils.isEmpty(str)) {
+                return str
+            }
+        } else {
+            if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_WIFI_STATE)
+                == PackageManager.PERMISSION_GRANTED
+            ) {
+                val wifiManager = context.applicationContext
+                    .getSystemService(Context.WIFI_SERVICE) as WifiManager
+                if (null != wifiManager) {
+                    return wifiManager.connectionInfo.macAddress
+                }
+            }
+        }
+        return null
+    }
+
+    /**
+     * android 6.0+获取wifi的mac地址
+     * @param paramContext
+     * @return
+     */
+    private fun getMacMoreThanM(paramContext: Context): String? {
+        try {
+            //获取本机器所有的网络接口
+            val enumeration = NetworkInterface.getNetworkInterfaces()
+            while (enumeration.hasMoreElements()) {
+                val networkInterface = enumeration.nextElement()
+                //获取硬件地址,一般是MAC
+                val arrayOfByte = networkInterface.hardwareAddress
+                if (arrayOfByte == null || arrayOfByte.size == 0) {
+                    continue
+                }
+                val stringBuilder = StringBuilder()
+                for (b in arrayOfByte) {
+                    //格式化为:两位十六进制加冒号的格式,若是不足两位,补0
+                    stringBuilder.append(
+                        String.format(
+                            "%02X:",
+                            *arrayOf<Any>(java.lang.Byte.valueOf(b))
+                        )
+                    )
+                }
+                if (stringBuilder.length > 0) {
+                    //删除后面多余的冒号
+                    stringBuilder.deleteCharAt(stringBuilder.length - 1)
+                }
+                val str = stringBuilder.toString()
+                // wlan0:无线网卡 eth0:以太网卡
+                if (networkInterface.name == "wlan0") {
+                    return str
+                }
+            }
+        } catch (socketException: SocketException) {
+            return null
+        }
+        return null
+    }
+}

+ 12 - 2
demo/src/main/java/com/framework/di/Di.kt

@@ -1,7 +1,9 @@
 package com.framework.di
 
+import android.content.Context
 import android.util.Log
 import com.framework.app.api.Api
+import com.framework.app.tencentIP
 import com.framework.mvvm.model.db.AdmDatabase
 import com.framework.mvvm.model.repository.AdmRepository
 import com.framework.mvvm.mv.AdmViewModel
@@ -20,7 +22,7 @@ val httpModule = DI.Module("netModule") {
     bind {
         singleton {
             Retrofit.Builder()
-                .baseUrl("http://192.168.0.48:8876/")
+                .baseUrl(tencentIP)
                 .client(instance())
                 .addConverterFactory(GsonConverterFactory.create())
                 .build()
@@ -59,13 +61,21 @@ val httpModule = DI.Module("netModule") {
 }
 
 val repositoryModule = DI.Module("repository") {
-    bindSingleton { AdmRepository(instance(), instance()) }
+    bindSingleton { AdmRepository(instance(), instance(), instance()) }
 }
 
 val viewModelModule = DI.Module("viewModel") {
     bindProvider { AdmViewModel(instance()) }
 }
 
+val androidModule = DI.Module("sys") {
+    bindSingleton {
+        instance<Context>().getSharedPreferences(
+            "adm_sp",
+            Context.MODE_PRIVATE
+        )
+    }
+}
 val databaseModule = DI.Module("database") {
     bindSingleton {
         AdmDatabase.getDatabase(instance())

+ 3 - 0
demo/src/main/java/com/framework/mvvm/model/db/dao/FileDao.kt

@@ -17,6 +17,9 @@ interface FileDao {
     @Query("select * from file where ref_obj_id = :id")
     suspend fun getFileByRefId(id: String): List<FileEntity>
 
+    @Query("select * from file where building_id = :id")
+    suspend fun getFileByBuildingId(id: String): List<FileEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insFile(vararg file: FileEntity)
 

+ 10 - 1
demo/src/main/java/com/framework/mvvm/model/db/dao/ObjectDao.kt

@@ -20,6 +20,9 @@ interface ObjectDao {
     @Query("select * from object where building_id = :buildingId and obj_type=:type")
     suspend fun getObjectByBuildingId(buildingId: String, type: String): List<ObjectEntity>
 
+    @Query("select * from object where building_id = :buildingId")
+    suspend fun getObjectByBuildingId(buildingId: String): List<ObjectEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insObject(vararg obj: ObjectEntity)
 
@@ -36,10 +39,16 @@ interface ObjectDao {
     suspend fun getFloors(): List<ObjectEntity>
 
     /**
+     * 返回所有建筑 ObjectEntity
+     */
+    @Query("select * from object where obj_type = 'building'")
+    suspend fun getBuildings(): List<ObjectEntity>
+
+    /**
      * 更新 ObjectEntity
      */
     @Update
-    suspend fun upObject(obj: ObjectEntity)
+    suspend fun updateObject(obj: ObjectEntity)
 
     // @Transaction
     // @Query("select * from object")

+ 4 - 1
demo/src/main/java/com/framework/mvvm/model/db/dao/PipeDao.kt

@@ -15,11 +15,14 @@ interface PipeDao {
     @Query("select * from pipe where id = :id")
     suspend fun getPipeById(id: String): PipeEntity
 
+    @Query("select * from pipe where building_id = :id")
+    suspend fun getPipeByBuildingId(id: String): List<PipeEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insPipe(vararg pipe: PipeEntity)
 
     @Insert(onConflict = OnConflictStrategy.REPLACE)
-    suspend fun insPipes(configs: List<PipeEntity>)
+    suspend fun insPipes(pipes: List<PipeEntity>)
 
     @Update
     suspend fun upPipe(pipe: PipeEntity)

+ 3 - 0
demo/src/main/java/com/framework/mvvm/model/db/dao/ProblemArchDao.kt

@@ -14,6 +14,9 @@ interface ProblemArchDao {
     @Query("select * from problem_arch where id = :id")
     suspend fun getProblemById(id: String): ProblemArchEntity
 
+    @Query("select * from problem_arch where building_id = :id")
+    suspend fun getProblemByBuildingId(id: String): List<ProblemArchEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insProblem(problem: ProblemArchEntity)
 

+ 4 - 0
demo/src/main/java/com/framework/mvvm/model/db/dao/ProblemEquipDao.kt

@@ -1,6 +1,7 @@
 package com.framework.mvvm.model.db.dao
 
 import androidx.room.*
+import com.framework.mvvm.model.db.entity.ProblemArchEntity
 import com.framework.mvvm.model.db.entity.ProblemEquipEntity
 
 /**
@@ -14,6 +15,9 @@ interface ProblemEquipDao {
     @Query("select * from problem_equip where id = :id")
     suspend fun getProblemById(id: String): ProblemEquipEntity
 
+    @Query("select * from problem_equip where building_id = :id")
+    suspend fun getProblemByBuildingId(id: String): List<ProblemEquipEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insProblem(vararg problem: ProblemEquipEntity)
 

+ 3 - 0
demo/src/main/java/com/framework/mvvm/model/db/dao/QrCodeDao.kt

@@ -17,6 +17,9 @@ interface QrCodeDao {
     @Query("select * from qr_code where obj_id = :id")
     suspend fun getQrCodeByObjId(id: String): List<QrCodeEntity>
 
+    @Query("select * from qr_code where building_id = :id")
+    suspend fun getQrCodeByBuildingId(id: String): List<QrCodeEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insQrCode(vararg qrCode: QrCodeEntity)
 

+ 3 - 0
demo/src/main/java/com/framework/mvvm/model/db/dao/RelationDao.kt

@@ -14,6 +14,9 @@ interface RelationDao {
     @Query("select * from relation where id = :id")
     suspend fun getRelationById(id: String): RelationEntity
 
+    @Query("select * from relation where building_id = :id")
+    suspend fun getRelationByBuildingId(id: String): List<RelationEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insRelation(vararg relation: RelationEntity)
 

+ 3 - 0
demo/src/main/java/com/framework/mvvm/model/db/dao/SpaceDao.kt

@@ -23,6 +23,9 @@ interface SpaceDao {
     @Query("select * from space where floor_id = :id and equip_state =:equipState")
     suspend fun getSpaceByEquipStateFloorId(id: String, equipState: String): List<SpaceEntity>
 
+    @Query("select * from space where building_id = :id")
+    suspend fun getSpaceByBuildingId(id: String): List<SpaceEntity>
+
     @Insert(onConflict = OnConflictStrategy.REPLACE)
     suspend fun insSpace(vararg space: SpaceEntity)
 

+ 2 - 0
demo/src/main/java/com/framework/mvvm/model/db/entity/PipeEntity.kt

@@ -3,11 +3,13 @@ package com.framework.mvvm.model.db.entity
 import androidx.room.ColumnInfo
 import androidx.room.Entity
 import androidx.room.PrimaryKey
+import kotlinx.serialization.Serializable
 
 /**
  * 管道表
  */
 @Entity(tableName = "pipe")
+@Serializable
 data class PipeEntity(
     @PrimaryKey val id: String,
     @ColumnInfo(name = "floor_id") val floorId: String?,              // 楼层id

+ 2 - 0
demo/src/main/java/com/framework/mvvm/model/db/entity/ProblemArchEntity.kt

@@ -3,11 +3,13 @@ package com.framework.mvvm.model.db.entity
 import androidx.room.ColumnInfo
 import androidx.room.Entity
 import androidx.room.PrimaryKey
+import kotlinx.serialization.Serializable
 
 /**
  * 结构问题  表
  */
 @Entity(tableName = "problem_arch")
+@Serializable
 data class ProblemArchEntity(
     @PrimaryKey val id: String,
     @ColumnInfo(name = "floor_id") val floorId: String,            // 问题所在楼层id

+ 2 - 0
demo/src/main/java/com/framework/mvvm/model/db/entity/ProblemEquipEntity.kt

@@ -3,11 +3,13 @@ package com.framework.mvvm.model.db.entity
 import androidx.room.ColumnInfo
 import androidx.room.Entity
 import androidx.room.PrimaryKey
+import kotlinx.serialization.Serializable
 
 /**
  * 设备问题 表
  */
 @Entity(tableName = "problem_equip")
+@Serializable
 data class ProblemEquipEntity(
     @PrimaryKey val id: String,
     @ColumnInfo(name = "floor_id") val floorId: String,            // 问题所在楼层id

+ 52 - 5
demo/src/main/java/com/framework/mvvm/model/repository/AdmRepository.kt

@@ -1,19 +1,24 @@
 package com.framework.mvvm.model.repository
 
+import android.content.SharedPreferences
 import android.util.Log
 import androidx.lifecycle.LiveData
 import com.framework.app.api.Api
 import com.framework.app.base.IRepository
 import com.framework.mvvm.model.data.Data
+import com.framework.mvvm.model.data.Response
 import com.framework.mvvm.model.data.dataSource
 import com.framework.mvvm.model.data.request
 import com.framework.mvvm.model.db.AdmDatabase
 import com.framework.mvvm.model.db.entity.*
 import com.framework.mvvm.model.vo.AdmRequest
+import com.framework.mvvm.model.vo.Building
+import com.framework.mvvm.model.vo.UploadBuilding
 
 class AdmRepository(
     private val api: Api,
-    private val db: AdmDatabase
+    private val db: AdmDatabase,
+    private val sp: SharedPreferences
 ) : IRepository {
 
     fun getProjects(request: AdmRequest): LiveData<Data<List<ProjectEntity>>> {
@@ -181,7 +186,7 @@ class AdmRepository(
                 val problemEquip = building.problemEquip
                 val qrCode = building.qrCode
                 val relations = building.relations
-
+                val pipes = building.pipes
                 try {
                     db.fileDao().insFiles(file)
                     db.spaceDao().insSpaces(space)
@@ -190,9 +195,10 @@ class AdmRepository(
                     db.problemEquipDao().insProblems(problemEquip)
                     db.qrCodeDao().insQrCodes(qrCode)
                     db.relationDao().insRelations(relations)
+                    db.pipeDao().insPipes(pipes)
                 } catch (e: Exception) {
                     Log.d(
-                        "FrameRepositoryFrameRepository",
+                        "AdmRepository requestBuilding",
                         e.message ?: "requestBuilding has error"
                     )
                 }
@@ -207,10 +213,51 @@ class AdmRepository(
         return db.objectDao().getFloors()
     }
 
+
+    /**
+     * 返回建筑
+     */
+    suspend fun getBuildings(): List<ObjectEntity> {
+        return db.objectDao().getBuildings()
+    }
+
     /**
      * 更新 ObjectEntity
      */
-    suspend fun upObject(obj: ObjectEntity) {
-        db.objectDao().upObject(obj)
+    suspend fun updateObject(obj: ObjectEntity) {
+        db.objectDao().updateObject(obj)
+    }
+
+    suspend fun uploadBuilding(buildingId: String): Response<Building> {
+        val pipes = db.pipeDao().getPipeByBuildingId(buildingId)
+        val files = db.fileDao().getFileByBuildingId(buildingId)
+        val spaces = db.spaceDao().getSpaceByBuildingId(buildingId)
+        val qrCodes = db.qrCodeDao().getQrCodeByBuildingId(buildingId)
+        val objects = db.objectDao().getObjectByBuildingId(buildingId)
+        val relations = db.relationDao().getRelationByBuildingId(buildingId)
+        val problemArchs = db.problemArchDao().getProblemByBuildingId(buildingId)
+        val problemEquips = db.problemEquipDao().getProblemByBuildingId(buildingId)
+
+        val deviceId = sp.getString("deviceId", "") ?: ""
+        val projectId = objects[0].projectId
+        val building = Building(
+            buildingId = buildingId,
+            file = files,
+            qrCode = qrCodes,
+            objects = objects,
+            jobSpace = spaces,
+            relations = relations,
+            problemArch = problemArchs,
+            problemEquip = problemEquips,
+            pipes = pipes
+        )
+
+        val uploadBuilding = UploadBuilding(
+            projectId = projectId,
+            uploadFlag = deviceId,
+            uploadData = building
+        )
+
+        return request { api.uploadBuilding(uploadBuilding) }
     }
 }

+ 6 - 4
demo/src/main/java/com/framework/mvvm/model/vo/AdmRequest.kt

@@ -1,11 +1,13 @@
 package com.framework.mvvm.model.vo
 
+import kotlinx.serialization.SerialName
 import kotlinx.serialization.Serializable
 
 @Serializable
 data class AdmRequest(
-    val userId: String = "",
-    val projectId: String = "",
-    val groupCode: String = "",
-    val buildingId: String = ""
+    val userId: String = "",      // 用户id
+    val projectId: String = "",   // 项目Id
+    val groupCode: String = "",   // 集团代码
+    val buildingId: String = "",  // 建筑id
+    val uploadFlag: String = ""   // 设备唯一标识
 )

+ 4 - 2
demo/src/main/java/com/framework/mvvm/model/vo/Building.kt

@@ -1,18 +1,20 @@
 package com.framework.mvvm.model.vo
 
 import com.framework.mvvm.model.db.entity.*
+import kotlinx.serialization.Serializable
 
 /**
  * Building 对象
  */
+@Serializable
 data class Building(
     val buildingId: String,
-    val timestamp: String,
     val jobSpace: List<SpaceEntity>, // outline 需要处理
     val objects: List<ObjectEntity>,
     val file: List<FileEntity>,
     val qrCode: List<QrCodeEntity>,
     val relations: List<RelationEntity>,
     val problemArch: List<ProblemArchEntity>,
-    val problemEquip: List<ProblemEquipEntity>
+    val problemEquip: List<ProblemEquipEntity>,
+    val pipes: List<PipeEntity>,
 )

+ 6 - 6
demo/src/main/java/com/framework/mvvm/model/vo/FloorInfo.kt

@@ -7,11 +7,11 @@ import kotlinx.serialization.Serializable
  */
 @Serializable
 data class FloorInfo(
-    val count: String?,
-    val modelId: String?,
-    val bimIdPre: String?,
-    val floorMap: String?,          // 楼层地图
-    val floorElevation: Double,
-    val floorSequenceID: Double,
+    val count: String? = "0",
+    val modelId: String? = "",
+    val bimIdPre: String? = "",
+    val floorMap: String? = "",          // 楼层地图
+    val floorElevation: Double = 0.0,
+    val floorSequenceID: Double = 0.0,
     val outline: List<Outline> = ArrayList()
 )

+ 10 - 0
demo/src/main/java/com/framework/mvvm/model/vo/UploadBuilding.kt

@@ -0,0 +1,10 @@
+package com.framework.mvvm.model.vo
+
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class UploadBuilding(
+    val projectId: String,
+    val uploadFlag: String,
+    val uploadData: Building
+)

+ 50 - 24
demo/src/main/java/com/framework/mvvm/mv/AdmViewModel.kt

@@ -1,35 +1,30 @@
 package com.framework.mvvm.mv
 
-import androidx.lifecycle.*
+import android.util.Log
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
 import cn.sagacloud.cadengine.OkhttpUtil
 import com.framework.app.pathDownloadMap
-import com.framework.app.testIP
-import com.framework.mvvm.model.data.AbsentLiveData
-import com.framework.mvvm.model.data.Data
-import com.framework.mvvm.model.db.entity.ProjectEntity
+import com.framework.app.tencentIP
+import com.framework.mvvm.model.data.EmptyResponse
+import com.framework.mvvm.model.data.FailureResponse
+import com.framework.mvvm.model.data.SuccessResponse
+import com.framework.mvvm.model.db.entity.ObjectEntity
 import com.framework.mvvm.model.repository.AdmRepository
 import com.framework.mvvm.model.vo.AdmRequest
 import com.framework.mvvm.model.vo.FloorInfo
 import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.SharingStarted.Companion.WhileSubscribed
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.stateIn
 import kotlinx.coroutines.launch
 import kotlinx.serialization.decodeFromString
 import kotlinx.serialization.json.Json
 
 
 class AdmViewModel(private val repository: AdmRepository) : ViewModel() {
-    private val _frameRequest = MutableLiveData<AdmRequest>()
-
-    private var _projects = MutableLiveData<Data<List<ProjectEntity>>>()
-
-    val projects: LiveData<Data<List<ProjectEntity>>> =
-        Transformations.switchMap(_frameRequest) { request ->
-            if (request == null) {
-                AbsentLiveData.create()
-            } else {
-                repository.getProjects(request)
-            }
-        }
-
+    
     /**
      * 请求架构数据
      */
@@ -39,9 +34,8 @@ class AdmViewModel(private val repository: AdmRepository) : ViewModel() {
         }
     }
 
-
     /**
-     * 请求字典
+     * 请求字典数据
      */
     fun requestDict(request: AdmRequest) {
         viewModelScope.launch {
@@ -50,7 +44,7 @@ class AdmViewModel(private val repository: AdmRepository) : ViewModel() {
     }
 
     /**
-     * 请求建筑
+     * 请求建筑数据
      */
     fun requestBuilding(request: AdmRequest) {
         viewModelScope.launch(Dispatchers.IO) {
@@ -58,19 +52,51 @@ class AdmViewModel(private val repository: AdmRepository) : ViewModel() {
             val floors = repository.getFloors()
             floors.forEach {
                 val strInfo = it.strInfos
-                if (!strInfo.isNullOrEmpty()) {
+                if (!strInfo.isNullOrEmpty() && strInfo.contains("floorMap")) {
                     try {
                         val info = Json.decodeFromString<FloorInfo>(strInfo)
                         val map = info.floorMap
                         val floorMap =
-                            OkhttpUtil.getGzipMap("$testIP$pathDownloadMap${map!!}")
+                            OkhttpUtil.getGzipMap("$tencentIP$pathDownloadMap${map!!}")
                         it.floorMap = floorMap
-                        repository.upObject(it)
+                        repository.updateObject(it)
                     } catch (e: Exception) {
                         println("floor map Exception: $e")
                     }
                 }
             }
+
+            println("floor map over !!!, floors: ${floors.size}")
+        }
+    }
+
+    /**
+     * 上传建筑数据
+     */
+    fun uploadBuilding(buildingId: String) {
+        viewModelScope.launch(Dispatchers.IO) {
+            when (val response = repository.uploadBuilding(buildingId)) {
+                is EmptyResponse -> {
+                    Log.e("AdmViewModel", "uploadBuilding empty")
+                }
+                is FailureResponse -> {
+                    Log.e("AdmViewModel", "uploadBuilding fail:${response.msg}")
+                }
+                is SuccessResponse -> {
+                    Log.e("AdmViewModel", "uploadBuilding success")
+                }
+            }
         }
     }
+
+    /**
+     * 获取建筑数量
+     */
+    val buildings: StateFlow<List<ObjectEntity>> = flow {
+        emit(repository.getBuildings())
+    }.stateIn(
+        scope = viewModelScope,
+        started = WhileSubscribed(5000),
+        initialValue = arrayListOf()
+    )
 }

+ 2 - 0
demo/src/main/java/com/sybotan/android/demo/DemoApp.kt

@@ -40,11 +40,13 @@ import java.io.File
 class DemoApp : Application(), DIAware {
 
     override val di: DI by DI.lazy {
+       // import(androidCoreModule(this@DemoApp))
         import(androidXModule(this@DemoApp))
         import(databaseModule)
         import(httpModule)
         import(repositoryModule)
         import(viewModelModule)
+        import(androidModule)
         //import(factoryModule)
     }
 

+ 45 - 16
demo/src/main/java/com/sybotan/android/demo/activities/PocActivity.kt

@@ -1,31 +1,37 @@
 package com.sybotan.android.demo.activities
 
 import android.Manifest
-import android.accounts.AccountManager
+import android.content.SharedPreferences
 import android.content.pm.PackageManager
 import android.os.Bundle
 import androidx.appcompat.app.AppCompatActivity
 import androidx.constraintlayout.widget.ConstraintLayout
 import androidx.core.app.ActivityCompat
-import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
+import androidx.core.content.edit
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import com.framework.app.tools.MacUtil
 import com.framework.mvvm.model.vo.AdmRequest
 import com.framework.mvvm.mv.AdmViewModel
 import com.sybotan.android.demo.R
 import com.sybotan.android.demo.activities.poc.SceneActivity
 import com.sybotan.android.demo.activities.poc.SpaceActivity
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.launch
 import org.jetbrains.anko.startActivity
 import org.kodein.di.DI
 import org.kodein.di.DIAware
 import org.kodein.di.android.closestDI
 import org.kodein.di.android.x.viewmodel.viewModel
+import org.kodein.di.instance
 
 class PocActivity : AppCompatActivity(), DIAware {
 
     override val di: DI by closestDI()
 
     private val mVm: AdmViewModel by viewModel()
-
-    private val tag = "PocActivity"
+    private val sp: SharedPreferences by instance()
 
     private val REQUEST_EXTERNAL_STORAGE = 1 // 不可改
 
@@ -46,7 +52,7 @@ class PocActivity : AppCompatActivity(), DIAware {
         mVm.requestFrame(
             AdmRequest(
                 userId = "bdtp",
-                projectId = "Pj0002220002",
+                projectId = "Pj0002220011",
                 groupCode = "BR"
             )
         )
@@ -54,20 +60,10 @@ class PocActivity : AppCompatActivity(), DIAware {
         mVm.requestDict(
             AdmRequest(
                 userId = "bdtp",
-                projectId = "Pj0002220002",
+                projectId = "Pj000222001",
                 groupCode = "BR"
             )
         )
-
-        mVm.requestBuilding(
-            AdmRequest(
-                userId = "bdtp",
-                projectId = "Pj0002220002",
-                groupCode = "BR",
-                buildingId = "Bd0002220002bcaa181bd406439c9ecaddac13b0d543"
-            )
-        )
-
     }
 
     private fun checkStoragePermission() {
@@ -94,4 +90,37 @@ class PocActivity : AppCompatActivity(), DIAware {
         }
     }
 
+    override fun onRequestPermissionsResult(
+        requestCode: Int,
+        permissions: Array<out String>,
+        grantResults: IntArray
+    ) {
+        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
+        if (requestCode == 1) {
+            val mac = MacUtil.getMacAddress(this)!!
+            println("deviceId: $mac")
+            sp.edit {
+                putString("deviceId", mac)
+            }
+
+            lifecycleScope.launch {
+                lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
+                    mVm.buildings.collect { buildings ->
+                        println("buildings in flow: $buildings")
+                        for (building in buildings) {
+                            mVm.requestBuilding(
+                                AdmRequest(
+                                    userId = "bdtp",
+                                    projectId = building.projectId,
+                                    groupCode = "BR",
+                                    buildingId = building.id!!,
+                                    uploadFlag = sp.getString("deviceId", "") ?: ""
+                                )
+                            )
+                        }
+                    }
+                }
+            }
+        }
+    }
 }