I'm testing AWS Lambda with an AWS IOT source. My mqtt clients are publishing in different topics : device A publish data into streaming/A
, device B publish data into streaming/B
so in AWS Lambda I defined a SQL rule selecting all devices coming from the topics streaming/+
. The thing is that now I didn't have the information of the device source because I only have a Array[Byte]]
with extra informations. If anyone has a solution to access to the mqtt payload with the topic information, I will take it !
import java.io.{ByteArrayOutputStream, InputStream, OutputStream}
import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
/**
* Created by alifirat on 24/04/17.
*/
class IOTConsumer extends RequestStreamHandler {
val BUFFER_SIZE = 1024 * 4
override def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = {
val bytes = toByteArray(input)
val logger= context.getLogger
logger.log("Receive following thing :" + new String(bytes))
output.write(bytes)
}
/**
* Reads and returns the rest of the given input stream as a byte array.
* Caller is responsible for closing the given input stream.
*/
def toByteArray(is : InputStream) : Array[Byte] = {
val output = new ByteArrayOutputStream()
try {
val b = new Array[Byte](BUFFER_SIZE);
var n = 0
var flag = true
while(flag) {
n = is.read(b)
if(n == -1) flag = false
else {
output.write(b, 0, n)
}
}
output.toByteArray();
} finally {
output.close();
Array[Byte]()
}
}
}
java.io.InputStream
? Where did that code come from? That doc seems to suggest that mqtt message is JSON. – Excellence