Search code examples
pythonrraspberry-pishinyrpython

R rPython remote computer's python


I want to build a Shiny app and control some hardware through it by using a raspberry pi's GPIO pins. If I install R on pi itself and use code like

library(rPython)
python.exec("
                import RPi.GPIO as GPIO
                import time
                GPIO.setmode(GPIO.BCM)
                GPIO.setwarnings(False)
                GPIO.setup(18,GPIO.OUT)
                GPIO.output(18,GPIO.HIGH)
            ")

I can control the output and inputs on GPIO pins pretty well from raspberry pi's R console. But since pi can't host a Shiny server, is there a way I can use my laptop's R session to connect to pi's python environment and control GPIO pins via rPython? Or any other suggestion for the task?


Solution

  • Try R's svSocket package. This communicates over TCP/IP protocol. With this package you setup a server on your pi. Like

    require(svSocket)
    startSocketServer(port = 9999) # choose your preferred port
    while(1)
    {
       ... # some code to do
       Sys.Sleep(0.05) # give the system some time to do other things
    }
    

    This enables your pi to do some stuff in the while statement. And in parallel you can send to it some code which is going to be evaluate from the running server.

    In the R session on your computer type:

    require(svSocket)
    con <- socketConnection(port = 9999)
    
    evalServer(con, <code to evaluate on your pi>)
    

    This is the way I talk to different R sessions on different computers.

    Best! Martin