Exemple #1
0
def connect_socket(argument):
    so = SocketServer(argument["ip"], argument["port"])
    if so.connect_server() == False:
        print("Error connexion to server ip:[{0}] port:[{1}]".format(
            argument["ip"], argument["port"]))
        exit(1)
    return so
Exemple #2
0
 def __init__(self, gateway_ip):
     self.Flaged_ip=dict()
     self.CONFIG = self.get_config()
     self.REPLICATION_COUNT = self.CONFIG["REPLICATION_COUNT"]
     self.GATEWAY_IP = gateway_ip
     self.mnode = SocketServer(gateway_ip)
     t = threading.Thread(target = self.run_mmnode_thread)
     t.start()
Exemple #3
0
 def __init__(self):
     self.CONFIG = self.get_config()
     self.GATEWAY_IPS = self.CONFIG["gateway_ips"]
     self.GATEWAY_SOCKS = []
     self.CONTAINER_IP = self.CONFIG["api_server"]
     self.APISOCK = SocketServer(self.CONTAINER_IP, 44123)
     t = threading.Thread(target=self.run_APISOCK_thread)
     t.start()
    def start(self):
        server = SocketServer()
        thread = Thread(target=server.run, args=[self.sf2, True])
        thread.start()

        while self.sf0.notComplete() and self.sf1.notComplete():
            # camera looking at reflective tape
            self.sf2.setFrame(
                viewReflTape(self.sf0.getFrame(), self.sf1.getFrame()))
Exemple #5
0
def main():
    if os.path.exists("config.json"):
        with open("config.json", 'r') as file:
            configuration = json.load(file)

        ip = configuration["ip"]
        port = configuration["port"]
        motd = configuration["motd"]["1"] + "\n" + configuration["motd"]["2"]
        version_text = configuration["version_text"]
        kick_message = ""
        server_icon = None

        for message in configuration["kick_message"]:
            kick_message += message + "\n"
        kick_message = kick_message[:-2]

        if not os.path.exists(configuration["server_icon"]):
            print("Server icon doesn't exists - submitting none...")
        else:
            with open(configuration["server_icon"], 'rb') as image:
                server_icon = "data:image/png;base64," + base64.b64encode(
                    image.read()).decode()
        try:
            global server
            server = SocketServer(ip, port, motd, version_text, kick_message,
                                  server_icon)
            server.start()
        except KeyboardInterrupt:
            server.close()
            exit(1)
        except Exception as e:
            print(e)
    else:
        configuration = {}
        configuration["ip"] = "0.0.0.0"
        configuration["port"] = 25565
        configuration["motd"] = {}
        configuration["motd"]["1"] = "§4Maintenance!"
        configuration["motd"][
            "2"] = "§aCheck example.com for more information!"
        configuration["version_text"] = "§4Maintenance"
        configuration["kick_message"] = [
            "§bSorry", "", "§aThis server is offline!"
        ]
        configuration["server_icon"] = "server_icon.png"
        configuration["samples"] = ["§bexample.com", "", "§4Maintenance"]

        with open("config.json", 'w') as file:
            json.dump(configuration,
                      file,
                      sort_keys=True,
                      indent=4,
                      ensure_ascii=False)

        print("[!] A new configuration was created!")
        print("Please check the settings in the config.json!")
        exit(1)
def scheduler():
    """
    Start all streams
    """
    print("Flask up and running, now starting data streams...")

    # Start TCP socket Server
    SocketServer().start()
    print("SocketServer Started")
    ImageServer().start()
    print("ImageServer Started")
    # Start HTTP server
    HTTPserver().start()
    print("HTTPServer Started")
Exemple #7
0
def init_socket():
    # Socket process
    parent_pipe, child_pipe = Pipe()

    # Starts the process
    proc = SocketServer(port, child_pipe)
    proc.start()

    queue = Queue()

    # Creates a new thread that will be listening the pipe
    nbpl = NBPL(parent_pipe, queue)
    nbpl.setDaemon(True)
    nbpl.start()
    return parent_pipe, queue
Exemple #8
0
    def run(self):
        # Get event loop
        # --------------------
        # Get the current event loop. If there is no current event loop set in 
        # the current OS thread and set_event_loop() has not yet been called, 
        # asyncio will create a new event loop and set it as the current one.
        self.loop = asyncio.get_event_loop()
        self.context.loop = self.loop
        self.futures = []

        # Register actor instances
        logger.info('Registering {0} actor instances'.format(
            len(self.context.config['actors'])
        ))
        
        self.context.actors = list(map(
            lambda a: a['class'](a, self.context), self.context.config['actors']
        ))

        # Message processor
        self.futures.append(asyncio.ensure_future(self.events_processor()))

        try:
            # Servers
            self.context.http_server = HttpServer()
            self.context.socket_server = SocketServer(async_mode='aiohttp')
            self.context.socket_server.configure(self.context)
            
            asyncio.ensure_future(
                self.context.http_server.configure(self.context), 
                loop=self.loop)

            # Startup event
            self.context.queue_event('homeghost', 'startup', payload={})

            # Run the event loop
            logger.info('Running core event loop')
            self.context.running = True
            self.loop.run_forever()


        finally:
            # Stop event loop
            self.context.running = False

            asyncio.wait(self.futures, loop=self.loop)

            self.loop.close()
Exemple #9
0
def scheduler():
    """
    Start all streams
    """
    print("Flask up and running, now starting data streams...")

    # Start TCP socket Server
    SocketServer().start()
    ImageServer().start()

    # Start HTTP server
    HTTPserver().start()

    # Can be a smart idea to start streams here!
    # Start some demo flows
    demo()
Exemple #10
0
from myutils import *
from machine import reset
from socket_server import SocketServer
from ubinascii import a2b_base64

l = Logger()
l.info('Started main.py')
wifi_connect()
wifi = network.WLAN(network.STA_IF)
ap = network.WLAN(network.AP_IF)
ss = SocketServer('10.0.0.32', 8888)



Exemple #11
0
    isServer.width = 50
    isServer.height = 30
    isServer.x = 30
    isServer.y = 650
    isServer.bind(active=on_server_active)
    layout.add_widget(isServer)
    global ed
    ed = TextInput(hint_text='digite a mensagem a ser enviada')
    ed.size_hint = None, None
    ed.height = 500
    ed.width = 400
    ed.y = 100
    layout.add_widget(ed)
    global bt
    bt = Button(text='send')
    bt.size_hint = None, None
    bt.width = 400
    bt.height = 60
    bt.y = 20
    bt.on_press = handleClick
    layout.add_widget(bt)
    return layout


global socket
socket = SocketServer()
janela = App()
Window.size = 400, 700
janela.build = build
janela.run()
Exemple #12
0
        None

    Returns: 
        None
    """
    from urllib.request import urlopen
    import json
    byte_str = urlopen('https://www.howsmyssl.com/a/check').read()
    data = json.loads(byte_str.decode('utf-8'))
    tls_version = data['tls_version']
    print('>>>Support TSL version {}'.format(tls_version))
    print('>>>SSL library version {}'.format(ssl.OPENSSL_VERSION))
    print('>>>SSL API version {}'.format(ssl._OPENSSL_API_VERSION))


if __name__ == "__main__":
    try:
        check_ssl()
    except Exception as ex:
        print(ex)

    server = SocketServer(is_debug=True, is_flushing=True)
    while True:
        if len(server.queuing_clients) > 0:
            print("Start recording ...")
            server.record()
            break
    # # server.start()
    # time.sleep(5.0)
    # server.record()
Exemple #13
0
from oled_print import OLEDPrint
from wifi import Wifi
from socket_server import SocketServer
from motor_control import MotorControl
from wheel_encoder import WheelEncoder
import global_params

if __name__ == '__main__':
    global_params.init()
    global_params.set_value("motor_control", MotorControl())
    global_params.set_value("wheel_encoder", WheelEncoder())

    oled = OLEDPrint()
    wifi = Wifi(output_fun=oled)
    flag = wifi.do_connect()
    if flag is False:
        oled.output("Wifi Error")
        exit(0)
    ip = wifi.get_ip()

    socket_server = SocketServer(ip, output_fun=oled)
    socket_server.run()
Exemple #14
0
from socket_server import SocketServer

s = SocketServer('', 7000)
s.start()
Exemple #15
0
 def __init__(self):
     self.socket_server = SocketServer()
     self.threads = []
     self.socket_ip = self.socket_server.get_ip()
Exemple #16
0
                 for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
                 ][0][1]]) if l
    ][0][0]


#---------------------------------------------------------------------------
###################################### MAIN ###########################################

if __name__ == "__main__":

    # Thread for socket server
    socket_host = getIpAddress()
    socket_port = "8889"
    print "Start MAIN - host: ", socket_host, ", port: ", socket_port

    socketServer = SocketServer(socket_host, socket_port)
    socketThread = threading.Thread(target=socketServer.communicate)
    socketThread.setDaemon(True)
    socketThread.start()
    print "SocketServer is running"

    # Streaming thread
    GObject.threads_init()
    Gst.init(None)

    server = GstServer()

    loop = GObject.MainLoop()
    loop.run()

    # End
Exemple #17
0
def run_websocket_svr():
    socket_svr = SocketServer()
    socket_svr.start()
Exemple #18
0
async def init_server():
    server = SocketServer(int(os.getenv("TELEGRAM_PORT")), on_response_message)
    await server.create()
Exemple #19
0
def run_inference(args):
    from modules.inference_engine_pytorch import InferenceEnginePyTorch

    socket_server = SocketServer(args.port)
    joint_angle_calculator = JointAngleCalculator()

    stride = 8

    model_path = os.path.join('models', 'human-pose-estimation-3d.pth')
    net = InferenceEnginePyTorch(model_path, "GPU")

    canvas_3d = np.zeros((720, 1280, 3), dtype=np.uint8)
    plotter = Plotter3d(canvas_3d.shape[:2])
    canvas_3d_window_name = 'Canvas 3D'
    cv2.namedWindow(canvas_3d_window_name)
    cv2.setMouseCallback(canvas_3d_window_name, Plotter3d.mouse_callback)

    file_path = None
    if file_path is None:
        file_path = os.path.join('data', 'extrinsics.json')
    with open(file_path, 'r') as f:
        extrinsics = json.load(f)
    R = np.array(extrinsics['R'], dtype=np.float32)
    t = np.array(extrinsics['t'], dtype=np.float32)

    frame_provider = ImageReader(args.images)
    is_video = False
    if args.video != '':
        frame_provider = VideoReader(args.video)
        is_video = True
    base_height = args.height_size
    fx = 1 # focal length

    delay = 1
    esc_code = 27
    p_code = 112
    space_code = 32
    mean_time = 0

    for frame in frame_provider:
        current_time = cv2.getTickCount()
        if frame is None:
            break
        input_scale = base_height / frame.shape[0]
        scaled_img = cv2.resize(frame, dsize=None, fx=input_scale, fy=input_scale)
        scaled_img = scaled_img[:, 0:scaled_img.shape[1] - (scaled_img.shape[1] % stride)]  # better to pad, but cut out for demo
        if fx < 0:  # Focal length is unknown
            fx = np.float32(0.8 * frame.shape[1])

        inference_result = net.infer(scaled_img)
        poses_3d, poses_2d = parse_poses(inference_result, input_scale, stride, fx, is_video)
        edges = []

        if len(poses_3d):
            poses_3d = rotate_poses(poses_3d, R, t)
            poses_3d_copy = poses_3d.copy()
            x = poses_3d_copy[:, 0::4]
            y = poses_3d_copy[:, 1::4]
            z = poses_3d_copy[:, 2::4]
            poses_3d[:, 0::4], poses_3d[:, 1::4], poses_3d[:, 2::4] = -z, x, -y

            poses_3d = poses_3d.reshape(poses_3d.shape[0], 19, -1)[:, :, 0:3]
            edges = (Plotter3d.SKELETON_EDGES + 19 * np.arange(poses_3d.shape[0]).reshape((-1, 1, 1))).reshape((-1, 2))

        plotter.plot(canvas_3d, poses_3d, edges)
        cv2.imshow(canvas_3d_window_name, canvas_3d)

        draw_poses(frame, poses_2d)
        current_time = (cv2.getTickCount() - current_time) / cv2.getTickFrequency()
        if mean_time == 0:
            mean_time = current_time
        else:
            mean_time = mean_time * 0.95 + current_time * 0.05
        cv2.putText(frame, 'FPS: {}'.format(int(1 / mean_time * 10) / 10),
                    (40, 80), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255))
        cv2.imshow('ICV 3D Human Pose Estimation', frame)

        key = cv2.waitKey(delay)
        if key == esc_code:
            break
        if key == p_code:
            if delay == 1:
                delay = 0
            else:
                delay = 1
        if delay == 0 or not is_video:  # allow to rotate 3D canvas while on pause
            key = 0
            while (key != p_code
                   and key != esc_code
                   and key != space_code):
                plotter.plot(canvas_3d, poses_3d, edges)
                cv2.imshow(canvas_3d_window_name, canvas_3d)
                key = cv2.waitKey(33)
            if key == esc_code:
                break
            else:
                delay = 1
        
        joint_angles = joint_angle_calculator.calculate_angles(poses_3d)
        if joint_angles:
            socket_server.send_data(joint_angles)
Exemple #20
0
 def create_router_instance(self):
     SocketClient().create_socket_client_instance(self.interfaces)
     SocketServer().create_socket_server_instance(self.router_name)
Exemple #21
0
def main():
    logger = logging.getLogger("FakeMCServer")
    if not os.path.exists("logs"):
        os.makedirs("logs")
    logger.setLevel(logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    file_handler = logging.FileHandler("logs/access.log")
    file_handler.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    if os.path.exists("config.json"):
        logger.info("Loading configuration...")
        with open("config.json", 'r') as file:
            configuration = json.load(file)

        ip = configuration["ip"]
        port = configuration["port"]
        motd = configuration["motd"]["1"] + "\n" + configuration["motd"]["2"]
        version_text = configuration["version_text"]
        kick_message = ""
        samples = configuration["samples"]
        try:
            show_hostname = configuration["show_hostname_if_available"]
        except KeyError:
            configuration["show_hostname_if_available"] = True
            show_hostname = True
            with open("config.json", 'w') as file:
                json.dump(configuration,
                          file,
                          sort_keys=True,
                          indent=4,
                          ensure_ascii=False)

        player_max = configuration.get("player_max", 0)
        player_online = configuration.get("player_online", 0)
        protocol = configuration.get("protocol", 2)
        server_icon = None

        for message in configuration["kick_message"]:
            kick_message += message + "\n"

        if not os.path.exists(configuration["server_icon"]):
            logger.warning("Server icon doesn't exists - submitting none...")
        else:
            with open(configuration["server_icon"], 'rb') as image:
                server_icon = "data:image/png;base64," + base64.b64encode(
                    image.read()).decode()
        try:
            global server
            logger.info("Setting up server...")
            server = SocketServer(ip, port, motd, version_text, kick_message,
                                  samples, server_icon, logger, show_hostname,
                                  player_max, player_online, protocol)
            server.start()
        except KeyboardInterrupt:
            logger.info("Shutting down server...")
            server.close()
            logger.info("Done. Thanks for using FakeMCServer!")
            exit(0)
        except Exception as e:
            logger.exception(e)
    else:
        logger.warning("No configuration file found. Creating config.json...")
        configuration = {}
        configuration["ip"] = "0.0.0.0"
        configuration["port"] = 25565
        configuration["protocol"] = 2
        configuration["motd"] = {}
        configuration["motd"]["1"] = "§4Maintenance!"
        configuration["motd"][
            "2"] = "§aCheck example.com for more information!"
        configuration["version_text"] = "§4Maintenance"
        configuration["kick_message"] = [
            "§bSorry", "", "§aThis server is offline!"
        ]
        configuration["server_icon"] = "server_icon.png"
        configuration["samples"] = ["§bexample.com", "", "§4Maintenance"]
        configuration["show_ip_if_hostname_available"] = True
        configuration["player_max"] = 0
        configuration["player_online"] = 0

        with open("config.json", 'w') as file:
            json.dump(configuration,
                      file,
                      sort_keys=True,
                      indent=4,
                      ensure_ascii=False)
        logger.info("Please adjust the settings in the config.json!")
        exit(1)

def thd_worker(inst, idx, conn, addr):
    print(f"got {idx} {addr}")

    conn.settimeout(3)
    buff = ""
    try:
        while (_ := conn.recv(512).decode()):
            if not _:
                break
            buff += _
    except socket.timeout:
        pass
    conn.settimeout(None)
    conn.send(b"ok\n")
    inst.halted = buff.strip() == "halt"
    print(inst.halted, buff.strip().encode())
    conn.close()


if __name__ != "__main__":
    raise SystemExit

server = SocketServer(port=randint(49152, 65535), logger_file=sys.stdout)
print(f"started server on address {server.host}:{server.port}")
server.handle_connections(
    thd_worker,
    proxy_worker_thd=lambda fn, *args, **kwargs: threading.Thread(
        target=fn, args=args, kwargs=kwargs).start())