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)
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 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 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 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 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 main( videoPath, onboardingMode, imageProcessingEndpoint="", imageProcessingParams="", showVideo=False, verbose=False, loopVideo=True, convertToGray=False, resizeWidth=0, resizeHeight=0, annotate=False, cognitiveServiceKey="", modelId="", max_exceptions=-1, num_exceptions=0 ): ''' Capture a camera feed, send it to processing and forward outputs to EdgeHub :param int videoPath: camera device path such as /dev/video0 or a test video file such as /TestAssets/myvideo.avi. Mandatory. :param bool onboardingMode: is onBoarding mode or live-stream mode :param str imageProcessingEndpoint: service endpoint to send the frames to for processing. Example: "http://face-detect-service:8080". Leave empty when no external processing is needed (Default). Optional. :param str imageProcessingParams: query parameters to send to the processing service. Example: "'returnLabels': 'true'". Empty by default. Optional. :param bool showVideo: show the video in a windows. False by default. Optional. :param bool verbose: show detailed logs and perf timers. False by default. Optional. :param bool loopVideo: when reading from a video file, it will loop this video. True by default. Optional. :param bool convertToGray: convert to gray before sending to external service for processing. False by default. Optional. :param int resizeWidth: resize frame width before sending to external service for processing. Does not resize by default (0). Optional. :param int resizeHeight: resize frame width before sending to external service for processing. Does not resize by default (0). Optional.ion( :param bool annotate: when showing the video in a window, it will annotate the frames with rectangles given by the image processing service. False by default. Optional. Rectangles should be passed in a json blob with a key containing the string rectangle, and a top left corner + bottom right corner or top left corner with width and height. ''' try: print("\nPython %s\n" % sys.version) print("RStream Video Analyzer. Press Ctrl-C to exit.") with CameraCapture(videoPath, onboardingMode, imageProcessingEndpoint, imageProcessingParams, showVideo, verbose, loopVideo, convertToGray, resizeWidth, resizeHeight, annotate, cognitiveServiceKey, modelId) as cameraCapture: cameraCapture.start() except Exception as e: print(e) tb = traceback.format_exc() if isinstance(e,KeyboardInterrupt): print("Camera capture module stopped") sys.exit(0) # TODO: make it more generic - excep VAOCVE error and if so - check e.send_socket elif isinstance(e, OCRSocketVAOCVError) or isinstance(e, SocketInitVAOCVError): exitCode = handleException(e,tb,DEVICE_ID,None) sys.exit(exitCode) else: socketIO = SocketIO(SOCKET_URL, 443, BaseNamespace) ocrSocket = socketIO.define(SocketNamespace, '/ocr') exitCode = handleException(e,tb,DEVICE_ID,ocrSocket) sys.exit(exitCode)
class RetentionDashboardSocket(): def __init__(self, hostname, port): imageio.plugins.freeimage.download() self.hostname = hostname self.port = port self.socket = SocketIO(self.hostname, self.port) self.retention_dashboard_namespace = self.socket.define( RetentionDashboardNamespace, Config.Socket.RETENTION_DASHBOARD_NAMESPACE) def send_result(self, **kwargs): image_id = kwargs.get('image_id') self.retention_dashboard_namespace.emit(Config.Socket.NEW_FACE_EVENT, image_id)
def connect(self): io = SocketIO(self.server, self.port) iron_namespace = io.define(IRONNamespace, '/iron') flash_namespace = io.define(FLASHNamespace, '/flash') mega_namespace = io.define(MEGANamespace, '/mega') io.emit('login', {'app_client_secret_id': os.environ.get('SOCKBOT_APPCLIENT_SECRET'), 'name': 'AUTOBOT'}, callback_login) #login update socketid io.wait_for_callbacks(seconds=1) #io.wait() return dict(io=io,iron_namespace=iron_namespace, flash_namespace=flash_namespace, mega_namespace=mega_namespace)
class SocketMessenger(): def __init__(self, hostname, port): imageio.plugins.freeimage.download() self.hostname = hostname self.port = port self.socket = SocketIO(self.hostname, self.port) self.messenger_namespace = self.socket.define(MessengerNameSpace, Config.Socket.NAMESPACE) def send_alert(self, **kwargs): json_string = json.dumps(kwargs) self.messenger_namespace.emit(Config.Socket.ALERT_EVENT, json_string) def send_statistic(self, **kwargs): json_string = json.dumps(kwargs) print(json_string) self.messenger_namespace.emit(Config.Socket.STATISTIC, json_string)
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)
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
my_device = XBeeDevice(PORT, BAUD_RATE) my_device.open() data_queue = [] ADDRESS1 = "0013A200419B5AD8" data_queue1 = '' ADDRESS2 = "0013A20041554FF4" data_queue2 = '' jt_address = {'JT601': ADDRESS1, 'JT602': ADDRESS2} count = 0 socket = SocketIO('http://711ffdf65ff0.ngrok.io', verify=True) #socket = SocketIO('http://192.168.0.2', 3000, verify=True) #establish socket connection to desired server # while not socket._connected: # socket = SocketIO('https://nicwebpage.herokuapp.com', verify =True) socket_a = socket.define(BaseNamespace, '/JT601') socket_a.emit("joinDrone") socket_b = socket.define(BaseNamespace, '/JT602') socket_b.emit("joinDrone") def socket_function(parsed_data, drone): global count sending_label = 'data' try: if (parsed_data[:3] == '{0:'): sending_label = 'waypoints' ini_string = json.dumps(parsed_data) processed_data = json.loads(ini_string) final_dictionary = eval(processed_data)
import numpy as np import serial import json from socketIO_client_nexus import SocketIO, BaseNamespace ser = serial.Serial('/dev/ttyUSB0') back_matrix = np.zeros((200, 100)) front_matrix = np.zeros((200, 100)) count = 0 socketIO = SocketIO('http://192.168.43.168', 5001) rekathon_namespace = socketIO.define(BaseNamespace, '/rekathon') while True: try: x = str(ser.readline()[:-2]).split(',') angle = int(x[0]) if count % 200 == 0: print np.where(back_matrix > 0) rekathon_namespace.emit( 'backend', json.dumps({ 'matrix': np.hstack( [np.flipud(front_matrix), np.fliplr(back_matrix)]).tolist() })) count = 1 back = int(x[1].split(':')[1]) front = int(x[2].split(':')[1]) angle = int(np.around((angle / 180.0) * 199)) if back > 0:
d = {} r = 0 file = open('pyfile.txt', 'r') for line in file: d[r] = line.split("\n")[0] r = r + 1 return d try: #socket1 = SocketIO('http://192.168.1.81', 3000, verify=True) #establish socket connection to desired server socket1 = SocketIO( 'http://drone.nicnepal.org', verify=True) #establish socket connection to desired server #socket1 = SocketIO('https://nicwebpage.herokuapp.com', verify =True) socket = socket1.define(BaseNamespace, '/JT602') #socket = socket1.define(BaseNamespace,'/pulchowk') #socket.emit("joinPiPulchowk") socket.emit("joinPi") #socket.emit("usernamePassword",read_username_password()) except Exception as e: print('The server is down. Try again later.') def set_mode_LAND(var): fix_type = 0 try: fix_type = vehicle.gps_0.fix_type except Exception as e: pass if fix_type > 1:
def __init__( self, videoPath, onboardingMode, imageProcessingEndpoint = "", imageProcessingParams = "", showVideo = False, verbose = False, loopVideo = False, convertToGray = False, resizeWidth = 0, resizeHeight = 0, annotate = False, cognitiveServiceKey="", modelId="", # TODO: change monitorID: monitorid = "90210"): self.videoPath = videoPath self.onboardingMode = onboardingMode # Avihay's bug fix: # TODO: add argument to choose which kind of processing - file or stream if not self.__IsInt(videoPath): # case of a stream self.isWebcam = True else: # case of a video file self.isWebcam = False # TODO: remove all commands related to imageProcessingEndpoint. It's irelevant self.imageProcessingEndpoint = imageProcessingEndpoint if imageProcessingParams == "": self.imageProcessingParams = "" else: self.imageProcessingParams = json.loads(imageProcessingParams) self.showVideo = showVideo self.verbose = verbose self.loopVideo = loopVideo self.convertToGray = convertToGray self.resizeWidth = resizeWidth self.resizeHeight = resizeHeight self.annotate = (self.imageProcessingEndpoint != "") and self.showVideo & annotate self.nbOfPreprocessingSteps = 0 self.autoRotate = False self.vs = None self.monitor_id = monitorid if not self.onboardingMode: # live-stream mode, will use known boundries self.__get_boundries() # connect to server socketIO = SocketIO('https://rstream-node.azurewebsites.net', 443, BaseNamespace) self.ocrSocket = socketIO.define(SocketNamespace, '/ocr') if self.convertToGray: self.nbOfPreprocessingSteps +=1 if self.resizeWidth != 0 or self.resizeHeight != 0: self.nbOfPreprocessingSteps +=1 self.cognitiveServiceKey = cognitiveServiceKey self.modelId = modelId if self.verbose: print("Initialising the camera capture with the following parameters: ") print(" - Video path: " + self.videoPath) print(" - Image processing endpoint: " + self.imageProcessingEndpoint) print(" - Image processing params: " + json.dumps(self.imageProcessingParams)) print(" - Show video: " + str(self.showVideo)) print(" - Loop video: " + str(self.loopVideo)) print(" - Convert to gray: " + str(self.convertToGray)) print(" - Resize width: " + str(self.resizeWidth)) print(" - Resize height: " + str(self.resizeHeight)) print(" - Annotate: " + str(self.annotate)) print(" - Cognitive Service Key: " + self.cognitiveServiceKey) print(" - Model Id: " + self.modelId) print() self.displayFrame = None # if self.showVideo: # self.imageServer = ImageServer(5012, self) # self.imageServer.start() # # self.imageServer.run() COMPUTER_VISION_ENDPOINT = os.environ["COMPUTER_VISION_ENDPOINT"] COMPUTER_VISION_SUBSCRIPTION_KEY = os.environ["COMPUTER_VISION_SUBSCRIPTION_KEY"] self.computervision_client = ComputerVisionClient(COMPUTER_VISION_ENDPOINT, CognitiveServicesCredentials(COMPUTER_VISION_SUBSCRIPTION_KEY))
# coding: UTF-8 # from socketio_client import SocketIO, BaseNamespace from socketIO_client_nexus import SocketIO, BaseNamespace class LogNamespace(BaseNamespace): def on_aaa_response(self, *args): print('on_aaa_response', args) # io = SocketIO('localhost', 8080) io = SocketIO('10.0.0.3', 8080) namespace = "/base" my_namespace = io.define(LogNamespace, namespace) print("connected") my_namespace.emit('log', {'name': 'cad', 'logs': []}) io.wait(seconds=1) # socketIO.wait(seconds=1)
class WebSocketClient: def __init__(self, symbols: Union[str, Set[str]] = None, channels: Set[Channel] = None, on_message=None, on_connect=None, on_disconnect=None, port=443, url='https://ws-api.iextrading.com'): """ :param symbols: Single symbol, or set of symbols to subscribe to. :param channels: The channels of interest. :param on_message: Callback to be invoked when data is received :param on_connect: Callback to be invoked when the connection is opened :param on_disconnect: Callback to be invoked when the connection is closed :param port: The port to use for the connection :param url: The IEX websocket URL to use """ self.port = port self.url = url symbols = {} if symbols is None else symbols channels = {Channel.ALL} if channels is None else channels self.symbols = {symbols} if isinstance(symbols, str) else set(symbols) self.channels = {channels} if isinstance(channels, Channel) else set(channels) class Namespace(BaseNamespace): count = 0 def on_connect(self, *data): if on_connect is not None: on_connect(*data) self.count = self.count + 1 def on_disconnect(self, *data): if on_disconnect is not None: on_disconnect(*data) self.count = self.count + 1 def on_message(self, data): if on_message is not None: on_message(json.loads(data)) self.count = self.count + 1 self.socket = SocketIO(host=self.url, port=self.port) self.namespace = self.socket.define(Namespace, '/1.0/deep') self.__thread = threading.Thread(target=self.__run) self.__terminate = threading.Event() for symbol in self.symbols: sendinit = { "symbols": [symbol], "channels": [c.value for c in channels] } self.namespace.emit('subscribe', json.dumps(sendinit)) def start(self): self.__thread.start() def __run(self): while not self.__terminate.is_set(): self.socket.wait(seconds=.1) self.namespace.disconnect() def stop(self, join=True, timeout=None): """Disconnect from the server and terminate the handler event loop""" self.__terminate.set() if join: self.__thread.join(timeout=timeout) if self.__thread.is_alive(): raise RuntimeError("Failed to join thread within timeout")
import numpy as np import serial import json from socketIO_client_nexus import SocketIO, BaseNamespace ser = serial.Serial('/dev/ttyUSB0') # replace with correct ip or address and port socketIO = SocketIO('X.X.X.X', 9999) directory_namespace = socketIO.define(BaseNamespace, '/directory') while True: try: data = str(ser.readline()[:-2]).split(',') directory_namespace.emit('backend',json.dumps({'from':'backend', 'data': })) except: pass # dont do sleep in python, do sleep using arduino # because why, python only a transmitter, serial port only listen, cannot send something to our devices
from threading import Thread from socketIO_client_nexus import SocketIO, LoggingNamespace def receive_events_thread(): socketIO.wait() def shit(*args): print args socketIO = SocketIO('http://192.168.43.168', 5001) camera_namespace = socketIO.define(LoggingNamespace, '/rekathon') camera_namespace.on('backend', shit) receive_events_thread = Thread(target=receive_events_thread) receive_events_thread.daemon = True receive_events_thread.start() while True: camera_namespace.emit('backend', 'a')
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]
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)
class Namespace(BaseNamespace): def on_connect(self, *data): print('conneced') def on_disconnect(self, *data): print('disconnected') def on_message(self, data): global i data = tryJSON(data) predicted_price = predict(data) data['nextPredictedPrice'] = predicted_price print(str(data['lastSalePrice']), " ", i) write_to_kafka(data) if data['symbol'] == "AAPL": i += 1 ''' Call all pyspark related functions here!! ''' namespace = socketIO.define(Namespace, '/1.0/tops') #namespace.emit('subscribe', 'AAPL') #loop for testing purpose only! for symbol in SYMBOLS: namespace.emit('subscribe', symbol) print("subscribed to ", symbol) socketIO.wait()
#print("\nConnecting to vehicle on: ,s" , connection_string) #vehicle = connect(connection_string, wait_ready=True)d={} def read_username_password(): d={} r=0 file = open('pyfile.txt', 'r') for line in file: d[r]=line.split("\n")[0] r=r+1 return d try: socket1 = SocketIO('http://192.168.1.119', 3000, wait_for_connection=False)#establish socket connection to desired server socket = socket1.define(BaseNamespace,'/pulchowk') #socket = SocketIO('https://nicwebpage.herokuapp.com', verify =False) socket.emit("joinPiPulchowk") #socket.emit("joinPi") #socket.emit("usernamePassword",read_username_password()) except ConnectionError: print('The server is down. Try again later.') try: vehicle = connect('127.0.0.1:14551', wait_ready=True) except Exception as e: error={'context':'Connection','msg':'Connection problem with pixhawk'} socket.emit("error",error) vehicle.wait_ready('autopilot_version')
def __init__(self, videoPath, onboardingMode, imageProcessingEndpoint="", imageProcessingParams="", showVideo=False, verbose=False, loopVideo=False, convertToGray=False, resizeWidth=0, resizeHeight=0, annotate=False, cognitiveServiceKey="", modelId=""): self.videoPath = videoPath self.onboardingMode = onboardingMode # Avihay's bug fix: # TODO: add argument to choose which kind of processing - file or stream # Explanation: in the original demo, only a number was passed as path, because in RasPi webcam it is the case. # the different is when it's a webcam (True) - we take the latest frame at each point. In case it's a video (False) - we run on ALL frames if not self.__IsInt(videoPath): # case of a stream self.isWebcam = True else: # case of a video file self.isWebcam = False # TODO: remove all commands related to imageProcessingEndpoint. It's irelevant self.imageProcessingEndpoint = imageProcessingEndpoint if imageProcessingParams == "": self.imageProcessingParams = "" else: self.imageProcessingParams = json.loads(imageProcessingParams) self.showVideo = showVideo self.verbose = verbose self.loopVideo = loopVideo self.convertToGray = convertToGray self.resizeWidth = resizeWidth self.resizeHeight = resizeHeight self.annotate = (self.imageProcessingEndpoint != "") and self.showVideo & annotate self.nbOfPreprocessingSteps = 0 self.autoRotate = False self.vs = None # TODO: wrap in try and add default value self.monitor_id = os.getenv("DEVICE_ID") self.results_list = [] if not self.onboardingMode: # live-stream mode, will use known boundries self.__get_boundries() # connect to server SOCKET_URL = os.getenv("SOCKET_URL") try: socketIO = SocketIO(SOCKET_URL, 443, BaseNamespace, False) time.sleep(3) self.ocrSocket = socketIO.define(SocketNamespace, '/ocr') except: print("Failed to open socket!") raise SocketInitVAOCVError( "Can't establish a connection to the socket") else: self.__get_device_type_for_onboarding() if self.convertToGray: self.nbOfPreprocessingSteps += 1 if self.resizeWidth != 0 or self.resizeHeight != 0: self.nbOfPreprocessingSteps += 1 self.cognitiveServiceKey = cognitiveServiceKey self.modelId = modelId if self.verbose: print("Container vesrion: --> v1.3 - Intel OCR TEST") print( "Initialising the camera capture with the following parameters: " ) print(" - Video path: " + str(self.videoPath)) print(" - OnBoarding mode: " + str(self.onboardingMode)) print(" - Device ID: " + str(self.monitor_id)) print(" - Device type: " + str(self.device_type)) print(" - Computer vision model: " + str(os.getenv('CV_MODEL', ""))) # print(" - Image processing endpoint: " + self.imageProcessingEndpoint) # print(" - Image processing params: " + json.dumps(self.imageProcessingParams)) # print(" - Show video: " + str(self.showVideo)) # print(" - Loop video: " + str(self.loopVideo)) # print(" - Convert to gray: " + str(self.convertToGray)) # print(" - Resize width: " + str(self.resizeWidth)) # print(" - Resize height: " + str(self.resizeHeight)) # print(" - Annotate: " + str(self.annotate)) print() self.displayFrame = None # if self.showVideo: # self.imageServer = ImageServer(5012, self) # self.imageServer.start() # # self.imageServer.run() COMPUTER_VISION_ENDPOINT = os.environ["COMPUTER_VISION_ENDPOINT"] COMPUTER_VISION_SUBSCRIPTION_KEY = os.environ[ "COMPUTER_VISION_SUBSCRIPTION_KEY"] self.computervision_client = ComputerVisionClient( COMPUTER_VISION_ENDPOINT, CognitiveServicesCredentials(COMPUTER_VISION_SUBSCRIPTION_KEY))
vera_mongo_db.geturl()).VERAPreProcessor.features except: print("WARNING: Mongo DB not set up") pass if (not mongo_features_collection is None): try: data['createdAt'] = datetime.datetime.now() data['calldatetime'] = datetime.datetime.now() mongo_features_collection.insert(data, w=0) except: print("NOT SAVED, EXCEPTION DURING SAVING in MONGODB") pass """ Setup Socket.io client and start listening for events """ try: socketIO = SocketIO(host=vera_hub_address.hostname, port=vera_hub_address.port, Namespace=Namespace, wait_for_connection=True) vera_namespace = socketIO.define(Namespace, '/VERA') vera_namespace.on('vera-start', on_vera_start) vera_namespace.on('vera-stop', on_vera_stop) print('Connected to VERA Hub ' + vera_hub_address.geturl()) print('using analyzer on address ' + vera_emotion_processor_address.geturl()) socketIO.wait() except ConnectionError: print('The server is down. Try again later.')
def _socket(self): socket = SocketIO('https://ws-api.iextrading.com', 443) namespace = socket.define(feed_handler, "/1.0/tops") symbols = "snap" namespace.emit('subscribe', 'firehose') socket.wait()
class CocoBuyinWorker: buyinCallback = None url = None socketIO = None provider = None buyinNamespace = None thread = None working = False clientTag = '' def __init__(self, url, provider): self.url = url self.provider = provider self.thread = threading.Thread(target=self.__wait__) self.thread.start() def setBuyinCallback(self, buyinCallback): self.buyinCallback = buyinCallback self.__regCallback__() def __wait__(self): print('coco:buyinworker:will wait') while True: if not self.working or not self.socketIO: time.sleep(5) else: try: self.socketIO.wait(5) except Exception as e: print('coco:buyinworker:waiting error:', e) traceback.print_exc() def __regCallback__(self): if self.buyinNamespace and self.buyinCallback: self.buyinNamespace.on(self.clientTag, self.buyinCallback) def __success__(self, clientId): print('coco:buyinworker:success:client id:', clientId) self.clientTag = 'client:%s' % clientId self.__regCallback__() def __onConnect__(self): print('coco:buyinworker:connected') def __onDisconnect__(self): print('coco:buyinworker:disconnected') def __onReconnect__(self): print('coco:buyinworker:reconnected') def start(self, cookie): if self.working: return print('coco:buyinworker:will start:', cookie) try: self.socketIO = SocketIO( self.url, cookies=cookie, ) self.socketIO.on('connect', self.__onConnect__) self.socketIO.on('disconnect', self.__onDisconnect__) self.socketIO.on('reconnect', self.__onReconnect__) self.buyinNamespace = self.socketIO.define(CocoBuyinNamespace, '/cms') self.buyinNamespace.on('success', self.__success__) self.buyinNamespace.emit('authentication') self.working = True except Exception as e: print('coco:buyinworker:connetion error:', e) traceback.print_exc() self.working = False self.buyinNamespace = None self.socketIO = None self.start(self.provider.getCookie()) def stop(self): if not self.working: return if self.buyinNamespace: self.buyinNamespace.off(self.clientTag) if self.socketIO: self.socketIO.disconnect() self.working = False self.buyinNamespace = None self.socketIO = None self.clientTag = None print('coco:buyinworker:stoped')