Skip to content

Instantly share code, notes, and snippets.

@lakewik
Created December 25, 2017 21:21
Show Gist options
  • Save lakewik/4957c063274a22401f84f2a6d6cde47c to your computer and use it in GitHub Desktop.
Save lakewik/4957c063274a22401f84f2a6d6cde47c to your computer and use it in GitHub Desktop.
sterowanie24
import websocket
import thread
import time
import threading
import RPi.GPIO as GPIO
import json
def set_interval(func, sec, ws):
def func_wrapper():
set_interval(func, sec, ws)
func(ws)
t = threading.Timer(sec, func_wrapper)
t.start()
return t
def ping (ws):
ts = int(time.time())
#ws.send(json.dumps([json.dumps({'event': 'ping', 'data': ts})]))
print "Sending ping"
def on_message(ws, message):
j = json.loads(str(message))
if j["event"] == "steruj" and j["card_id"] == "20":
if j['button'] == 0:
if j['state'] == 0:
GPIO.output(2, GPIO.HIGH)
else:
GPIO.output(2, GPIO.LOW)
if j['button'] == 1:
if j['state'] == 0:
GPIO.output(3, GPIO.HIGH)
else:
GPIO.output(3, GPIO.LOW)
if j['button'] == 2:
if j['state'] == 0:
GPIO.output(4, GPIO.HIGH)
else:
GPIO.output(4, GPIO.LOW)
if j['button'] == 3:
if j['state'] == 0:
GPIO.output(19, GPIO.HIGH)
else:
GPIO.output(19, GPIO.LOW)
if j['button'] == 3:
if j['state'] == 0:
GPIO.output(17, GPIO.HIGH)
else:
GPIO.output(17, GPIO.LOW)
if j['button'] == 3:
if j['state'] == 0:
GPIO.output(27, GPIO.HIGH)
else:
GPIO.output(27, GPIO.LOW)
if j['button'] == 3:
if j['state'] == 0:
GPIO.output(22, GPIO.HIGH)
else:
GPIO.output(22, GPIO.LOW)
if j['button'] == 3:
if j['state'] == 0:
GPIO.output(10, GPIO.HIGH)
else:
GPIO.output(10, GPIO.LOW)
if j['button'] == 3:
if j['state'] == 0:
GPIO.output(9, GPIO.HIGH)
else:
GPIO.output(9, GPIO.LOW)
if j['button'] == 3:
if j['state'] == 0:
GPIO.output(11, GPIO.HIGH)
else:
GPIO.output(11, GPIO.LOW)
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
startWS()
def on_open(ws):
#def run(*args):
#for i in range(3):
#time.sleep(1)
#ws.send("Hello %d" % i)
# time.sleep(1)
# ws.close()
# print("thread terminating...")
#thread.start_new_thread(run, ())
#set_interval(ping, 5, ws)
print "Opened connection"
def startWS():
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://socket.sterowanie24.pl:8000//?c=20",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment