Skip to content

Instantly share code, notes, and snippets.

@skoky
Last active April 5, 2020 07:44
Show Gist options
  • Save skoky/21d8e2b9d8f7f423bf96a8953dc4615c to your computer and use it in GitHub Desktop.
Save skoky/21d8e2b9d8f7f423bf96a8953dc4615c to your computer and use it in GitHub Desktop.
SolarPower web server - copies Derby database, reads solar power status and publishes to local web server every minute. Compatible with SolarPower 1.14
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'MainKt'
buildscript {
ext.kotlin_version = '1.3.71'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'org.apache.derby:derby:10.14.1.0'
compile 'com.github.seratch:kotliquery:1.3.0'
compile "com.sparkjava:spark-kotlin:1.0.0-alpha"
}
import kotliquery.queryOf
import kotliquery.sessionOf
import kotliquery.using
import spark.kotlin.Http
import spark.kotlin.ignite
import java.io.File
import java.sql.DriverManager
import java.util.*
import kotlin.concurrent.schedule
import kotlin.system.exitProcess
data class Status(
val workmode: String,
val batteryVoltage: String, val chargingCurrent: String, val inputPower: String,
val timestamp: String
)
fun main(args: Array<String>) {
if (args.isEmpty() || !File(args[0]).exists()) {
println("Derby dir does no exists ${Arrays.toString(args)}")
exitProcess(1)
}
var status: Status? = null
Timer().schedule(delay = 1000, period = 60000) {// every minute
status = getStatus(args[0])
}
val http: Http = ignite()
http.port(80)
http.get("/") {
when (status) {
null -> "Starting"
else -> {
"${status?.workmode}<br>" +
"Solar power: ${status?.inputPower}W<br>" +
"Battery voltage: ${status?.batteryVoltage}V<br>" +
"Battery charging: ${status?.chargingCurrent}A<br>" +
"At: ${status?.timestamp}"
}
}
}
println("started at port ${http.port()}")
}
fun getStatus(dir: String): Status {
val tmpDir: File = createTempDir("sp-")
val srcFile = File(dir)
srcFile.copyRecursively(tmpDir, overwrite = true)
val connString = "jdbc:derby:${tmpDir}"
val select =
"select workmode, PBATTERYVOLTAGE,CURRENTTIME, CHARGINGCURRENT, PVINPUTPOWER1 " +
"from WORK_DATA order by WORKID desc fetch " +
"first 1 rows only"
return using(sessionOf(connString, "", "")) { session ->
val stateQuery = queryOf(select).map { row ->
Status(
row.string("workmode"),
row.string("PBATTERYVOLTAGE"),
row.string("CHARGINGCURRENT"),
row.string("PVINPUTPOWER1"),
row.string("CURRENTTIME")
)
}.asList
val status: List<Status> = session.run(stateQuery)
try { // hack to work on Windows
DriverManager.getConnection("${connString};shutdown=true");
} catch (e:Exception) {}
status[0]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment