def run(self): self.config.reload_if_updated() with Wapt(config_filename = self.config.config_filename) as tmp_wapt: logger.info('Starting socketio on "%s://%s:%s" ...' % (self.config.websockets_proto,self.config.websockets_host,self.config.websockets_port)) logger.debug('Certificate checking : %s' % self.config.websockets_verify_cert) def get_connect_params(wapt): connect_params = {'uuid': wapt.host_uuid} if not self.server_authorization_token: try: self.server_authorization_token = wapt.get_auth_token('websocket') logger.info('Websocket token: %s' % self.server_authorization_token) connect_params['token'] = self.server_authorization_token except Exception as e: logger.warning('Websocket connect params: %s' % e) self.server_authorization_token = None return {'params':connect_params, 'cert' :(wapt.get_host_certificate_filename(),wapt.get_host_key_filename())} while True: try: connect_params = get_connect_params(tmp_wapt) if not self.socketio_client and self.config.websockets_host: logger.debug('Creating socketio client') logger.debug('Proxies : %s'%self.config.waptserver.proxies) # bug in socketio... ? we must not pass proxies at all (even None) if we don"t want to switch to polling mode... kwargs = {} if self.config.waptserver.proxies and self.config.waptserver.proxies.get(self.config.websockets_proto,None) is not None: kwargs['proxies'] = self.config.waptserver.proxies kwargs.update(connect_params) self.socketio_client = SocketIO( host="%s://%s" % (self.config.websockets_proto,self.config.websockets_host), port=self.config.websockets_port, Namespace = WaptSocketIORemoteCalls, resource=self.config.websockets_root, verify=self.config.websockets_verify_cert, wait_for_connection = False, transport = ['websocket'], ping_interval = self.config.websockets_ping, hurry_interval_in_seconds = self.config.websockets_hurry_interval, request_timeout = self.request_timeout, **kwargs) self.socketio_client.get_namespace().wapt = tmp_wapt self.socketio_client.get_namespace().task_manager = self.task_manager if self.socketio_client and self.config.websockets_host: if not self.socketio_client.connected: self.socketio_client._http_session.update(connect_params) self.socketio_client.define(WaptSocketIORemoteCalls) self.socketio_client.get_namespace().wapt = tmp_wapt self.socketio_client.get_namespace().task_manager = self.task_manager self.socketio_client.connect('') else: # be sure server DB is aware of the current connection. # could be avoided self.socketio_client.emit('wapt_pong') if self.socketio_client.connected: logger.info('Socket IO listening for %ss' % self.config.websockets_check_config_interval ) startwait = time.time() self.socketio_client.wait(self.config.websockets_check_config_interval) # QAD workaround for cases where server disconnect but client is between 2 states. # In this case; wait() immediately returns, leading to an indefinite loop eating 1 core. if time.time() - startwait < self.config.websockets_check_config_interval-2: raise Exception('Websocket client seems disconnected. Force Websocket connection to be recreated') elif not self.config.websockets_host: self.socketio_client = None time.sleep(self.config.websockets_retry_delay) else: time.sleep(self.config.websockets_retry_delay) if self.config.reload_if_updated(): tmp_wapt.reload_config_if_updated() if self.socketio_client: self.socketio_client.disconnect() raise EWaptException('Configuration changed, force Websocket connection to be recreated') except Exception as e: try: # reset token self.server_authorization_token = None self.config.reload_if_updated() if self.socketio_client: self.socketio_client = None finally: logger.info(u'Exception %s, Socket IO Stopped, waiting %ss before retrying' % (repr(e),self.config.websockets_retry_delay)) time.sleep(self.config.websockets_retry_delay)
from socketIO_client import SocketIO, LoggingNamespace with SocketIO('localhost', 3000, LoggingNamespace) as socketIO: socketIO.emit('bbox', [{ 'x': 10, 'y': 10, 'w': 100, 'h': 100 }, { 'x': 10, 'y': 10, 'w': 100, 'h': 100 }, { 'x': 10, 'y': 10, 'w': 100, 'h': 100 }, { 'x': 10, 'y': 10, 'w': 100, 'h': 100 }]) socketIO.wait(seconds=1)
win32print.WritePrinter( prt, '========================================' + "\r\n") win32print.WritePrinter(prt, ' Cartorio Moreira de Deus' + "\r\n") win32print.WritePrinter( prt, '========================================' + "\r\n") win32print.WritePrinter(prt, 'Servico: ' + "\r\n") win32print.WritePrinter(prt, vservico + "\r\n") win32print.WritePrinter( prt, '----------------------------------------' + "\r\n") win32print.WritePrinter(prt, 'Atendimento: ' + vatendimento + "\r\n") win32print.WritePrinter(prt, 'Sequencia: ' + vsequencia + "\r\n") win32print.WritePrinter(prt, 'Chegou as: ' + vtimestamp + "\r\n") win32print.WritePrinter( prt, '----------------------------------------' + "\r\n") win32print.WritePrinter( prt, 'A sequencia sera chamada 3 vezes, caso' + "\r\n") win32print.WritePrinter(prt, 'nao compareca ao balcão tera que' + "\r\n") win32print.WritePrinter(prt, 'solicitar outra sequencia.' + "\r\n") win32print.WritePrinter( prt, '========================================' + "\r\n\f") finally: win32print.EndDocPrinter(prt) win32print.ClosePrinter(prt) # Conexão socketIO = SocketIO('10.1.1.4', 8080) socketIO.on('print', ouvindoPrint) socketIO.wait()
from socketIO_client import SocketIO import serial import time import csv total = 0 len = 20 ecg = [None] * len i = 0 print("Comenzando...") socketIO = SocketIO('201.174.122.203', 5001) print("Conectado al servidor.") arduino = serial.Serial('/dev/ttyACM0', 9600, timeout=3.0) arduino.isOpen() #file1 = open('muestra.csv', 'w+') while True: arduino.write("T") sig = arduino.readline() if sig[:3] == "TEM": print("TEM = " + sig[3:]) socketIO.emit("temperatura", sig[3:]) arduino.write("C") sig = arduino.readline() if sig[:4] == "CARB": print("CARB = " + sig[4:]) socketIO.emit("carbono", sig[4:])
from socketIO_client import SocketIO, BaseNamespace class ChatNamespace(BaseNamespace): # Name of the method starts with on_{channel_name} # Server does emit('my_response', {'data': 'Connected'}) # hence the name on_my_response @staticmethod def on_my_response(data): print(data) print('[Connected]') socketIO = SocketIO('localhost', 5002) chat_namespace = socketIO.define(ChatNamespace, '/test') chat_namespace.emit('my_event', {'data': 20}) chat_namespace.emit('my_broadcast_event', {'data': 40}) socketIO.wait(seconds=20)
0:24] == "https://www.youtube.com/" or message[ 0:17] == "https://youtu.be/" or message[ 0:23] == "https://soundcloud.com/": url = message if url not in blocked: print "url", url subprocess.call(["Taskkill", "/IM", "firefox.exe", "/F"]) subprocess.Popen([ "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", url ]) print 'received chat', fullMessage socketIO = SocketIO('https://runmyrobot.com', 8000, LoggingNamespace) socketIO.on('connect', on_connect) socketIO.on('disconnect', on_disconnect) socketIO.on('reconnect', on_reconnect) # Listen socketIO.on('chat_message_with_name', on_chat_message) #socketIO.emit('aaa') #socketIO.emit('aaa') socketIO.wait(seconds=1) # Stop listening #socketIO.off('play_youtube') socketIO.emit('aaa') socketIO.wait(seconds=1)
self.nameToUse = [] self.drinkToUse = [] self.ageToUse = [] self.choosenName = None self.choosenDrink = None self.choosenAge = None self.nameAction = None self.currentStep = None self.currentAction = None self.index = 0 self.indexStepCompleted = 0 self.dataToUse = '' self.indexFailure = None self.restart = 0 self.data_received = False self.currentIndexDataReceivedJS = 0 self.end_guest_procedure = None self.restart_mode = 'ON' socketIO.emit('restartHRI', broadcast=True) self.pub_restart_request.publish("RESTART") if __name__ == '__main__': socketIO = SocketIO('http://127.0.0.1', 5000, LoggingNamespace) hri = HRIManager(socketIO) while not rospy.is_shutdown(): rospy.spin()
print 'PROD MODE *************' print "using prod port 8022" port = 8022 else: print "invalid environment" sys.exit(0) if commandArgs.type == 'serial': # initialize serial connection serialBaud = 9600 print "baud:", serialBaud #ser = serial.Serial('/dev/tty.usbmodem12341', 19200, timeout=1) # open serial ser = serial.Serial(serialDevice, serialBaud, timeout=1) # open serial print 'using socket io to connect to', server socketIO = SocketIO(server, port, LoggingNamespace) print 'finished using socket io to connect to', server def setServoPulse(channel, pulse): pulseLength = 1000000 # 1,000,000 us per second pulseLength /= 60 # 60 Hz print "%d us per period" % pulseLength pulseLength /= 4096 # 12 bits of resolution print "%d us per bit" % pulseLength pulse *= 1000 pulse /= pulseLength pwm.setPWM(channel, 0, pulse) if commandArgs.type == 'motor_hat' or commandArgs.type == 'adafruit_pwm':
#!/usr/bin/python import threading import serial import ast #ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1) from socketIO_client import SocketIO, LoggingNamespace socketIO = SocketIO('willclark.io:1642') exitFlag = 0 def on_camera_message(*args): print("Python received camera message!") def on_debug_message(*args): print("Python receiced debug message!") class SocketThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): socketIO.on("cameraMessage", on_camera_message) socketIO.on("debugMessage", on_debug_message) socketIO.wait()
import time import pyupm_grove as grove import pyupm_i2clcd as lcd from socketIO_client import SocketIO, BaseNamespace class SensorNamespace(BaseNamespace): def on_connect(self): print('[Connected]') socketIO = SocketIO('antoniohernandez.me', 8000) sensor_socket = socketIO.define(SensorNamespace, '/sensor') # Create the buttons buttonInp = grove.GroveButton(3) buttonInp2 = grove.GroveButton(7) buttonOut = grove.GroveButton(4) buttonOut2 = grove.GroveButton(8) available = capacity = 21 bandera=True # Initialize Jhd1313m1 at 0x3E (Lcd address) myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62) # RGB Blue myLcd.setColor(255, 55, 0) # Read the input and print, waiting one second between readings while 1: if buttonInp.value() == 1 or buttonInp2==1: available= available - 1 if available<0: sensor_socket.emit('signal', {'area' : 'A', 'availability' :
from socketIO_client import SocketIO, LoggingNamespace sock = SocketIO('http://localhost', 9000, LoggingNamespace) def backup_event(message): print(f"Backup file {message['file_name']}, size {message['file_size']} is done at time {message['date']}") def failed_backup(mes): print(f"Backup failed") sock.on('backup_successful', backup_event) sock.on('backup_failed', failed_backup) if __name__ == '__main__': sock.wait()
# This is a script to test the communication from the web socket to the ev3dev from socketIO_client import SocketIO import logging # Connects to the web socket socket = SocketIO('http://bd9c8794.ngrok.io') # Sends a move command to the web socket def moveCommand(): # Print for testing print("Hi") # Sets a direction/command direction = 'stop' # Prints for testing print("Hello World") # Sends the message to the web socket socket.emit('move',direction) # Alerts if there is an error with the web socket def onError(): print("ERROR") # Connects the functions with messages from the web socket socket.on('connect',moveCommand) socket.on('error',onError) # Makes the socket client wait for the web socket socket.wait()
# `pip install -U socketIO-client` # `pip install simplejson` # # --- Using this binding for one of your programs? --- # # Simply copy the code up until the line of hashes and paste it into your script. # Next, set the `SOCKET_IO_HOST` and `SOCKET_IO_PORT` values to the IP address and port number of the server your NodeSpace is running on from socketIO_client import SocketIO import json import time #Needs to be declared and set in client code SOCKET_IO_HOST = 'localhost' SOCKET_IO_PORT = 8888 socketIO = SocketIO(SOCKET_IO_HOST,SOCKET_IO_PORT) mostRecentTuple = '' #Need to parse JSON object to be readable by any language def processTuple(*args): print "Tuple read from space: " print args #Method to encode a Python object to JSON to be used as the argument of put(tuple) def encode(o): return json.dumps(o) #Put function def put(tuple): print "Adding: "+tuple
ser.write('H' + chr(2) + chr(speed) + chr(2) + chr(speed)) elif state == "movingBackward": ser.write('H' + chr(0) + chr(speed) + chr(0) + chr(speed)) elif state == "movingLeft": ser.write('H' + chr(0) + chr(speed) + chr(2) + chr(speed)) elif state == "movingRight": ser.write('H' + chr(2) + chr(speed) + chr(0) + chr(speed)) elif args[0] == "rotateleft": # robot rotates left ser2.write('H' + chr(2) + chr(TurnSpeed) + chr(0) + chr(0)) # writes a 5 byte sequence to the 2nd Trex that controls the platform motors # refer to secion 4.4 in the developer's manual for details about this sequence time.sleep(0.05) elif args[0] == "rotateright": # robot rotates right ser2.write('H' + chr(0) + chr(TurnSpeed) + chr(2) + chr(0)) time.sleep(0.05) elif args[0] == "rise": # tablet board rises up ser2.write('H' + chr(2) + chr(0) + chr(2) + chr(TurnSpeed)) elif args[0] == "fall": # tablet board falls down toward the home position ser2.write('H' + chr(2) + chr(0) + chr(0) + chr(TurnSpeed)) elif args[0] == "stop": # stops all platform and wheel movement for both trex boards ser.write('H' + chr(2) + chr(0) + chr(2) + chr(0)) ser2.write('H' + chr(2) + chr(0) + chr(2) + chr(0)) socketIO = SocketIO('52.34.97.173', 3000) # connects to url at port 3000 socketIO.on('raspberry', listener) # listens for an event called "raspberry" from app.js nodejs server program and then enters the listener function socketIO.wait(seconds=6000) # waits 6000 seconds until the socketIO connection times out
carList[index].roadID = status carList[index].mergeID = mergeRegion carList[index].xo = xo carList[index].xf = xf carList[index].vo = vo carList[index].vf = vf carList[index].a = a carList[index].b = b carList[index].c = c def listener(): global tfl rospy.init_node('zumo_go', anonymous=True) tfl = tf.TransformListener() time.sleep(1) while not rospy.is_shutdown(): time.sleep(0.05) proc() #print("Welcome to the UD Scaled Smart City") if __name__ == '__main__': global s socketIO = SocketIO('192.168.1.245', 5001, LoggingNamespace) socketIO.on('connect', on_connect) listener()
from gps import start_reading import requests from Point import MyPoint import camera #import temperature import led from pulse import SendPulse from BPM import get_BPM #from license import get_lisense import RPi.GPIO as GPIO LocationPoint = MyPoint() PhoneNumber = '0547777777' #PhoneNumber = get_lisense() socketIO = SocketIO('https://ipet-project-server.herokuapp.com/socket.io/') Pulse_List = [] Pulse_BPM = 0 BPM_Counter = 0 BPM_request = 0 BPM_list = [0,0,0,0,0,0,0,0] #temperature = temperature.Temperature() leds = led.Ledscontrol() Led_var = 0 #Temperature_var = 0
def run(self): self.socketIO = SocketIO('192.168.1.10', 3000, params={'did': 10563}) self.device_namespace = self.socketIO.define(Namespace, '/device') self._set_ready() self.socketIO.wait()
sys.exit(1) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Example MultiBot') parser.add_argument('token', help='token for logging in as bot ' + '(see SERVURL/token)') parser.add_argument('-c', '--chat_host', help='full URL (protocol, hostname; ' + 'ending with /) of chat server', default='http://localhost') parser.add_argument('-p', '--chat_port', type=int, help='port of chat server', default=5000) args = parser.parse_args() with SocketIO(args.chat_host, args.chat_port) as socketIO: login_namespace = socketIO.define(LoginNamespace, '/login') login_namespace.emit('connectWithToken', { 'token': args.token, 'name': "minimal bot" }) socketIO.wait()
Leftspeed = speed1 Rightspeed = speed1 else: pass if command == 'backward': if Leftspeed >= 0 and Rightspeed >= 0: Leftmode = 0 Rightmode = 0 Leftspeed = speed1 Rightspeed = speed1 else: pass socketIO = SocketIO('192.168.1.13', 3000) socketIO.on('serverToPython', listener) socketIO.emit('clientType', 'Python') socketIO.wait(seconds=6000) while 1: accel = 1.001 decel = 0.999 if command == 'forward': Rightspeed *= accel Leftspeed *= accel if command == '-forward': Rightspeed *= decel
def on_clientRefresh(data): #重新刷新微信号 refresh_name = data.get("refresh_name") print(data) if refresh_name: temp = { "refresh_name": refresh_name } update(**temp) def on_clientStart(data): #启动另一个手机,公众号位置 statrt_name = data.get("start_name") socketIO = SocketIO('127.0.0.1', 8000, LoggingNamespace) # Listen socketIO.on('start', on_satrt) socketIO.on('clientRefresh', on_clientRefresh) socketIO.on('clientLimit', on_clientLimit) socketIO.on('clientStart', on_clientStart) socketIO.wait() # def run_connect(): # socketIO = SocketIO('127.0.0.1', 8000, wait_for_connection=True) # # Listen # socketIO.on('connect', on_connect) # socketIO.on('start', on_satrt) # socketIO.on('clientRefresh', on_clientRefresh) # socketIO.on('clientLimit', on_clientLimit) # socketIO.on('clientStart', on_clientStart)
np.save(args.output_path + '/' + fpath, prediction) cache = [] image_cache = [] filename = fpath.split('_-_') args.socketIO.emit('update', { 'id': iname, "phase": 2, 'val': ind, 'max': len(onlyfiles) }) #args.socketIO.wait(seconds=1) if __name__ == '__main__': remote_uuid = "{0}{1}".format(uuid.uuid4(), "_deeplearning") socketIO = SocketIO('localhost', 30001, LoggingNamespace) parser = argparse.ArgumentParser() parser.add_argument('-m', '--model', type=str, default='pspnet50_ade20k', help='Model/Weights to use', choices=[ 'pspnet50_ade20k', 'pspnet101_cityscapes', 'pspnet101_voc2012' ]) parser.add_argument('-i', '--input_path', type=str, default='p1/', help='Path the input image')
import redis from socketIO_client import SocketIO import json __redisPool__ = redis.ConnectionPool(host='redis.rfddc.com', port='8003', password='******') __rc__ = redis.Redis(connection_pool=__redisPool__) if __name__ == '__main__': datamap = __rc__.hgetall( 'EYES_TOTLE_ORDERACTION_COUNTER_MAPKEY_1063YE4LJJA5S3UM') socketIO = SocketIO('https://message.wuliusys.com') emitMap = {} for key in datamap: emitMap[key.decode()] = datamap[key].decode() print(json.dumps(emitMap)) socketIO.emit("OrderActionCount", json.dumps(emitMap)) socketIO.wait(seconds=1) socketIO.disconnect()
from websockets import connect from json import loads, dumps import asyncio from socketIO_client import SocketIO from time import sleep WID = "BTFX" template_ticker = {"event": "subscribe", "channel": "ticker", "pair": ""} # ticker_response = ['channel_id','bid','bid_size','ask','ask_size','daily_change'\ # ,'daily_change_perc','last_price','volume','high','low'] pair_map = {} NotificationSocket = SocketIO('localhost', 8000) async def get_data(payloads): url = "wss://api.bitfinex.com/ws" async with connect(url) as websocket: for payload in payloads: await websocket.send(payload) async for message in websocket: parse(message) def parse(msg): res = loads(msg) # dict response means it's a response for corresponding to a 'send' if isinstance(res, dict): event = res['event']
def listPlayList(): with SocketIO('127.0.0.1', 3000, LoggingNamespace) as socketIO: socketIO.on('pushListPlaylist', on_getState_response) socketIO.emit('listPlaylist', '') socketIO.wait(seconds=1)
from pyrcb import IRCBot from socketIO_client import SocketIO, BaseNamespace import threading channel = '#tjcsl-avalon2' sio = SocketIO('localhost', 5000) class AvalonBot(IRCBot): def on_message(self, message, nickname, channel, is_query): if not is_query: if message.startswith("!propose "): private_ns.emit('propose players', [nickname, message.split()[1:]]) elif message.startswith("!kill "): private_ns.emit('kill player request', [nickname, message.split()[1]]) elif message == "!join": private_ns.emit('join game request', nickname) elif message == "!start": private_ns.emit('game start request', nickname) else: if message == "yes": private_ns.emit('vote request', [nickname, True]) elif message == "no": private_ns.emit('vote request', [nickname, False]) elif message == "pass": private_ns.emit('qvote request', [nickname, True]) elif message == "fail": private_ns.emit('qvote request', [nickname, False]) class PublicNamespace(BaseNamespace): def on_game_start_error(self, message):
def unmute(): # urllib2.urlopen('http://127.0.0.1:3000/api/v1/commands/?cmd=volume&value=unmute') with SocketIO('127.0.0.1', 3000, LoggingNamespace) as socketIO: socketIO.emit('unmute', '')
def __init__(self, slug): self.slug = slug self.sio = SocketIO('localhost', 3000, LoggingNamespace) self.result = None
from socketIO_client import SocketIO def on_sample(*args): print(args) socketIO = SocketIO('10.0.1.194', 8880) socketIO.on('openbci', on_sample) socketIO.wait(seconds=10)
import SerialPortCommunicator import sys import time from socketIO_client import SocketIO from threading import Thread socketIO = SocketIO('localhost', 8080) spc = SerialPortCommunicator.SerialPortCommunicator() def arreterCommande(): print('backend : arreter com') spc.arreterCommande() def verifierError(): spc.verifierError() def resetArduino(self): spc.resetArduino() def verifierSurtention(): spc.verifierSurtention() def valeurTension(): spc.lireTension() def refresh (): while(True): # tensions = spc.lireTension() # error = spc.verifierError() # surtention = spc.verifierSurtention() # socketIO.emit('sendInfo',tensions) # socketIO.emit('verifierSurtention',surtention) # socketIO.emit('verifierError', error) # print('envoi des tensions , verification urtension, et verification erreur driver') time.sleep(2)
walker.cleanup() def setInterval(func, timeSec): loop = asyncio.get_event_loop() loop.run_in_executor(None, func, timeSec) return loop cleanUpLoop = setInterval( launchCleanup, cfg.cleanupTimeOut ) #TODO:need to improve here , it should reset eventloop timer on every message recieved on socket #start socket client socketIO = SocketIO(cfg.socketIOHost, cfg.socketIOHostPort, LoggingNamespace) streamCmdSock = socketIO.define(Pirover_StreamerCmdSocket, '/StreamCmdSock') streamCmdSock.on('startstream', streamCmdSock.startStream) streamCmdSock.on('stopstream', streamCmdSock.stopstream) streamCmdSock.on('restream', streamCmdSock.restream) walkCmdSock = socketIO.define(Pirover_WalkerCmdSocket, '/WalkCmdSock') walkCmdSock.on('gofwd', walkCmdSock.goFwd) walkCmdSock.on('gorit', walkCmdSock.goRit) walkCmdSock.on('golft', walkCmdSock.goLft) walkCmdSock.on('gobkd', walkCmdSock.goBkd) walkCmdSock.on('stop', walkCmdSock.stop) walkCmdSock.on('estop', walkCmdSock.estop) socketIO.wait()