import websocket
import json

def on_message(ws, message):
    values = json.loads(message)['values']
    x = values[0]
    y = values[1]
    z = values[2]
    
    # open the file in append mode
    with open("output.txt", "a") as f:
        # write the results to the file
        f.write(f"x = {x}, y = {y}, z = {z}\n")
    
    print(f"x = {x}, y = {y}, z = {z}")

def on_error(ws, error):
    print("error occurred")
    print(error)

def on_close(ws, close_code, reason):
    print("connection close")
    print("close code : ", close_code)
    print("reason : ", reason  )

def on_open(ws):
    print("connected")

def connect(url):
    ws = websocket.WebSocketApp(url,
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)

    ws.run_forever()



 
#connect("ws://192.168.97.29:8081/sensor/connect?type=android.sensor.accelerometer")
#connect("ws://192.168.166.2:8081/sensor/connect?type=android.sensor.orientation") 
#connect("ws://192.168.97.29:8081/sensor/connect?type=android.sensor.gyroscope")
#connect("ws://192.168.97.29:8081/sensor/connect?type=com.samsung.sensor.physical_proximity")
#connect("ws://192.168.97.29:8081/sensor/connect?type=android.sensor.step_detector")
#connect("ws://192.168.166.72:8081/sensor/connect?type=android.sensor.proximity")

connect("ws://192.168.12.113:8081/sensor/connect?type=android.sensor.accelerometer")

#print(list(connect("ws://192.168.166.72:8081/sensor/connect?type=android.sensor.orientation").__get__())[0:5])