def start(self, code): def run(sdk_conn): '''The run method runs once Cozmo SDK is connected.''' self._robot = sdk_conn.wait_for_robot() self._origin = self._robot.pose self.cubes_to_numbers = {} for key in self._robot.world.light_cubes: self.cubes_to_numbers[self._robot.world.light_cubes.get( key).object_id] = key self.resetCubes() self.resetCustomObjects() self._robot.camera.image_stream_enabled = True bot = self import cozmo exec(code, locals(), locals()) from ws4py.client.threadedclient import WebSocketClient self._camClient = WebSocketClient('ws://localhost:9090/camPub') self._camClient.connect() self._wsClient = WebSocketClient('ws://localhost:9090/WsPub') self._wsClient.connect() self._dataPubThread = threading.Thread( target=self.feedRobotDataInThread) self._dataPubThread.daemon = True self._dataPubThread.start() cozmo.setup_basic_logging() cozmo.robot.Robot.drive_off_charger_on_connect = False cozmo.connect(run) self._robot = None
def start(self): # Web Sockets # self._camClient = WebSocketClient('ws://localhost:8080/camPub') # self._camClient.connect() self._wsClient = WebSocketClient('ws://localhost:8080/WsPub') self._wsClient.connect() # self._consoleClient = WebSocketClient('ws://localhost:8080/consolePub') # self._consoleClient.connect() # # self._cozmo_messagesClient = WebSocketClient('ws://localhost:8080/cozmo_messagesPub') # self._cozmo_messagesClient.connect() self._blocksClient = WebSocketClient('ws://localhost:8080/blocksPub') self._blocksClient.connect()
def _create_websocket(self, url, reconnect=False): if url is None: raise GatewayNotFound() log.info('websocket gateway found') self.ws = WebSocketClient(url, protocols=['http-only', 'chat']) # this is kind of hacky, but it's to avoid deadlocks. # i.e. python does not allow me to have the current thread running if it's self # it throws a 'cannot join current thread' RuntimeError # So instead of doing a basic inheritance scheme, we're overriding the member functions. self.ws.opened = self._opened self.ws.closed = self._closed self.ws.received_message = self._received_message self.ws.connect() log.info('websocket has connected') if reconnect == False: second_payload = { 'op': 2, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', '$device': 'discord.py', '$referrer': '', '$referring_domain': '' }, 'v': 2 } } self.ws.send(json.dumps(second_payload))
def __init__(self, WebSocket=None, notify_file=None, config=None): self.notify_lock = RLock() if not config: self.config = ConfigService() else: self.config = config if not notify_file: notify_file = self.config.get('general', 'notify_file') if not WebSocket: SOCKET_HOST = self.config.get('socket', 'host') SOCKET_PORT = self.config.get('socket', 'port') self.ws = WebSocketClient('ws://' + SOCKET_HOST + ':' + SOCKET_PORT + '/') self.ws.connect() else: self.ws = WebSocket self.notify_file = notify_file self.backtrack = int(self.config.get('notify', 'backtrack', 30)) self.event_id = 0 self.events = []
def GET(self): url = 'ws://{0}:{1}/yapt/ws?clientname={2}'.format( c.conf.YAPT.WebUiAddress, str(c.conf.YAPT.WebUiPort), c.conf.YAPT.WebUiPlugin) wsc = WebSocketClient(url=url) wsc.connect() fname = './logs/info.log' fsize = os.stat(fname).st_size iter = 0 lines = 17 with open(fname, 'r') as f: bufsize = fsize - 1 data = [] while True: iter += 1 f.seek(fsize - bufsize * iter) data.extend(f.readlines()) if len(data) >= lines or f.tell() == 0: # print(''.join(data[-lines:])) wsc.send(payload=json.dumps({ 'action': c.UI_ACTION_INIT_LOG_VIEWER, 'data': ''.join(data[-lines:]) })) break wsc.close() pass
def printlog(percent, num): global ws global host global port stats = { 'percent': str(percent), 'img_number': str(cs), 'tot_images': str(slices) } post_processing = { 'name': name, 'pid': str(myPID), 'started': str(t0), 'completed': str(completed), 'completed_time': str(completed_time), 'stats': stats } str_log = {'post_processing': post_processing} #str_log='{"post_processing":{"name": "'+name+'","pid": "'+str(myPID)+'","started": "'+str(t0)+'","completed": "'+str(completed)+'","completed_time": "'+str(completed_time)+'","stats":{"percent":"'+str(percent)+'","img_number":'+str(cs)+',"tot_images":'+str(slices)+'}}}' message = {'type': 'post_processing', 'data': str_log} try: ws.send(json.dumps(message)) except Exception, e: print str(e) ws = WebSocketClient('ws://' + host + ':' + port + '/') ws.connect()
def __init__(self, **kwargs): self._is_logged_in = False self.user = None self.servers = [] self.private_channels = [] self.token = '' self.events = { 'on_ready': _null_event, 'on_disconnect': _null_event, 'on_error': _null_event, 'on_response': _null_event, 'on_message': _null_event } self.ws = WebSocketClient(endpoints.WEBSOCKET_HUB, protocols=['http-only', 'chat']) # this is kind of hacky, but it's to avoid deadlocks. # i.e. python does not allow me to have the current thread running if it's self # it throws a 'cannot join current thread' RuntimeError # So instead of doing a basic inheritance scheme, we're overriding the member functions. self.ws.opened = self._opened self.ws.closed = self._closed self.ws.received_message = self._received_message self.ws.connect() # the actual headers for the request... # we only override 'authorization' since the rest could use the defaults. self.headers = { 'authorization': self.token, }
def __init__(self, **kwargs): self.token = '' gateway = requests.get(endpoints.GATEWAY) if gateway.status_code != 200: raise GatewayNotFound() gateway_js = gateway.json() url = gateway_js.get('url') if url is None: raise GatewayNotFound() self.ws = WebSocketClient(url, protocols=['http-only', 'chat', 'voice']) # this is kind of hacky, but it's to avoid deadlocks. # i.e. python does not allow me to have the current thread running if it's self # it throws a 'cannot join current thread' RuntimeError # So instead of doing a basic inheritance scheme, we're overriding the member functions. self.ws.opened = self._opened self.ws.closed = self._closed self.ws.received_message = self._received_message # the actual headers for the request... # we only override 'authorization' since the rest could use the defaults. self.headers = { 'authorization': self.token, }
def setUp(self, sock): self.sock = MagicMock(spec=socket.socket) sock.socket.return_value = self.sock sock.getaddrinfo.return_value = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 80, 0, 0))] self.client = WebSocketClient(url="ws://127.0.0.1/")
def __init__(self, url): self.ws = WebSocketClient(url) self.queue = Queue.Queue() def onmessage(m): print "received: %s" % m self.queue.put(unicode(str(m), 'utf-8')) self.ws.received_message = onmessage
def main(): from ws4py.client.threadedclient import WebSocketClient from fabtotum.fabui.notify import NotifyService from fabtotum.utils.pyro.gcodeclient import GCodeServiceClient from fabtotum.fabui.config import ConfigService from fabtotum.os.paths import RUN_PATH import logging import argparse import os # Setup arguments parser = argparse.ArgumentParser() parser.add_argument("-L", "--log", help="Use logfile to store log messages.", default='/var/log/fabui/gpiomonitor.log') parser.add_argument("-p", "--pidfile", help="File to store process pid.", default=os.path.join(RUN_PATH, 'gpiomonitor.pid') ) # Get arguments args = parser.parse_args() pidfile = args.pidfile with open(pidfile, 'w') as f: f.write( str(os.getpid()) ) config = ConfigService() # Load configuration NOTIFY_FILE = config.get('general', 'notify_file') ################################################################## SOCKET_HOST = config.get('socket', 'host') SOCKET_PORT = config.get('socket', 'port') ################################################################## EVENT_PIN = config.get('totumduino', 'event_pin') # Pyro GCodeService wrapper gcs = GCodeServiceClient() ws = WebSocketClient('ws://'+SOCKET_HOST +':'+SOCKET_PORT+'/') ws.connect(); # Notification service ns = NotifyService(ws, NOTIFY_FILE, config) # Setup logger logger2 = logging.getLogger('GPIOMonitor') logger2.setLevel(logging.DEBUG) fh = logging.FileHandler(args.log, mode='w') #~ formatter = logging.Formatter("%(name)s - %(levelname)s : %(message)s") formatter = logging.Formatter("[%(asctime)s] %(levelname)s : %(message)s") fh.setFormatter(formatter) fh.setLevel(logging.DEBUG) logger2.addHandler(fh) gpioMonitor = GPIOMonitor(ns, gcs, logger2, EVENT_PIN) gpioMonitor.start() gpioMonitor.loop()
def __init__(self, IP): sock = socket.gethostbyname(socket.gethostname()) # self.addr = "ws://{}:81/ws".format(sock) print('Connecting...') self.addr = IP self.socket = WebSocketClient(self.addr) self.socket.connect() print('Socket connected:', IP)
def start(self, code): from ws4py.client.threadedclient import WebSocketClient self._wsClient = WebSocketClient('ws://localhost:9090/WsPub') self._wsClient.connect() if self._aruco: self._dataPubThread = threading.Thread( target=self.feedRobotDataInThread) self._dataPubThread.daemon = True self._dataPubThread.start() bot = self import cozmo exec(code, locals(), locals())
def killAndRaise(): ''' global php_script_path command = 'sudo php ' + php_script_path +'/kill_raise.php ' + str(monitorPID) + ' "python" "' + python_script_path + '/monitor.py" &' print command os.system(command) ''' global host global port global ws global SOCKET_CONNECTED try: ws = WebSocketClient('ws://' + host + ':' + port + '/') ws.connect() SOCKET_CONNECTED = True except Exception as inst: SOCKET_CONNECTED = False
def connect(self): try: if self.client: try: self.client.close() except: pass self.client = WebSocketClient("ws://" + self.config['hostName'] + ':' + str(self.config['port']), exclude_headers=["Origin"]) self.client.opened = self.on_open self.client.closed = self.on_close self.client.received_message = self.on_message self.client.sock.settimeout(self.config['timeout']) self.client.connect() self.connectEvent.wait(self.config['timeout'] if self.clientKey else self.config['promptTimeout']) except: pass
def run_gevent(): from gevent import monkey; monkey.patch_all() import gevent from ws4py.client.geventclient import WebSocketClient ws = WebSocketClient(wss_url) ws.connect() ws.send("hello") def incoming(): while True: m = ws.receive() if m is not None: print m else: break ws.close() gevent.joinall([gevent.spawn(incoming)])
def test_thread_is_started_once_connected(self, sock): s = MagicMock(spec=socket.socket) sock.socket.return_value = s sock.getaddrinfo.return_value = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 80, 0, 0))] c = WebSocketClient(url="ws://127.0.0.1/") def exchange1(*args, **kwargs): yield b"\r\n".join([ b"HTTP/1.1 101 Switching Protocols", b"Connection: Upgrade", b"Sec-Websocket-Version: 13", b"Content-Type: text/plain;charset=utf-8", b"Sec-Websocket-Accept: " + b64encode(sha1(c.key + WS_KEY).digest()), b"Upgrade: websocket", b"Date: Sun, 26 Jul 2015 12:32:55 GMT", b"Server: ws4py/test", b"\r\n" ]) for i in range(100): time.sleep(0.1) yield Frame(opcode=OPCODE_TEXT, body=b'hello', fin=1).build() s.recv.side_effect = exchange1() self.assertFalse(c._th.is_alive()) c.connect() time.sleep(0.5) self.assertTrue(c._th.is_alive()) def exchange2(*args, **kwargs): yield Frame(opcode=OPCODE_CLOSE, body=b'', fin=1).build() s.recv.side_effect = exchange2() time.sleep(0.5) self.assertFalse(c._th.is_alive())
def start(self): from ws4py.client.threadedclient import WebSocketClient self._client = WebSocketClient('ws://localhost:9090/highlightPub') self._client.connect()
def start(port=8080): blocksClient = WebSocketClient('ws://localhost:' + str(port)+ '/blocksPub') blocksClient.connect()
"scene": "1.1" } firstMess = json.dumps(firstJsonMess) # 字典转json字符串传递参数,文本参数 #create_connection进行连接 # while True: # time.sleep(2) # try: # ws = create_connection(url) # print(ws) # ws.send(firstMess) # result = ws.recv() #返回json字符串 # #result = json.loads(result) json 字符串转dict字典用来数据处理 # print(result) # ws.close # break # except Exception as e: # print("exception ", format(e)) # continue ws = None try: ws = WebSocketClient(url, protocols=['chat']) ws.connect() # ws.run_forever() ws.send(firstMess) print() except Exception as e: print(e) ws.close()
return code = '' write_emergency(code) #safety log = safe! #wait 5 seconds port = '/dev/ttyAMA0' baud = 115200 serial = serial.Serial(port, baud, timeout=0.6) host = config.get('socket', 'host') port = config.get('socket', 'port') ws = WebSocketClient('ws://' + host + ':' + port + '/', protocols=['http-only', 'chat']) ws.connect() print "Connected to socket" while True: if (GPIO.input(2) == GPIO.LOW): #Pin is set as low, switch to emergency mode! if not emergency: #read status serial.flushInput() serial.write("M730\r\n") #time.sleep(0.5) reply = serial.readline()
conn.commit() conn.close() #myFabototumCom = MyFabtotumCom(gcservice, config, logger) # Start gcode service gcservice = GCodeService(SERIAL_PORT, SERIAL_BAUD, logger=logger, fabid=FABID_ACTIVE) gcservice.start() # Pyro GCodeService wrapper gcserver = GCodeServiceServer(gcservice) ws = WebSocketClient('ws://' + SOCKET_HOST + ':' + SOCKET_PORT + '/') ws.connect() # Notification service ns = NotifyService(ws, NOTIFY_FILE, config) ## Folder temp monitor ftm = FolderTempMonitor(ns, gcservice, logger, TRACE, TASK_MONITOR) ## usb disk monitor um = UsbMonitor(ns, logger, USB_FILE) ## Configuration monitor cm = ConfigMonitor(gcservice, config, logger) ## The Observer ;) observer = Observer() observer.schedule(um, '/dev/', recursive=False)
import cv2, cv import sys, getopt, os from subprocess import call import datetime, time from os import path, access, R_OK import math from ws4py.client.threadedclient import WebSocketClient import ConfigParser import json config = ConfigParser.ConfigParser() config.read('/var/www/fabui/python/config.ini') '''#### WEB SOCKET CLIENT ####''' host = config.get('socket', 'host') port = config.get('socket', 'port') ws = WebSocketClient('ws://' + host + ':' + port + '/') ws.connect() #defaults: scan_dir = '/var/www/camera/scan_temp/' #default dir output_file = scan_dir + "cloud.asc" #default output file slices = 360 #default total slices start = 1 #starting number end = 360 #ending number img_width = 1920 #default scan size img_height = 1080 #default scan size #progress tracking myPID = os.getpid() #get process pid so the GUI can kill it if needed t0 = datetime.datetime.now() #starting time completed = 0 #completed flag
"mid": "6aad0b12-2192-4b90-8f40-08a2bc0b5c2a", "version": "1.0", "request": { "apiVer": "1.0.0", "timestamp": 1234567890, "pki":"fndjsafhop3u8rheowfh" }, "params": { "sn": "0000DB11138104887174101101740000", "category": "0xDB", "model": "123", "id": "23454365465643", "ip": "0.0.0.0", "mac": "88e9fe5d3829", "random": "545623" } } if __name__ == '__main__': try: ws = WebSocketClient('ws://linksit.aimidea.cn:10000/cloud/connect', protocols=['chat']) ws.connect() print(ws.received_message("连接成功")) # # ws.run_forever() print("连接成功") except KeyboardInterrupt: ws.close() print("失败了") ws.send(json.dumps(data)) # print(ws.recv()) time.sleep(10) ws.close()
def feedRobotDataInThread(self): import io from ws4py.client.threadedclient import WebSocketClient import json camClient = WebSocketClient('ws://localhost:9090/camPub') camClient.connect() r3dClient = WebSocketClient('ws://localhost:9090/3dPub') r3dClient.connect() print('Starting data feed') while True: if self._robot is None: print('No robot') time.sleep(0.1) continue # Feed camera image = self._robot.world.latest_image if image is None: print('No image') time.sleep(0.1) continue fobj = io.BytesIO() image.raw_image.save(fobj, format="jpeg") fobj.seek(0) binaryImage = fobj.read() if binaryImage is None: continue camClient.send(binaryImage, binary=True) # Feed robot data def getData(pose): # Don't fail if one of the cubes has flat battery. if not pose: return {'x': 0, 'y': 0, 'z': 0, 'rot': (0, 0, 0, 0)} pos = pose.position rot = pose.rotation return { 'x': pos.x, 'y': pos.y, 'z': pos.z, 'rot': rot.q0_q1_q2_q3 } def getCubeData(num): cube = self._robot.world.light_cubes.get(num) data = getData(cube.pose) data['seen'] = self.getCubeSeen(num) data['visible'] = self.getCubeIsVisible(num) return data data = { 'cozmo': getData(self._robot.pose), 'cubes': [getCubeData(1), getCubeData(2), getCubeData(3)] } r3dClient.send(json.dumps(data)) # Sleep a while time.sleep(0.1)
# Autre TechLab - Core functionality for the Blockly and Ros2 import rclpy from rclpy.node import Node import os import time from ws4py.client.threadedclient import WebSocketClient # blocksClient = WebSocketClient('ws://localhost:8080/blocksPub') blocksClient.connect() def start(port=8080): blocksClient = WebSocketClient('ws://localhost:' + str(port)+ '/blocksPub') blocksClient.connect() def highlight(block, AtlDebugLevel = 0): #defined in ../atlide-blockly/js/code.js and ../nodejs/headless.js try: blocksClient.send(block) except: get_logger("atlide_core.highlight").info("Ups, cannot send message!!") pass from rclpy.node import get_logger get_logger("atlide_core.highlight").info(str(block) + " " + str(AtlDebugLevel)) if AtlDebugLevel == 1: time.sleep(1) if AtlDebugLevel == 2: time.sleep(2) if AtlDebugLevel == 3: time.sleep(5)