本文整理汇总了Scala中org.eclipse.paho.client.mqttv3.MqttClient类的典型用法代码示例。如果您正苦于以下问题:Scala MqttClient类的具体用法?Scala MqttClient怎么用?Scala MqttClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MqttClient类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Publisher
//设置package包名称以及导入依赖的类
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence
import org.eclipse.paho.client.mqttv3.{MqttClient, MqttMessage}
import scala.util.{Failure, Random, Success, Try}
object Publisher extends App {
// Global information
val name = "apdl-case-study-from-scratch"
// MQTT Server info to publish
val brokerURL = "tcp://mosquitto-mqtt:1883"
val topicTemperature = s"temp"
val topicLuminosity = s"light"
val persistence = new MqttDefaultFilePersistence("tmp")
Try {
val client = new MqttClient(brokerURL, MqttClient.generateClientId(), persistence)
client.connect()
val topicTemp = client.getTopic(topicTemperature)
val topicLight = client.getTopic(topicLuminosity)
while (true) {
val temp = Random.nextInt(10) + 20
val light = Random.nextInt(40) + 640
val msgTemp = new MqttMessage(s"$temp".getBytes)
val msgLight = new MqttMessage(s"$light".getBytes)
println(s"Publish $temp to $topicTemperature")
println(s"Publish $light to $topicLight")
topicTemp.publish(msgTemp)
topicLight.publish(msgLight)
Thread.sleep(1000)
}
while(true) {
println("OK !")
Thread.sleep(1000)
}
} match {
case Failure(exception) => println(s"ERROR : $exception + ${exception.getCause}")
case Success(_) => println(s"OK !")
}
}
示例2: MQTTClient
//设置package包名称以及导入依赖的类
package com.murraywilliams
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttMessage
object MQTTClient {
private[this] val logger = org.log4s.getLogger
lazy val mqttClient = {
import XBeeReceiver.conf
try {
val memoryPersistence = new MemoryPersistence()
val brokerUrl = conf.getString("mqtt.url")
val client = new MqttClient(brokerUrl, "xbeeSensorsClientId", memoryPersistence)
val opts = new MqttConnectOptions()
opts.setCleanSession(true)
logger.info(s"Connecting to broker ${brokerUrl}...")
client.connect(opts)
logger.info("Connected")
Some(client)
} catch {
case t : Throwable => {
logger.error(t)("Could not connect to MQTT server.")
None
}
}
}
lazy val mqttTopicRoot = XBeeReceiver.conf.getString("mqtt.topic")
def mqttSend(topicSuffix : String, message : Any) = {
val msg = message match {
case str : String => str.getBytes
case byteArray : Array[Byte] => byteArray
case _ => message.toString.getBytes
}
mqttClient match {
case Some(client) if client.isConnected => client.publish(s"${mqttTopicRoot}/${topicSuffix}",new MqttMessage(msg))
case None => logger.warn("No connection to MQTT broker. Not sending any data.")
}
}
}
示例3: MQTTPublisher
//设置package包名称以及导入依赖的类
package com.knoldus
import com.typesafe.config.ConfigFactory
import org.eclipse.paho.client.mqttv3.{MqttClient, MqttException, MqttMessage}
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import scala.sys.process._
object MQTTPublisher extends App {
val config = ConfigFactory.load()
val url = config.getString("mosquitto-server.url")
val port = config.getInt("mosquitto-server.port")
def publishToserver() = {
println("Hey I am publishing")
val brokerUrl = s"tcp://$url:$port"
val topic = "TemperatureEvent"
val tempCommand = "/opt/vc/bin/vcgencmd measure_temp"
def getMessage = s"Temperature of CPU at ${System.currentTimeMillis()} is ${tempCommand.!!.split("=")(1)} "
var client: MqttClient = null
val persistence = new MemoryPersistence
try {
client = new MqttClient(brokerUrl, MqttClient.generateClientId, persistence)
client.connect()
val msgTopic = client.getTopic(topic)
val message = new MqttMessage(getMessage.getBytes("utf-8"))
while (true) {
msgTopic.publish(message)
println(s"Publishing the data topic ${msgTopic.getName} message: ${message.toString}")
Thread.sleep(1000)
}
}
catch {
case exception: MqttException => println(s"ExceptionOccured:$exception ")
}
finally {
client.disconnect()
}
}
publishToserver
}
示例4: MqttSinkAppA
//设置package包名称以及导入依赖的类
package org.apress.prospark
import java.nio.charset.StandardCharsets
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.streaming.Seconds
import org.apache.spark.streaming.StreamingContext
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import org.json4s.DefaultFormats
import org.json4s.JField
import org.json4s.JsonAST.JObject
import org.json4s.jvalue2extractable
import org.json4s.jvalue2monadic
import org.json4s.native.JsonMethods.parse
import org.json4s.string2JsonInput
object MqttSinkAppA {
def main(args: Array[String]) {
if (args.length != 3) {
System.err.println(
"Usage: MqttSinkApp <appname> <outputBrokerUrl> <topic>")
System.exit(1)
}
val Seq(appName, outputBrokerUrl, topic) = args.toSeq
val conf = new SparkConf()
.setAppName(appName)
.setJars(SparkContext.jarOfClass(this.getClass).toSeq)
val batchInterval = 10
val ssc = new StreamingContext(conf, Seconds(batchInterval))
HttpUtils.createStream(ssc, url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22IBM,GOOG,MSFT,AAPL,FB,ORCL,YHOO,TWTR,LNKD,INTC%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env",
interval = batchInterval)
.flatMap(rec => {
val query = parse(rec) \ "query"
((query \ "results" \ "quote").children).map(rec => JObject(JField("Timestamp", query \ "created")).merge(rec))
})
.map(rec => {
implicit val formats = DefaultFormats
rec.children.map(f => f.extract[String]) mkString ","
})
.foreachRDD { rdd =>
val client = new MqttClient(outputBrokerUrl, MqttClient.generateClientId(), new MemoryPersistence())
client.connect()
rdd.foreach(rec => client.publish(topic, new MqttMessage(rec.getBytes(StandardCharsets.UTF_8))))
client.disconnect()
client.close()
}
ssc.start()
ssc.awaitTermination()
}
}
示例5: MQTTPublisher
//设置package包名称以及导入依赖的类
import com.typesafe.config.ConfigFactory
import org.eclipse.paho.client.mqttv3.{MqttClient, MqttException, MqttMessage}
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import scala.sys.process._
import scala.util.Try
object MQTTPublisher extends App {
val url = Try(ConfigFactory.load().getString("mosquitto-server.url")).toOption.fold("localhost")
val port = Try(ConfigFactory.load().getInt("mosquitto-server.port")).toOption.fold(1883)
def publishToserver() = {
println("Hey I am publishing")
val brokerUrl = s"tcp://$url:$port"
val topic = "TemperatureEvent"
val tempCommand = "/opt/vc/bin/vcgencmd measure_temp"
def getMessage = s"Temperature of CPU at ${System.currentTimeMillis()} is ${tempCommand.!!.split("=")(1)} "
var client: MqttClient = null
val persistence = new MemoryPersistence
try {
client = new MqttClient(brokerUrl, MqttClient.generateClientId, persistence)
client.connect()
val msgTopic = client.getTopic(topic)
val message = new MqttMessage(getMessage.getBytes("utf-8"))
while (true) {
msgTopic.publish(message)
println(s"Publishing the data topic ${msgTopic.getName} message: ${message.toString}")
Thread.sleep(1000)
}
}
catch {
case exception: MqttException => println(s"ExceptionOccured:$exception ")
}
finally {
client.disconnect()
}
}
publishToserver
}
示例6: BrokerUtil
//设置package包名称以及导入依赖的类
package com.ubirch.backend.util
import com.ubirch.backend.config.Config
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import org.eclipse.paho.client.mqttv3.{MqttClient, MqttConnectOptions}
object BrokerUtil {
def connectBroker(topic: String, qos: Int, clientId: String): MqttClient = {
val broker = Config.mqttBroker
val persistence = new MemoryPersistence()
val mqttClient = new MqttClient(broker, clientId, persistence)
val connOpts = new MqttConnectOptions()
connOpts.setCleanSession(true)
mqttClient.connect(connOpts)
mqttClient
}
}
示例7: SubscribeService
//设置package包名称以及导入依赖的类
package service
import controllers.socket.LightSocketActor
import model.Message
import org.eclipse.paho.client.mqttv3.{IMqttDeliveryToken, MqttCallback, MqttClient, MqttMessage}
object SubscribeService {
val client = new MqttClient(brokerUrl, MqttClient.generateClientId(), persistence)
def subscribe(): Unit = {
client.connect()
// TODO: Change topic
client.subscribe(topic)
val callback = new MqttCallback {
override def deliveryComplete(token: IMqttDeliveryToken): Unit = {
play.Logger.debug("Delivery complete!")
}
override def connectionLost(cause: Throwable): Unit = {
play.Logger.debug("Connection to socket lost")
LightSocketActor.sendMessage(Message("Connection lost"))
}
override def messageArrived(topic: String, message: MqttMessage): Unit = {
play.Logger.debug(s"A message arrived: ${new String(message.getPayload)}")
LightSocketActor.sendMessage(Message(new String(message.getPayload)))
}
}
client.setCallback(callback)
}
}