#
# A minimal example SNAP Connect 3.0 application. This example was
# deliberately kept simple, and so does not showcase the full power
# of Python or SNAP Connect 3.0. It enables RPC access via TCP/IP
# or via SNAP Engine (2.4 GHz radio, etc.), and gives you control
# of the Linux processor's "B" LED and Push Button.
#

from snapconnect import snap
 
import os # So we can gain access to the LEDs and Push Button

#
#
# Example routines to control the "B" LED on the E10
# (The "A" LED is connected to the internal SNAP Engine inside the E10)
#
#

#
# Individual LED pin control (used internally)
#
def setGreenLed(value):
    os.system("echo "+str(value)+" >> /sys/class/leds/greenled/brightness")

def setRedLed(value):
    os.system("echo "+str(value)+" >> /sys/class/leds/redled/brightness")

#
# It's actually a tri-color LED (this will be the public API)
#
def setLedBOff():
    setGreenLed(0)
    setRedLed(0)
 
def setLedBGreen():
    setGreenLed(1)
    setRedLed(0)
 
def setLedBRed():
    setGreenLed(0)
    setRedLed(1)
 
def setLedBYellow():
    setGreenLed(1)
    setRedLed(1)

#
# Example routine to read the MODE push button
# Normally a pullup resistor holds the pin high/True
# Pushing the button connects the physical pin to ground (low/False)
#
def readButton():
    result = os.system("/usr/bin/gpio9260 ?PB10")
    return result != 0 # Forcing boolean result

def server_auth(realm, username):
    """
    An example server authentication function
 
    Returns the password for the specified username in the realm
 
    realm : This server's realm
    username : The username specified by the remote server
    """
    if username == "public":
        return "public"
 
 
if __name__ == '__main__':
    import logging
 
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(msecs)03d %(levelname)-8s %(name)-8s %(message)s', datefmt='%H:%M:%S')
 
    funcdir = { # You CHOOSE what you want to provide RPC access to...
               'setLedBOff'    : setLedBOff,
               'setLedBGreen'  : setLedBGreen,
               'setLedBRed'    : setLedBRed,
               'setLedBYellow' : setLedBYellow,
               'readButton'    : readButton
              }
    com = snap.Snap(funcs=funcdir)

    # Make us accessible over TCP/IP
    com.accept_tcp(server_auth)

    # Make us accessible over our internal SNAP Engine
    com.open_serial(1, '/dev/ttyS1')

    #
    # Configure some example settings
    #

    # No encryption
    com.save_nv_param(snap.NV_AES128_ENABLE_ID, False)

    # Lock down our routes (we are a stationary device)
    com.save_nv_param(snap.NV_MESH_ROUTE_AGE_MAX_TIMEOUT_ID, 0)

    # Don't allow others to change our NV Parameters
    com.save_nv_param(snap.NV_LOCKDOWN_FLAGS_ID, 0x2)
 
    # Run SNAP Connect until shutdown
    while True:
        com.poll()
    com.stop_accepting_tcp()
