230 lines
5.5 KiB
Python
230 lines
5.5 KiB
Python
#!/usr/bin/python3
|
|
# -*- coding: utf-8 -*-
|
|
# -*- mode: Python -*-
|
|
|
|
'''
|
|
|
|
Nerves WS server v0.1b
|
|
|
|
http page index.html get Server IP, Port from config.js
|
|
|
|
'''
|
|
|
|
#import socket
|
|
import types, json
|
|
import _thread, time
|
|
|
|
from websocket_server import WebsocketServer
|
|
import argparse
|
|
import leds
|
|
import traceback
|
|
|
|
|
|
Players=0
|
|
clientmode = False
|
|
broadcast = True
|
|
|
|
# record current values
|
|
crtvalueMMO3 = [0] * 32
|
|
crtfunc = 0
|
|
funcs = [0,1,2]
|
|
|
|
|
|
print("")
|
|
print("Loading Nerves WS server v0.1b")
|
|
print ("Arguments parsing if needed...")
|
|
argsparser = argparse.ArgumentParser(description="Nerves experimental v0.1b help mode")
|
|
argsparser.add_argument("-i","--IP",help="IP to bind to (0.0.0.0 by default)", type=str)
|
|
argsparser.add_argument("-p","--port",help="Websocket port to bind to (8081 by default)", type=str)
|
|
argsparser.add_argument("-d","--debug",action="store_true",default="False",help="Debug output")
|
|
args = argsparser.parse_args()
|
|
# Server name
|
|
if args.IP:
|
|
serverIP = args.IP
|
|
else:
|
|
serverIP = "0.0.0.0"
|
|
|
|
# ORCA destination device
|
|
if args.port:
|
|
wsPORT = int(args.port)
|
|
else:
|
|
wsPORT = 8081
|
|
|
|
debug = args.debug
|
|
print('Debug mode', debug)
|
|
|
|
|
|
def Start(serverIP, wsPORT):
|
|
global wserver
|
|
|
|
print("Starting WS server ", serverIP, ":", wsPORT)
|
|
wserver = WebsocketServer(wsPORT,host=serverIP)
|
|
wserver.set_fn_new_client(new_client)
|
|
wserver.set_fn_client_left(client_left)
|
|
wserver.set_fn_message_received(message_received)
|
|
|
|
|
|
def runforever():
|
|
|
|
print("Running WS server...")
|
|
#leds.mode = 0
|
|
wserver.run_forever()
|
|
|
|
|
|
# Called for every WS client connecting (after handshake)
|
|
def new_client(client, wserver):
|
|
global Players
|
|
|
|
|
|
print("New WS client connected and was given id %d" % client['id'])
|
|
#sendWSall("/status Hello %d" % client['id'])
|
|
#if current == True:
|
|
# sendallcurrentccvalues("mmo3")
|
|
# sendallcurrentccvalues("ocs2")
|
|
|
|
Players+=1
|
|
sendWSall("/status Hello %d" %(client['id']))
|
|
if Players > 1:
|
|
#sendWSall("/Players %d" %(Players))
|
|
sendWSall("/players connected:%d" %(Players))
|
|
else:
|
|
sendWSall("/players connected:%d" %(Players))
|
|
|
|
|
|
|
|
# Called for every WS client disconnecting
|
|
def client_left(client, wserver):
|
|
|
|
|
|
try:
|
|
print("WS Client(%d) disconnected" % client['id'])
|
|
Players-=1
|
|
sendWSall("/players %d" %(Players))
|
|
except:
|
|
print("Something weird if coming from",client,"on the wire...")
|
|
pass
|
|
|
|
|
|
# Called for each WS received message.
|
|
def message_received(client, wserver, message):
|
|
global crtfunc
|
|
|
|
if len(message) > 200:
|
|
message = message[:200]+'..'
|
|
|
|
wspath = message.split(" ")
|
|
wscommand = wspath[0].split("/")
|
|
|
|
# debug
|
|
if debug == True:
|
|
print("Main got from WS", client['id'], "said :", message, ": wscommand :",wscommand,"and wspath :", wspath)
|
|
|
|
# noarg
|
|
if len(wspath) == 1:
|
|
args[0] = "noargs"
|
|
#print "noargs command"
|
|
|
|
# functions : /func 1
|
|
elif wscommand[1] == "func":
|
|
if debug == True:
|
|
print("func function with ", wspath[1])
|
|
|
|
crtfunc +=1
|
|
if crtfunc == len(funcs):
|
|
crtfunc = 0
|
|
print('Launch func', crtfunc)
|
|
sendWSall("/players Function:"+leds.modes[crtfunc])
|
|
|
|
print('Launch func', crtfunc)
|
|
if crtfunc == 0:
|
|
leds.mode = 0
|
|
if crtfunc == 1:
|
|
leds.mode = 1
|
|
if crtfunc == 2:
|
|
leds.mode = 2
|
|
|
|
# shutdown : /down 1
|
|
elif wscommand[1] == "down":
|
|
|
|
if wspath[1] == '1':
|
|
import os
|
|
print('will shutdown...')
|
|
sendWSall("/players Shutdown...")
|
|
leds.mode = -1
|
|
leds.cls()
|
|
os.system("systemctl poweroff")
|
|
|
|
# incoming termspy : /termspy portnumber
|
|
elif wscommand[1] == "termspy":
|
|
|
|
print('incoming port', str(wspath[1]),'from termspy')
|
|
|
|
if leds.mode == 2:
|
|
|
|
# port = int(wspath[1])
|
|
if int(wspath[1]) != wsPORT:
|
|
leds.nextnerve(int(wspath[1]))
|
|
|
|
'''
|
|
# CC : /device/cc/2 127
|
|
elif wscommand[2] == "cc":
|
|
ccvr=int(wscommand[3]) #cc variable
|
|
ccvl=int(wspath[1]) #cc value
|
|
if debug > 0:
|
|
print("ccvr=%d/ccvl=%d"%(ccvr,ccvl))
|
|
if wscommand[1] == "ocs2":
|
|
crtvalueOCS2[ccvr]=ccvl
|
|
else:
|
|
crtvalueMMO3[ccvr]=ccvl
|
|
'''
|
|
# Loop back : WS Client -> server -> WS Client
|
|
#sendWSall(message)
|
|
|
|
# Send through websocket.
|
|
# Different websocket library for client (websocket) or server (websocket_server.
|
|
# ws object is added here by main.py or client.py startup : midi3.ws =
|
|
def send(message):
|
|
|
|
if clientmode == True:
|
|
send(message)
|
|
else:
|
|
wserver.send_message_to_all(msg = message)
|
|
|
|
|
|
|
|
def sendWSall(message):
|
|
|
|
if broadcast == True:
|
|
if debug == True:
|
|
print("WS sending to all %s" % (message))
|
|
|
|
wserver.send_message_to_all(message)
|
|
'''
|
|
# /send all current cc values
|
|
def sendallcurrentccvalues(nozoid):
|
|
|
|
if broadcast == True:
|
|
#print ""
|
|
print("sending all current cc values of", nozoid)
|
|
|
|
if nozoid == "mmo3":
|
|
for ccnumber in range(0,32):
|
|
sendWSall("/mmo3/cc/"+str(ccnumber)+" "+str(crtvalueMMO3[ccnumber]))
|
|
else:
|
|
for ccnumber in range(0,32):
|
|
sendWSall("/ocs2/cc/"+str(ccnumber)+" "+str(crtvalueOCS2[ccnumber]))
|
|
'''
|
|
|
|
if __name__ == '__main__':
|
|
|
|
Start(serverIP, wsPORT)
|
|
|
|
try:
|
|
|
|
runforever()
|
|
|
|
except Exception:
|
|
traceback.print_exc()
|
|
wserver.close()
|
|
|