Skip to content

Instantly share code, notes, and snippets.

@itsecurityco
Last active September 7, 2021 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsecurityco/5a3f6f486fc2a413e62cdcd0052fc686 to your computer and use it in GitHub Desktop.
Save itsecurityco/5a3f6f486fc2a413e62cdcd0052fc686 to your computer and use it in GitHub Desktop.
Simple Kotlin application to communicate with a PLC via Modbus
/* @author: Juan Escobar (juan.escobar@dreamlab.net) */
package net.dreamlab.modbuscoils
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.StrictMode
import android.util.Log
import android.view.View
import io.ktor.network.selector.*
import io.ktor.network.sockets.*
import io.ktor.utils.io.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.net.InetSocketAddress
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder().permitAll().build())
}
/* https://stackoverflow.com/a/51404278/2067290 */
private fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() }
/* Called when the user taps the ON button */
fun turnOnLight(view: View) {
runBlocking {
val socket = aSocket(ActorSelectorManager(Dispatchers.IO)).tcp().connect(InetSocketAddress("plc_address", 502))
val output = socket.openWriteChannel(autoFlush = true)
val packet = byteArrayOfInts(0x00,0x01,0x00,0x00,0x00,0x06,0xff,0x05,0x00,0x00,0xff,0x00)
output.writeFully(packet)
socket.close()
}
}
/* Called when the user taps the OFF button */
fun turnOffLight(view: View) {
runBlocking {
val socket = aSocket(ActorSelectorManager(Dispatchers.IO)).tcp().connect(InetSocketAddress("ip_address", 502))
val output = socket.openWriteChannel(autoFlush = true)
val packet = byteArrayOfInts(0x00,0x01,0x00,0x00,0x00,0x06,0xff,0x05,0x00,0x00,0x00,0x00)
output.writeFully(packet)
socket.close()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment