'Utilizing the Websocket Data from Android cellphone while running
Using SensorServer, I am establishing a connection between an android phone and Python and utilizing the data sent. The accelerometer of the Android device is used to determine a polygonal position.
SensorServer Code:
import websocket
import json
def on_message(ws, message):
values = json.loads(message)['values']
x = values[0]
y = values[1]
z = values[2]
print('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("connection open")
if __name__ == "__main__":
ws = websocket.WebSocketApp("ws://192.168.0.101:8081/sensor/connect?type=android.sensor.accelerometer",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever()
The 'x-axis', 'y-axis', and 'z-axis' are my primary uses. But I have difficulty using the data due to two main limitations:
The first, is manipulating the data while the program is running - say something like this:
#Ensure that the polygon will not cross the 2:-2 outline
if x > 2:
x = 2
if x < -2:
x = -2
Second, Because of the endless loop of ws.run_forever()
i can't run any other code that defines the polygon position:
polygon = visual.ShapeStim(
win=win, name='polygon',
size=(z), vertices='triangle',
ori=0.0, pos=[x,y], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='white',
opacity=None, depth=-2.0, interpolate=True)
So, I need help in resulting those complications Appreciating comments in advance.
Solution 1:[1]
I used this code:
ws = websocket.WebSocket()
ws.connect("ws://10.100.102.17:8081/sensor/connecttype=android.sensor.gyroscope_uncalibrated")
while True:
if ws.getstatus() == None:
pass
else:
break
rc = ws.recv()
rc = json.loads(str(rc))
rc = rc['values']
polygon = visual.ShapeStim(
win=win, name='polygon',
size=(rc[0]), vertices='triangle',
ori=0.0, pos=[rc[1],rc[2]], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='white',
opacity=None, depth=-2.0, interpolate=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Javad Nikbakht |