import SocketServer
import sys
import mraa

try:
    # set ports A2, A1 and A0 on Edison arduino board as analog inputs
    ax = mraa.Aio(2)
    ay = mraa.Aio(1)
    az = mraa.Aio(0)
    # ax, ay, az correspond to X_out, Y_out, Z_out pins of accelerometer
except:
    print("you don't have an ADC")

# set ADC reading precision to 12-bits
ax.setBit(12)
ay.setBit(12)
az.setBit(12)

def get_accl_data():
    # return the three adc readings as space seperated string
    return str(az.read()) + " " + str(ay.read()) + " " + str(ax.read())

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        ret_data = get_accl_data()
        self.request.sendall(ret_data)

if __name__ == "__main__":
    HOST, PORT = "192.168.1.108", 5000
    # Create the server, binding to localhost on port 5000
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()


