def start_process(self): """main process start from here. """ self.jwt_token = self.get_auth_code() # print("jwt token is: {}\n".format(self.jwt_token)) params1 = self.util_obj.socket_connection['params1'] params1["token"] = self.jwt_token # socketIO = SocketIO('192.168.0.60', 8080, params=params1) socketIO = SocketIO(self.util_obj.socket_connection['ip'], self.util_obj.socket_connection['port'], params=params1) socketIO.emit('server.version', {}) socketIO.on('server.version', self.get_server_version) pLocationNamespace = socketIO.define(self.LocationNamespace, '/location') filterData = self.util_obj.filterData pLocationNamespace.emit('location:monitor:send:filter', filterData) pLocationNamespace.on('location:monitor:receive', self.on_aaa_response) try: socketIO.wait() # engineSocket.wait() except ConnectionError as ex: print("got connection error %s" % ex)
def transmit(): while True: time.sleep(1) # If there's something to transmit, make a connection and sent it out if (len(queue) > 0): # Attempt to connect, transmit all in queue if success print("Attempting connection...") try: sio = SocketIO(sys.argv[1], verify=False, wait_for_connection=False, cert=('client.crt', 'client.key')) sio.wait(seconds=1) print("Connected") #sio.on('disconnect', on_disconnect) sio.on('response', on_response) queue2 = queue[:] # Copy the list to resolve a bug in how the for loop works for id in queue2: print("Transmitting " + str(id)) sio.emit('attend', {'ID': id}) sio.wait(seconds=1) #sio.disconnect() except ConnectionError: print('Server unreachable. Retrying shortly')
class WSClient(object): def __init__( self, addr, sendinit=None, on_data=None, on_open=None, on_close=None, raw=True ): """ addr: path to sio sendinit: tuple to emit on_data, on_open, on_close: functions to call """ self.addr = addr self.sendinit = sendinit on_data = on_data or print class Namespace(BaseNamespace): def on_connect(self, *data): if on_open: on_open(_tryJson(data, raw)) def on_disconnect(self, *data): if on_close: on_close(_tryJson(data, raw)) def on_message(self, data): on_data(_tryJson(data, raw)) self._Namespace = Namespace def run(self): self.socketIO = SocketIO(_SIO_URL_PREFIX, _SIO_PORT) self.namespace = self.socketIO.define(self._Namespace, self.addr) if self.sendinit: self.namespace.emit(*self.sendinit) self.socketIO.wait()
def connect_run_forever(self): socketIO = SocketIO(self.ws_url, self.ws_port, LoggingNamespace) socketIO.on('connect', self._on_connect) socketIO.on('disconnect', self._on_disconnect) socketIO.on('reconnect', self._on_reconnect) socketIO.on('msg', self._on_msg) socketIO.wait()
class TwoWayClient(object): def __init__(self): self.socketIO = SocketIO(host, port) def on_socket_open(*args): print("on_socket_open: ", args[0]) self.socketIO.emit('agent_alive', {'task_group_id': 'test_group', 'agent_id': '[World]'}) def on_disconnect(*args): print("Server disconnected", args[0]) def on_new_messgae(*args): print(args[0]) self.socketIO.on('socket_open', on_socket_open) self.socketIO.on('disconnect', on_disconnect) # This works self.socketIO.on('new_message', on_new_messgae) self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() while True: some_input = input("Hit ENTER to send message:") self.socketIO.emit('new_message', {'task_group_id': 'test_group', 'receiver_agent_id': 'Worker'}) def _receive_events_thread(self): self.socketIO.wait()
class WSClient(object): def __init__(self, addr, tickers=None, on_data=None, on_open=None, on_close=None, raw=False, tcp='tcp://127.0.0.1:7000'): ''' addr: path to sio sendinit: tuple to emit on_data, on_open, on_close: functions to call ''' # Socket to talk to server # Global variable as need to pass to function context = zmq.Context() zmqsocket = context.socket(zmq.PUB) zmqsocket.connect(tcp) print('IEX publisher connect to port 7000') # connect to correct socket self.addr = addr self.tickers = tickers on_data = on_data or print class Namespace(BaseNamespace): def on_connect(self, *data): if on_open: on_open(_tryJson(data, raw)) def on_disconnect(self, *data): if on_close: on_close(_tryJson(data, raw)) def on_message(self, data): prased = _tryJson(data, raw) on_data(prased) zmqsocket.send_multipart([ bytes('IEX', 'utf-8'), bytes(json.dumps(prased), 'utf-8') ]) self._Namespace = Namespace def run(self): self.socketIO = SocketIO(_SIO_URL_PREFIX, _SIO_PORT) self.namespace = self.socketIO.define(self._Namespace, self.addr) for t in self.tickers: if self.addr == '/1.0/tops': self.namespace.emit('subscribe', t) print('Subscribe to IEX {}'.format(t)) if self.addr == '/1.0/deep': subscribe_dict = {'channels': ['deep']} subscribe_dict['symbols'] = [t] self.namespace.emit('subscribe', json.dumps(subscribe_dict)) print('Subscribe to IEX DEEP {}'.format(t)) self.socketIO.wait()
class ImageSocketDynamicPutResult(ImageSocket): def __init__(self, hostname, port, max_queue_size=50): imageio.plugins.freeimage.download() self.hostname = hostname self.port = port self.queue = multiprocessing.JoinableQueue(maxsize=max_queue_size) print('Connecting on %s:%s' % (self.hostname, self.port)) self.socket = SocketIO(self.hostname, self.port) self.image_namespace = self.socket.define( AliasIdImageNamespace, Config.Socket.IMAGE_NAMESPACE) self.image_namespace.set_queue(self.queue) # self.image_namespace.queue = self.queue Thread(target=self.crawl_image).start() def crawl_image(self): self.socket.wait() def get_image_and_client(self, timeout=None): try: # print(id(self.queue), 'get_image_and_client', self.queue.qsize()) frame, client_id, alias_id = self.queue.get(timeout=timeout) self.queue.task_done() return frame, client_id, alias_id except queue.Empty: return None, None, None def put_result(self, **kwargs): self.image_namespace.emit(Config.Socket.RESULT_EVENT, kwargs)
class SIOHelper(GenBase): def __init__(self, psp, url, send=None, channel='', records=False): self.validate(url, 'sio') self.__type = 'sio' self.url = url self.send = send self.channel = channel self.records = records self._data = [] @asyncio.coroutine def getData(self): # FIXME class Namespace(BaseNamespace): def on_connect(self, *data): pass def on_disconnect(self, *data): pass def on_message(self, data): return data self.socketIO = SocketIO(self.url, 443) # needs base url namespace = self.socketIO.define(Namespace, self.url) # needs path in url if self.send: namespace.emit(*self.send) self.socketIO.wait()
class TwoWayClient(object): def __init__(self): self.socketIO = SocketIO(host, port) def on_connect(): print("Server connected") def on_disconnect(*args): print("Server disconnected") def on_reconnect(): print("Server reconnected") def on_time(*args): print(args[0]) self.socketIO.on('connect', on_connect) # This is not working self.socketIO.on('disconnect', on_disconnect) # This works self.socketIO.on('reconnect', on_reconnect) # This is not working self.socketIO.on('time', on_time) self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() while True: some_input = input("Please input: ") self.socketIO.emit('custom', some_input) def _receive_events_thread(self): self.socketIO.wait()
class TwoWayClient(object): def __init__(self): self.socketIO = SocketIO(host, port) def on_connect(): print("Server connected") def on_disconnect(*args): print("Server disconnected") def on_reconnect(): print("Server reconnected") def on_time(*args): print(args[0]) self.socketIO.on('connect', on_connect) # This is not working self.socketIO.on('disconnect', on_disconnect) # This works self.socketIO.on('reconnect', on_reconnect) # This is not working self.socketIO.on('time', on_time) self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() while True: some_input = input("Please input: ") self.socketIO.emit('custom', some_input) def _receive_events_thread(self): self.socketIO.wait()
def calibrate_PH(): print("hey") devices = AtlasI2C(); socket_url = "localhost" socketIO = SocketIO(socket_url, 9000, verify=False) def start_calibrate(*arg): try: print("should be something") print(arg) a = arg[0][u'data'] print(a) if(a=="low"): command = "cal,low,4" if(a=="medium"): command = "cal,mid,7" if(a=="high"): command = "cal,high,10" print(command) mutex.acquire() devices.query(command) print("Command Successful") mutex.release() except ValueError: print("Wrong Command") socketIO.on('welcome',start_calibrate) #Listen to calibrating event socketIO.wait() while True: #keep the thread alive to continue listening pass
class asyncSocketIo(): def __init__(self, bot, settings): self.bot = bot self.settings = settings try: self.receive_events_thread._stop except Exception as e: pass self.socketio = SocketIO('https://sockets.streamlabs.com', params={'token': settings['socket_token']}) self.socketio.on('event', self.on_event) self.socketio.on('disconnect', self.on_disconnect) self.receive_events_thread = threading.Thread( target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() def on_event(self, *args): DonationPointsModule.updatePoints(args, self.bot, self.settings) def on_disconnect(self, *args): log.error('Socket disconnected. Donations no longer monitored') self.bot.say('Socket disconnected. Donations no longer monitored') self.bot.execute_delayed(600, self.__init__, (self.bot, self.settings)) def _receive_events_thread(self): self.socketio.wait()
class RetentionDashboardBlacklistSocket(RetentionDashboardSocket): def __init__(self, hostname, port): imageio.plugins.freeimage.download() self.hostname = hostname self.port = port self.update_blacklist = queue.Queue() self.socket = SocketIO(self.hostname, self.port) self.retention_dashboard_namespace = self.socket.define( RetentionDashboardBlacklistNamespace, Config.Socket.RETENTION_DASHBOARD_NAMESPACE) self.retention_dashboard_namespace.update_blacklist = self.update_blacklist self.socket.on(Config.Socket.UPDATE_BLACKLIST, \ self.retention_dashboard_namespace.on_update_pedestrian_blacklist()) Thread(target=self.listen).start() def listen(self): self.socket.wait() def send_result(self, **kwargs): image_id = kwargs.get('image_id') self.retention_dashboard_namespace.emit(Config.Socket.NEW_FACE_EVENT, image_id) def get_update_blacklist(self): status = not self.update_blacklist.empty() if status: self.update_blacklist.get() return status
class TwoWayClient(object): def __init__(self): self.socketIO = SocketIO(host, port) def on_socket_open(*args): print("on_socket_open: ", args[0]) self.socketIO.emit('agent_alive', { 'task_group_id': 'test_group', 'agent_id': '[World]' }) def on_disconnect(*args): print("Server disconnected", args[0]) def on_new_messgae(*args): print(args[0]) self.socketIO.on('socket_open', on_socket_open) self.socketIO.on('disconnect', on_disconnect) # This works self.socketIO.on('new_message', on_new_messgae) self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() while True: some_input = input("Hit ENTER to send message:") self.socketIO.emit('new_message', { 'task_group_id': 'test_group', 'receiver_agent_id': 'Worker' }) def _receive_events_thread(self): self.socketIO.wait()
class socket: def __init__(self, id): self.id = id self.socketIO = None self.token = None self.missatge_doctor = None self.esperar = True self.createsocket(id) def desconectar(self, id): self.socketIO.emit('disconnect', {'id': id}) def createsocket(self, id): print id self.socketIO = SocketIO('https://ptin2018.herokuapp.com', params={"id": id}) print "Socket creado" self.socketIO.wait(seconds=3) def receive_general(self, *args): print "Recibido" print args[0] self.token = args[0] def response(self, *args): print "response" print args def response_doctor(self, *args): print "response doctor" print args self.missatge_doctor = args self.esperar = False def envia_confirmacio(self): self.socketIO.wait(seconds=1) self.socketIO.emit('generalAuthentication', { 'requester': self.id, 'token': self.token }) self.socketIO.on("generalResponse", self.response) self.socketIO.wait(seconds=1) def esperar_doctor(self): self.socketIO.on('pacientLocation', self.response_doctor) while self.esperar: self.socketIO.wait(seconds=3) self.esperar = True return self.missatge_doctor def envia_general(self, lat, lon): self.socketIO.emit('alarm', { 'type': 2, 'latitude': lat, 'longitude': lon }) print self.socketIO self.socketIO.on("generalAuthentication", self.receive_general) self.socketIO.wait(seconds=1)
def cytube(config): url = 'http://%s/socketconfig/%s.json' % ('cytu.be', config['channel']) server_list = req.get(url).json()['servers'] server = [i['url'] for i in server_list if i['secure'] is False][0] url = urlparse(server) sio = SocketIO(url.hostname, url.port, Client) instance = sio.get_namespace() instance.config(config) sio.wait()
class Client(object): def __init__(self): self.socketio = SocketIO("http://twitchplaysnintendoswitch.com:8110") self.socketio.on("disableInternet", self.on_disable_internet) self.socketio.on("enableInternet", self.on_enable_internet) self.socketio.on("getInternetStatus", self.on_get_internet_status) self.socketio.on("disconnect", self.on_disconnect) self.socketio.emit("join", "proxy") self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() self.start = time.process_time() self.end = time.process_time() self.status = False def _receive_events_thread(self): self.socketio.wait() def on_event(self, event): #print(event) pass def on_disconnect(self): print("disconnected") os.system("killall python3") def on_disable_internet(*args): print("disabling proxy!") client.status = False sudoPassword = "******" command = "service squid stop" p = os.system("echo %s|sudo -S %s" % (sudoPassword, command)) def on_enable_internet(*args): print("enabling proxy!") client.status = True sudoPassword = "******" command = "service squid restart" p = os.system("echo %s|sudo -S %s" % (sudoPassword, command)) def on_get_internet_status(*args): print("checking status!") self.socketio.emit("internetStatus", client.status) def loop(self): self.end = time.process_time() diffInMilliSeconds = (self.end - self.start) * 1000 if (diffInMilliSeconds > 1000 * 60 * 5): self.socketio.emit("join", "proxy") self.start = time.process_time()
def connectWSock(self): try: socketIO = SocketIO(self.operationConfigs['SOCK_ENDPOINT'], 3000, cookies={'sessionId': s.csrftoken}, wait_for_connection=False) socketIO.on('connect', on_connect) socketIO.on('/devices/updated', self.on_updated) socketIO.on('disconnect', on_disconnect) socketIO.on('reconnect', on_reconnect) socketIO.wait() except ConnectionError: logging.warning('Error connecting WebSockets\n')
class FrontendConnection: def __init__(self, host, port): self.host = host self.port = port self.socket = SocketIO(host, port, wait_for_connection=False) #self.receiveStatus() def on_posicion_response(self, *args): # print('Posicion enviada al frontend:', args[0], args[1]) pass def on_send_status_response(self, *args): # print('Estado enviado al frontend:', args[0], args[1]) pass def on_reconocimiento_response(self, response): if response == "ok": # print('Reconocimiento ok') pass else: # print("El servidor no te reconoce") exit() def on_change_attributtes_response(self, *args): # print('Cambiados atributos:', args[0], args[1]) pass def send(self, topic, data, callback): self.socket.emit(topic, data, callback) def recognizeAgent(self, agent_info): self.send("agent/recognition", agent_info, self.on_reconocimiento_response) def repositionAgent(self, agent_id, posicion): self.send("agent/position", { "position": posicion, "agent_id": agent_id }, self.on_posicion_response) def sendStatus(self, agent_id, status): self.send("agent/status", { "status": status, "agent_id": agent_id }, self.on_send_status_response) def changeAttributtes(self, agent_id, attributtes): self.send("agent/attributes", { "agent_id": agent_id, "attributes": attributtes }, self.on_change_attributtes_response) def wait(self, segs): self.socket.wait(segs)
def parse_rrcs(self) -> NoReturn: """ SocketIO connection to RIPE RIS to retrieve all active Route Collectors. """ try: socket_io = SocketIO('http://stream-dev.ris.ripe.net/stream', wait_for_connection=False) def on_msg(msg): self.available_ris = set(msg) socket_io.disconnect() socket_io.on('ris_rrc_list', on_msg) socket_io.wait(seconds=3) except Exception: log.warning('RIPE RIS server is down. Try again later..')
def socketio( url, callback, channel="", field="", sendinit=None, json=False, wrap=False, interval=1, ): """Connect to socketIO server and pipe results through the callback Args: url (str): url to connect to callback (callable): function to call on websocket data channel (str): socketio channel to connect through field (str): field to index result by sendinit (list): data to send on socketio connection open json (bool): load websocket data as json wrap (bool): wrap result in a list interval (int): socketio wai interval """ from socketIO_client_nexus import SocketIO as SIO o = urlparse(url) socketIO = SIO(o.scheme + "://" + o.netloc, o.port) if sendinit: socketIO.emit(sendinit) while True: _data = [] socketIO.on(channel, lambda data: _data.append(data)) socketIO.wait(seconds=interval) for msg in _data: if json: msg = json.loads(msg) if field: msg = msg[field] if wrap: msg = [msg] callback(msg)
class HandleServer(): def __init__(self,udp_ip,udp_port): # self.UDP_IP = udp_ip # self.UDP_PORT = udp_port # self.sock = socket.socket(socket.AF_INET, # Internet # socket.SOCK_DGRAM) # UDP # #self.sock.bind((self.UDP_IP, self.UDP_PORT)) self.socket = SocketIO('https://nicwebpage.herokuapp.com', verify =True) self.socket_a = self.socket.define(BaseNamespace,'/JT601') self.socket_a.emit("joinWebsite") self.mavlink_queue = queue.Queue() # receive_thread = threading.Thread(target= self.receive_data, daemon = True) # receive_thread.start() def send_data(self,data): #self.sock.sendto(data,(self.UDP_IP,self.UDP_PORT)) self.socket_a.emit("LAND",str(data)) self.socket.wait(seconds=0.01)
def calibrate_PH(): """ This function creates a client endpoint in socket connection between nodeJS and python process, listens continuosly to socketIO event, calibrates PH-circuit with received information. If calibration succeed, send back a success message. Else, send back an error message. """ devices = AtlasI2C(); socket_url = "localhost" socketIO = SocketIO(socket_url, 9000, verify=False) def start_calibrate(*arg): try: print(arg) a = arg[0][u'data'] print(a) commandList = { "low": "cal,low,4", "medium": "cal,mid,7","high":"cal,high,10"} command = commandList.get(a) logger.info(command) mutex.acquire() tempRecalibration = "T,"+str(measure_temperature(26)) devices.query(tempRecalibration) sleep(0.3) devices.query(command) sleep(0.3) status = devices.query('cal,?') status = status[-1] socketIO.emit('success',status) f = open("/home/pi/Public/main/Server/status.txt","w+") f.write(status) f.close() logger.info("Calibration Command Successful,"+str(a)) mutex.release() except : socketIO.emit("error") logger.debug("Wrong Command") socketIO.on('send_data',start_calibrate) #Listen to calibrating event socketIO.wait() while True: #keep the thread alive to continue listening to socket event pass
def main(): attempts = 0 while attempts < 3: try: socketIO = SocketIO(FMF_SERVER, 8080, Namespace, verify=False, wait_for_connection=False) socketIO.emit('authenticate', { "app_id": APP_ID, "device_id": DEVICE_ID }) socketIO.wait() except ConnectionError: attempts += 1 time.sleep(30) print "Can't connect to server, trying again..."
def socketio(url, callback, channel='', field='', sendinit=None, json=False, wrap=False, interval=1): o = urlparse(url) socketIO = SIO(o.scheme + '://' + o.netloc, o.port) if sendinit: socketIO.emit(sendinit) while True: _data = [] socketIO.on(channel, lambda data: _data.append(data)) socketIO.wait(seconds=interval) for msg in _data: if json: msg = json.loads(msg) if field: msg = msg[field] if wrap: msg = [msg] callback(msg)
class ImageSocket(): RESULT_SUCESSFUL = 'successful' RESULT_ALERT = 'alert' RESULT_ERROR = 'error' def __init__(self, hostname, port): imageio.plugins.freeimage.download() self.hostname = hostname self.port = port self.queue = queue.Queue() print('Connecting on %s:%s' % (self.hostname, self.port)) self.socket = SocketIO(self.hostname, self.port) self.image_namespace = self.socket.define( ImageNamespace, Config.Socket.IMAGE_NAMESPACE) self.image_namespace.queue = self.queue Thread(target=self.crawl_image).start() def crawl_image(self): self.socket.wait() def get_image_and_client(self, timeout=None): try: frame, client_id = self.queue.get(timeout=timeout) return frame, client_id except queue.Empty: return None, None def put_result(self, **args): client_id = args.get('client_id') status = args.get('status') message = {'clientSocketId': client_id} face_name = args.get('face_name') message['message'] = face_name message['status'] = status self.image_namespace.emit(Config.Socket.RESULT_EVENT, message) def release(self): # TODO: release this socket pass
class MainClient: def __init__(self, token): self.APIServer = '13.209.66.217' self.port = 3000 self.Sensor = Sensor(self) self.token = token self.gid = -1 self.gname = 'default gateway name' self.SocketIO = SocketIO( self.APIServer, self.port, headers = {'x-access-token': self.token}, ) self.Socket = self.SocketIO.define(BaseNamespace, '/gateway') self.IRSerial = IRSerial(self) self.IRSerialTemp = [] self._setOnListener() # Check Setting backfile if os.path.isfile('setting.json'): settings = json.loads(open('setting.json').read()) self.gid = settings['gid'] self.gname = settings['gname'] self._emit_notifyGid() else: self.macAddr = self._getMAC('wlan0') self._emit_gatewayInit() def Run(self): print('MainClient Start!') self.Sensor.start() while True: self.SocketIO.wait() def _setOnListener(self): self.Socket.on('reconnect', self._on_reconnect) self.Socket.on('res/gateway/create', self._on_setGid) self.Socket.on('res/sensor/create', self._on_setSID) self.Socket.on('req/sensor/refresh', self._on_refreshSensor) self.Socket.on('req/sensor/update/name', self._on_setSensorName) self.Socket.on('req/sensor/update/interval', self._on_setSensorInterval) self.Socket.on('req/remocon/learn', self._on_getIRSerial) self.Socket.on('req/remocon/learn/OK', self._on_updateIRSerial) def _on_reconnect(self): print('reconnect') self._emit_notifyGid() def _on_setGid(self, obj): if obj['status'] is True: self.gid = obj['data']['gatewayID'] f = open('setting.json', 'w', encoding='utf-8') f.write(json.dumps({ 'gid': self.gid, 'gname': self.gname }, ensure_ascii=False, indent="\t")) f.close() self._emit_notifyGid() def _on_setSID(self, obj): if obj['status'] is True: baseID = obj['data']['_id'] sid = obj['data']['sensorID'] self.Sensor.updateServerSensorID(baseID, sid) def _on_refreshSensor(self, obj): self.Sensor.refreshSensor(obj['sid']) def _on_setSensorName(self, obj): self.Sensor.updateSensorName(obj['sid'], obj['name']) def _on_setSensorInterval(self, obj): self.Sensor.updateSensorInterval(obj['sid'], obj['interval']) def _on_getIRSerial(self, obj): print('On getIRSerial!') # self.IRSerial.mode = 'in' # self.IRSerial.start() def _on_updateIRSerial(self, obj): self.IRSerial.start() def _emit_gatewayInit(self): self.Socket.emit('req/gateway/create',{ 'token': self.token, 'name': self.gname, 'mac_addr': self.macAddr }) self.SocketIO.wait(seconds=1) def _emit_notifyGid(self): self.Socket.emit('req/connection/init',{ 'gid': self.gid }) self.SocketIO.wait(seconds=1) def _emit_createSensor(self, s): self.Socket.emit('req/sensor/create', { '_id' : s['bid'], 'gid' : self.gid, 'type' : s['type'], 'name' : s['name'], }) def _emit_updateValueSensor(self, sid, value, time): self.Socket.emit('req/sensor/update', { 'sid' : sid, 'gid' : self.gid, 'token': self.token, 'time' : time, 'value' : value, }) def _emit_res_getIRSerial(self): self.Socket.emit('res/remocon/learn') def _getMAC(self, interface): try: str = open('/sys/class/net/%s/address' %interface).read() except: str = "00:00:00:00:00:00" return str[0:17]
pwm.start(float(85) / 10.0 + 2.5) from socketIO_client_nexus import SocketIO, LoggingNamespace Sock = SocketIO('38.88.74.79', 80) def unlock(): duty = float(185) / 10.0 + 2.5 pwm.ChangeDutyCycle(duty) #start = time.time() print("door unlocked") def lock(): duty = float(85) / 10.0 + 2.5 pwm.ChangeDutyCycle(duty) print("door locked") def status(*args): if args[0] == 1: lock() elif args[0] == 0: unlock() else: print("error") while True: #print("waiting\n") Sock.on("lockChanged", status) Sock.wait(seconds=1)
socketIO.emit('newMessage',{'chat':message.sender.id,'message':content+'.ogg','type':'ogg','caption':message.caption}) else: socketIO.emit('newMessage',{'chat':message.sender.id,'message':'Contenido No soportado'}) ##### SOCKET LISSENER ##### socketIO.on('connect', on_connect) socketIO.on('welcome', on_welcome) socketIO.on('reconnect', on_reconnect) socketIO.on('getQr',on_getQr) socketIO.on('matchUpdate',on_matchUpdate) socketIO.on('giveScreen',on_giveScreen) socketIO.on('sendText',on_sendText) socketIO.on('sendFile',on_sendFile) socketIO.on('deleteChat',on_deleteChat) socketIO.wait() # def on_sendFile(*args): # try: # id = args[0][0] # caption = args[0][1] # typeMessage = args[0][2] # fileMessage = args[0][3] # send = Thread(target=sendFile,args=(id,caption,typeMessage,fileMessage)) # send.start() # except Exception as e: # write_log('Socket-Error',traceback.format_exc()) # socketIO.emit('errorSendFile',{'chat':id,'message':caption,'sendBy':'Agent'}) # errorSend(traceback.format_exc())
class Client(object): def __init__(self): self.socketio = SocketIO("http://twitchplaysnintendoswitch.com:8110") # self.socketio.on("controllerState1", self.on_controller_state1) # self.socketio.on("controllerState2", self.on_controller_state2) # self.socketio.on("controllerState3", self.on_controller_state3) self.socketio.on("controllerState5", self.on_controller_state1) self.socketio.on("turnTimesLeft", self.on_turn_times_left) self.socketio.emit("join", "wiiu3dscontroller") self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() self.start = time.clock() self.end = time.clock() self.botstart = time.clock() self.botend = time.clock() self.controllerStart = time.clock() self.controllerEnd = time.clock() self.lockon = False self.yeaVotes = 0 self.nayVotes = 0 self.voting = False self.currentPlayers = [] self.laglessEnabled = True self.currentGame = "none" self.oldArgs2 = "800000000000000 128 128 128 128" def _receive_events_thread(self): self.socketio.wait() def on_event(self, event): #print(event) pass def on_controller_command(*args): nextCommands.append(args) def on_turn_times_left(*args): try: client.currentPlayers = args[1]["usernames"] except: pass def on_controller_state(*args): if(not client.laglessEnabled): return state = args[1] cNum = args[2] print("controller state" + str(cNum) + ":", state) client.oldArgs2 = state controller = None if(cNum == 0): controller = controller1 elif(cNum == 1): controller = controller2 elif(cNum == 2): return cNum = 1 controller = controller2 elif(cNum == 3): return cNum = 1 controller = controller2 elif(cNum == 4): return cNum = 1 controller = controller2 controller.reset() inputs = state.split() cPlayer = "" try: cPlayer = client.currentPlayers[cNum] except: pass btns = inputs[0] LX = inputs[1] LY = inputs[2] RX = inputs[3] RY = inputs[4] controller.dpad = int(btns[0]) if (btns[1] == "1"): controller.lstick = 1; if (btns[2] == "1"): controller.l = 1; if (btns[3] == "1"): controller.zl = 1; if (btns[4] == "1"): controller.minus = 1; if (btns[5] == "1"): try: if (cPlayer.lower() in modlist): controller.capture = 1 else: controller.capture = 0 except: controller.capture = 0 if (btns[6] == "1"): controller.a = 1; if (btns[7] == "1"): controller.b = 1; if (btns[8] == "1"): controller.x = 1; if (btns[9] == "1"): controller.y = 1; if (btns[10] == "1"): controller.rstick = 1; if (btns[11] == "1"): controller.r = 1; if (btns[12] == "1"): controller.zr = 1; if (btns[13] == "1"): try: if (cPlayer.lower() in pluslist): controller.plus = 1 else: controller.plus = 0 except: controller.plus = 0 if (btns[14] == "1"): try: if (cPlayer.lower() in modlist): controller.home = 1 else: controller.home = 0 except: controller.home = 0 try: controller.LX = int(LX) controller.LY = 255-int(LY) controller.RX = int(RX) controller.RY = 255-int(RY) except: pass duration = 0.001 reset = 0 if(cNum == 0): send_and_reset(duration, reset) elif(cNum == 1): send_and_reset2(duration, reset) elif(cNum == 2): send_and_reset3(duration, reset) elif(cNum == 3): send_and_reset4(duration, reset) # player 1: def on_controller_state1(*args): client.on_controller_state(args[1], 0) def handleChat(self, username, message): print(message) # handle chat messages here def decreaseQueue(self): # handle queue from handlechat pass def loop(self): # control switch here: # every 5 minutes: self.botend = time.clock() diffInMilliSeconds = (self.botend - self.botstart)*1000 if(diffInMilliSeconds > 1000*60*5): self.socketio.emit("join", "wiiu3dscontroller") self.botstart = time.clock() # msg = "Join the discord server! https://discord.gg/ARTbddH\ # hate the stream delay? go here! https://twitchplaysnintendoswitch.com" # twitchBot.chat(msg) # every 6 seconds, probably doesn't need to do this so often: self.controllerEnd = time.clock() diffInMilliSeconds2 = (self.controllerEnd - self.controllerStart)*1000 if(diffInMilliSeconds2 > 6000): self.socketio.emit("join", "wiiu3dscontroller") self.controllerStart = time.clock() response = twitchBot.stayConnected() if(response != "none"): # prevent crash try: username = re.search(r"\w+", response).group(0) # return the entire match username = username.lower() message = CHAT_MSG.sub("", response) message = message.strip() message = message.lower() self.handleChat(username, message) except: pass self.decreaseQueue() def _receive_events_thread(self): self.socketio.wait()
class TelemetryReporter: """ This is used to report boat and environment statistics (e.g. position, heading, wind speed & direction) to a telemetry server for remote monitoring. """ def __init__(self): self.reporter = None self.socketIO = None self.rosbag_process = None # Register as a ROS node rospy.init_node('telemetry_reporter') # Listen for ROS boat position messages TODO Reference name from another file self.subscribers = {} self.publishers = {} # Listen for SIGINT (process termination requests) signal.signal(signal.SIGINT, self.terminate) def connect(self, server_address, port, use_ssl=False): print('Connecting to {} on port {} {}using SSL'.format(server_address, port, '' if use_ssl else 'without ')) self.socketIO = SocketIO(server_address, port, verify=(not use_ssl)) self.reporter = self.socketIO.define(ReportingNamespace, '/reporting') self.reporter.on('publishROSMessage', self._handle_server_publish_msg) self.reporter.on('getTopics', self._handle_get_published_topics_request) self.reporter.on('startStopRosbag', self.start_stop_rosbag) self.socketIO.wait() # Don't finish execution def terminate(self, *args): if self.socketIO: print('Disconnecting...') self.socketIO.disconnect() def listen_to_topic(self, topic_name, msg_type, save_to_db=True, max_transmit_rate=0, queue_size=1): """ Sets up a subscriber on the given ROS topic. :param {string} topic_name: the name of the ROS topic :param {string|genpy.Message} msg_type: the type of ROS message :param {boolean} save_to_db: whether or not messages sent to the server should be stored in the database or just forwarded on to connected observers :param {number} max_transmit_rate: the maximum rate at which to broadcast updates to the server (Hz) :param {number} queue_size: the maximum number of ROS messages to hold in the buffer :return: True if a subscriber was successfully registered, False otherwise """ # Try to resolve the message type if it is not already a ROS message class if not issubclass(msg_type, Message): if type(msg_type) == str: # Try to look up in our dictionary msg_type = ROS_MSG_TYPES.get(msg_type) if not msg_type: # Couldn't find given message type in dictionary return False else: # Not a subclass of genpy.Message and not a string return False # Define a handler to serialize the ROS message and send it to the server def msg_handler(msg): self.transmit_message(topic_name, msg, msg_type, save_to_db=save_to_db) self.subscribers[topic_name] = rospy.Subscriber(topic_name, msg_type, msg_handler, queue_size=queue_size) print('Registered listener for ' + topic_name) return True def transmit_message(self, topic_name, msg, msg_type, save_to_db=True): """ Transmits a message to the server. :param {string} topic_name: the name of the ROS topic :param {genpy.Message} msg: the actual ROS message :param {type} msg_type: the type of ROS message :param {boolean} save_to_db: whether or not the message should be saved to the database """ if not self.reporter: print('Not connected to /reporter') return payload = { 'topicName': topic_name, 'type': msg_type.__name__, 'data': self._serialize_ros_message(msg), 'timestamp': str(datetime.now()), 'saveToDb': save_to_db } self.reporter.emit('message', payload) @staticmethod def _serialize_ros_message(msg): """ Converts a ROS message into a dictionary that can be serialized and sent to the server. :param {genpy.Message} msg: the raw ROS message :return: a dictionary with the important values from the message """ msg_type = type(msg) if msg_type == Pose2D: return { 'x': msg.x, 'y': msg.y, 'theta': msg.theta } elif msg_type == Float32 \ or msg_type == Float64 \ or msg_type == UInt8 \ or msg_type == UInt16 \ or msg_type == UInt32 \ or msg_type == UInt64: return msg.data elif msg_type == Float32MultiArray \ or msg_type == Float64MultiArray: return list(msg.data) elif msg_type == GridMap: return { 'grid': TelemetryReporter._serialize_ros_image_message(msg.grid), 'minLatitude': msg.minLatitude.data, 'maxLatitude': msg.maxLatitude.data, 'minLongitude': msg.minLongitude.data, 'maxLongitude': msg.maxLongitude.data } elif msg_type == WaypointList: points = [] for lat, long in zip(msg.latitudes.data, msg.longitudes.data): points.append({'lat': lat, 'long': long}) return points return None @staticmethod def _serialize_ros_image_message(msg): """ Converts a ROS Image message into a dictionary. :param msg: the ROS Image message (from sensor_msgs.msg) :return: a dictionary with the image width, height, encoding, and pixel data """ return { 'height': msg.height, 'width': msg.width, 'encoding': msg.encoding, 'data': msg.data } def publish_message(self, topic_name, msg_type, data): """ Publishes a message to the given ROS topic. :param {string} topic_name: the name of the ROS topic to publish to :param {type} msg_type: the ROS message type :param data: the message payload """ # Turn the data into a ROS message msg = self._build_ros_msg(data, msg_type) if msg is not None: # Register a publisher if one is not already registered for this topic if topic_name not in self.publishers: self.configure_publisher(topic_name, msg_type) # Note: Messages sent shortly after configuring publisher will likely be lost. # See https://github.com/ros/ros_comm/issues/176 for more info. self.publishers[topic_name].publish(msg) def _convert_unicode(self, data): """ Recursively converts attributes unicode string attributes or elements on an object to UTF-8 strings. :param data: a dict, list, or string to convert to UTF-8. :return: the converted object """ if isinstance(data, dict): return {self._convert_unicode(key): self._convert_unicode(value) for key, value in data.iteritems()} elif isinstance(data, list): return [self._convert_unicode(element) for element in data] elif isinstance(data, unicode): return data.encode('utf-8') else: return data def configure_publisher(self, topic_name, msg_type, queue_size=1): """ Sets up a ROS message publisher. :param topic_name: the name of the ROS topic to publish to :param msg_type: the type of messages to publish :param queue_size: the number of messages to queue up for sending before dropping old ones """ if topic_name not in self.publishers: self.publishers[topic_name] = rospy.Publisher(topic_name, msg_type, queue_size=queue_size) def _build_ros_msg(self, data, msg_type): """ Constructs a ROS message to transmit the given data. :param data: the data to hold in the message :param {genpy.Message} msg_type: the type of message to construct :return: a ROS message containing the data """ try: # TODO Ints and arrays of ints if msg_type == UInt8 \ or msg_type == UInt16: # Integers return msg_type(data=int(data)) if msg_type == Float32 \ or msg_type == Float64: # Floating-point numbers return msg_type(data=float(data)) if msg_type == Float32MultiArray or msg_type == Float64MultiArray: # Array of floating-point numbers return msg_type(data=[float(x) for x in data]) if msg_type == String: return msg_type(data=data) if msg_type == Pose2D and 'x' in data and 'y' in data: return Pose2D(x=float(data['x']), y=float(data['y'])) except ValueError: error_msg = 'Problem parsing data: ' + data + '. Supposed to be of type ' + str(msg_type) self.publish_message(ERROR_TOPIC_NAME, String, error_msg) return None def _handle_server_publish_msg(self, msg): """ Handles WebSockets "publish" events from the server by publishing their info to ROS. :param msg: the WebSockets message payload """ # Convert Unicode strings to UTF-8 msg = self._convert_unicode(msg) # Make sure message type is specified and try to resolve it to ROS message class if 'type' in msg: msg_type = ROS_MSG_TYPES.get(msg['type']) if not msg_type: return self._publish_error_msg('Could not understand message type "' + msg['type'] + '".') else: return self._publish_error_msg('Attribute "type" must be specified.') # Check for the topic name if 'topicName' not in msg: return self._publish_error_msg('Attribute "topicName" must be specified.') # Check for the message payload elif 'data' not in msg: self._publish_error_msg('Attribute "data" must be specified.') self.publish_message(msg['topicName'], msg_type, msg['data']) def _publish_error_msg(self, error): """ Logs an error by publishing it to the error log topic. :param {string} error: the content of the message """ print(error) self.publish_message(ERROR_TOPIC_NAME, String, String(data=error)) def _handle_get_published_topics_request(self, data): """ Gets a list of the published ROS topics and their associated message types :param :return: A list of dictionaries of the form {name: topicName, type: topicType} :rtype list """ res = [] # Reformat the list items as dictionaries rather than arrays for topic in rospy.get_published_topics(): res.append({ 'name': topic[0], 'type': topic[1] }) # Send the topics to the server self.reporter.emit('topicList', res) def start_stop_rosbag(self, data): """ Handles a request from an observer to start or stop rosbag on the boat. This currently only supports one instance of rosbag. Attempts to start a second instance without first ending the first will be ignored. :param data: the WebSockets message from the observer """ if 'action' not in data: return action = data['action'] if self.rosbag_process and action == 'stop': # Stop rosbag print('Stopping rosbag...') os.killpg(os.getpgid(self.rosbag_process.pid), signal.SIGINT) self.rosbag_process = None elif action == 'start': # Start rosbag print('Starting rosbag...') cmd = 'rosbag record --all' if 'args' in data: cmd += ' ' + data['args'] self.rosbag_process = subprocess.Popen(cmd, cwd=os.environ.get('HOME'), shell=True, preexec_fn=os.setsid)
def on_Response_C(*args): print('I got a reponse from server for event_C', args) def FuncA(): print('FuncA: Now I got a message from server.') socketIO = SocketIO('localhost', 3000, LoggingNamespace) socketIO.on('connect', on_connect) socketIO.on('disconnect', on_disconnect) socketIO.on('reconnect', on_reconnect) socketIO.on('event_A', FuncA) # Listen socketIO.on('Response_B', on_Response_B) socketIO.emit('event_B') socketIO.emit('event_B') socketIO.wait(seconds=1) # Stop listening socketIO.off('Response_B') socketIO.emit('event_B') socketIO.wait(seconds=1) # Listen only once socketIO.once('Response_C', on_Response_C) socketIO.emit('event_C') # Activate aaa_response socketIO.emit('event_C') # Ignore socketIO.wait(seconds=1)
pulse_duration = pulse_end - pulse_start distance = round(17150 * pulse_duration, 2) return distance # get_measurement() # while (True): # distance = get_measurement() # print('Distance is:', distance) # time.sleep(.05) thread = Thread(target=continuous_loop) thread.setDaemon(True) thread.start() socket.on('connect', on_connect) socket.on('disconnect', on_disconnect) socket.on('reconnect', on_reconnect) socket.on('command', on_command) socket.on('socket_id', on_socket_id) socket.emit('connect_rover') socket.wait()