Skip to content

Commit

Permalink
iss #24: use universal config in mt8057 agent
Browse files Browse the repository at this point in the history
  • Loading branch information
maizy committed Feb 6, 2017
1 parent bf7308d commit bde1e6b
Show file tree
Hide file tree
Showing 17 changed files with 347 additions and 359 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ case class Ambient7Options(

// TODO: how to extract those specific option to target submodule?
webAppSpecificOptions: Option[WebAppSpecificOptions] = None,


mt8057AgentSpecificOptions: Option[Mt8057AgentSpecificOptions] = None,

// TODO: fix this little hack
showHelp: Boolean = false
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ru.maizy.ambient7.core.config

import java.io.File

/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2017
* See LICENSE.txt for details.
*/

// TODO: should be only in mt8057-agent submodule

trait EnumerationMap extends Enumeration {
self =>
lazy val valuesMap: Map[String, Value] = self.values.map{ v => (v.toString, v) }.toMap
}

object Writers extends Enumeration with EnumerationMap {
self =>
type Writer = Value
val Console = Value("console")
val Interactive = Value("interactive")
val InfluxDb = Value("influxdb")
}

case class Mt8057AgentSpecificOptions(
writers: Set[Writers.Writer] = Set.empty,
useEmulator: Boolean = false,
logFile: Option[File] = None,
verboseLogging: Boolean = false
)
13 changes: 12 additions & 1 deletion core/src/main/scala/ru/maizy/ambient7/core/data/AgentTags.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ class AgentTags private(val tags: IndexedSeq[AgentTag]) {
def encoded: String = tags.map(_.encoded).mkString(",")
override def toString: String = s"AgentTags(${tags.mkString(",")})"
def asPairs: IndexedSeq[(String, String)] = tags.map(t => (t.name, t.value))

def canEqual(other: Any): Boolean = other.isInstanceOf[AgentTags]

override def equals(other: Any): Boolean = other match {
case that: AgentTags => (that canEqual this) && tags == that.tags
case _ => false
}

override def hashCode(): Int = {
tags.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
}

object AgentTags {
Expand Down Expand Up @@ -48,7 +59,7 @@ object AgentTags {
part <- parts
if part.count(_ == '=') == 1;
nameValue = part.split("=")
) yield AgentTag(nameValue(0), decodeTag(nameValue(1)))
) yield AgentTag(decodeTag(nameValue(0)), decodeTag(nameValue(1)))

if (parts.size != parsedTags.size) {
// TODO: more precise errors
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package ru.maizy.ambient7.core.tests.data

/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2017
* See LICENSE.txt for details.
*/

import ru.maizy.ambient7.core.data.{ AgentTag, AgentTags }
import ru.maizy.ambient7.core.tests.BaseSpec

class AgentTagsSpec extends BaseSpec {

"AgentTags" should "encode & decode tags and tags values with escaping" in {
val originalString = "atag=va\\,lue,b\\,tag=value"
AgentTags(originalString) shouldBe
AgentTags(Seq(AgentTag("atag", "va,lue"), AgentTag("b,tag", "value")))

AgentTags(originalString).encoded shouldBe originalString
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ package ru.maizy.ambient7.mt8057agent
import java.text.SimpleDateFormat
import java.util.Date
import com.typesafe.scalalogging.LazyLogging
import ru.maizy.ambient7.core.config.Ambient7Options

/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2015-2017
* See LICENSE.txt for details.
*/
class ConsoleWriter(opts: AppOptions) extends Writer with LazyLogging {
class ConsoleWriter(opts: Ambient7Options) extends Writer with LazyLogging {

private def convertTimestamp(nanos: Long): String = {
val millis = nanos / 1000000
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
package ru.maizy.ambient7.mt8057agent

import scala.collection.mutable
import scala.util.{ Success, Failure, Try }
import scalaj.http.{ HttpOptions, HttpResponse, BaseHttp, HttpRequest }
import com.typesafe.scalalogging.LazyLogging

/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2015-2017
* See LICENSE.txt for details.
*/
class InfluxDbWriter(opts: AppOptions) extends Writer with LazyLogging {

import scala.util.{ Failure, Success, Try }
import scalaj.http.{ BaseHttp, HttpOptions, HttpRequest, HttpResponse }
import com.typesafe.scalalogging.LazyLogging
import ru.maizy.ambient7.core.config.{ Ambient7Options, InfluxDbOptions }
import ru.maizy.ambient7.core.data.{ AgentTag, AgentTags }

class InfluxDbWriter(opts: Ambient7Options) extends Writer with LazyLogging {
import InfluxDbWriter._
val OK_NO_CONTENT = 204

override def write(event: Event): Unit = {
formatLine(event).foreach { data =>
val request = buildWriteRequest(data)
val responseRes = performRequest(request)
// TODO: buffer for N events if a failure happens (iss #14)
responseRes match {
case Failure(e) =>
logger.warn(s"Unable to perform influxdb request: ${e.getClass}")
logger.debug(s"Request error", e)
case Success(response) if response.code != OK_NO_CONTENT =>
logger.warn(s"Unable to write event to influxdb: HTTP ${response.code} ${response.body}")
case _ =>
opts.influxDb match {
case None => logger.error(s"Unable to perform influxdb request: options not available")
case Some(influxDbOptions) =>
val request = buildWriteRequest(data, influxDbOptions)
val responseRes = performRequest(request)
// TODO: buffer for N events if a failure happens (iss #14)
responseRes match {
case Failure(e) =>
logger.warn(s"Unable to perform influxdb request: ${e.getClass}")
logger.debug(s"Request error", e)
case Success(response) if response.code != OK_NO_CONTENT =>
logger.warn(s"Unable to write event to influxdb: HTTP ${response.code} ${response.body}")
case _ =>
}
}
}
}
Expand All @@ -42,42 +48,34 @@ class InfluxDbWriter(opts: AppOptions) extends Writer with LazyLogging {
}
}

// TODO: migrate to ru.maizy.ambient7.core.data.AgentTags
private lazy val tags: String = {
val tags = mutable.ListBuffer[(String, String)]()
opts.influxDbAgentName foreach { n =>
tags += (("agent", n))
}
tags += (("device", "mt8057"))
val additionalTags = opts.influxDbTags
if (additionalTags.length > 0) {
additionalTags.split("""(?<!\\),""")
.foreach { pair =>
val parts = pair.split("=")
if (parts.length == 2) {
tags += ((parts(0), parts(1)))
}
}
opts.selectedCo2Device match {
case Some(device) =>
val finalTags = AgentTags(
device.agent.tags.tags ++ IndexedSeq(
AgentTag("agent", device.agent.agentName),
AgentTag("device", "mt8057")
)
)
"," + finalTags.encoded
case _ => ""
}
"," + tags
.sortWith { case (p1, p2) => p1._1.compareTo(p2._1) < 0 }
.map {case (key, value) => s"$key=$value"}
.mkString(",")
}

private[mt8057agent] def performRequest(request: HttpRequest): Try[HttpResponse[String]] =
Try(request.asString)

private def buildWriteRequest(data: String): HttpRequest = {
var request = HttpClient(opts.influxDbBaseUrl)
private def buildWriteRequest(data: String, influxDbOpts: InfluxDbOptions): HttpRequest = {
// TODO: migrate to influxdb client
var request = HttpClient(influxDbOpts.baseUrl)
.postData(data)

request = opts.influxDbDatabase match {
request = influxDbOpts.database match {
case Some(dbName) => request.param("db", dbName)
case _ => request
}

request = (opts.influxDbUser, opts.influxDbPassword) match {
request = (influxDbOpts.user, influxDbOpts.password) match {
case (Some(user), Some(pass)) =>
request.auth(user, pass)
case _ =>
Expand All @@ -91,7 +89,7 @@ class InfluxDbWriter(opts: AppOptions) extends Writer with LazyLogging {

object InfluxDbWriter {
object HttpClient extends BaseHttp (
userAgent = "ambient7/" + AppOptions.APP_VERSION,
userAgent = "ambient7", // TODO: app version
options = Seq(
HttpOptions.connTimeout(200),
HttpOptions.readTimeout(200),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ package ru.maizy.ambient7.mt8057agent
* Copyright (c) Nikita Kovaliov, maizy.ru, 2015-2017
* See LICENSE.txt for details.
*/
class InteractiveWriter(opts: AppOptions) extends StatefullWriter {

import ru.maizy.ambient7.core.config.Ambient7Options

class InteractiveWriter(opts: Ambient7Options) extends StatefullWriter {
val CO2_OK = 800
val C02_NOT_OK = 1200

Expand Down
Loading

0 comments on commit bde1e6b

Please sign in to comment.