예제 #1
0
def micrOS():
    profiling_info(label='[1] MAIN BASELOAD')

    # BOOT HOOKs execution
    safe_boot_hook()
    profiling_info(label='[2] AFTER SAFE BOOT HOOK')

    # NETWORK setup
    auto_network_configuration()
    profiling_info(label='[3] AFTER NETWORK CONFIGURATION')

    # LOAD Singleton SocketServer [1]
    SocketServer()
    profiling_info(label='[4] AFTER SOCKET SERVER CREATION')

    # SET interrupt with timirqcbf from nodeconfig
    interrupt_handler()
    profiling_info(label='[5] AFTER TIMER INTERRUPT SETUP')

    # SET external interrupt with extirqcbf from nodeconfig
    external_interrupt_handler()
    profiling_info(label='[6] AFTER EXTERNAL INTERRUPT SETUP')

    # RUN Singleton SocketServer - main loop [2]
    SocketServer().run()
예제 #2
0
    def test_check_for_msg_no_clients(self):
        with patch('socket.socket') as socket_socket_mock:
            with patch('select.select') as select_select_mock:
                serverSocketMock = Mock()
                socket_socket_mock.return_value = serverSocketMock

                sS = SocketServer("1.2.3.4", 1234)
                assert sS.clientSocketList == []
                assert [] == sS.CheckForMsg(1.5)
                assert sS.clientSocketList == []
                del sS

                assert not select_select_mock.called
예제 #3
0
    def test_send_to(self):
        with patch('socket.socket') as socket_mock:
            mock = Mock()
            socket_mock.return_value = mock
            clientMock = Mock()

            sS = SocketServer("1.2.3.4", 1234)
            sS.SendTo(clientMock, "DATA")
            del sS

            socket_mock.assert_called_with(socket.AF_INET, socket.SOCK_STREAM,
                                           socket.getprotobyname('TCP'))
            mock.bind.assert_called_with(("1.2.3.4", 1234))
            clientMock.send.assert_called_with(b"DATA")
예제 #4
0
    def test_check_for_new_clients_no_clients(self):
        with patch('socket.socket') as socket_socket_mock:
            with patch('select.select') as select_select_mock:

                serverSocketMock = Mock()
                socket_socket_mock.return_value = serverSocketMock
                select_select_mock.return_value = ([], [], [])

                sS = SocketServer("1.2.3.4", 1234)
                sS.CheckForNewClient(1.5)
                assert sS.clientSocketList == []
                del sS

                select_select_mock.assert_called_with([serverSocketMock], [],
                                                      [], 1.5)
                assert not serverSocketMock.accept.called
예제 #5
0
    def test_check_for_msg_client_with_error(self):
        with patch('socket.socket') as socket_socket_mock:
            with patch('select.select') as select_select_mock:
                serverSocketMock = Mock()
                socket_socket_mock.return_value = serverSocketMock
                socketClientMock = Mock()
                socketClientMock.recv.return_value = b"ABCD"
                socketClientMock.recv.side_effect = socket.error
                select_select_mock.return_value = ([socketClientMock], [], [])

                sS = SocketServer("1.2.3.4", 1234)
                sS.clientSocketList = [socketClientMock]
                assert [(socketClientMock, "ERROR")] == sS.CheckForMsg()
                socketClientMock.recv.assert_called_with(1024)
                assert socketClientMock.close.called
                assert sS.clientSocketList == []
                del sS
예제 #6
0
    def test_check_for_msg_single_client(self):
        with patch('socket.socket') as socket_socket_mock:
            with patch('select.select') as select_select_mock:
                serverSocketMock = Mock()
                socket_socket_mock.return_value = serverSocketMock
                socketClientMock = Mock()
                socketClientMock.recv.return_value = b"ABCD"
                select_select_mock.return_value = ([socketClientMock], [], [])

                sS = SocketServer("1.2.3.4", 1234)
                sS.clientSocketList = [socketClientMock]
                assert [(socketClientMock, "ABCD")] == sS.CheckForMsg()
                del sS

                select_select_mock.assert_called_with([socketClientMock], [],
                                                      [], 0.2)
                socketClientMock.recv.assert_called_with(1024)
예제 #7
0
    def test_server_params(self):
        with patch('socket.socket') as socket_mock:
            mock = Mock()
            socket_mock.return_value = mock

            sS = SocketServer("1.2.3.4", 1234)
            del sS

            socket_mock.assert_called_with(socket.AF_INET, socket.SOCK_STREAM,
                                           socket.getprotobyname('TCP'))
            mock.bind.assert_called_with(("1.2.3.4", 1234))
예제 #8
0
    def test_create_listen_destroy(self):
        with patch('socket.socket') as socket_mock:
            mock = Mock()
            socket_mock.return_value = mock

            sS = SocketServer()
            del sS

            socket_mock.assert_called_with(socket.AF_INET, socket.SOCK_STREAM,
                                           socket.getprotobyname('TCP'))
            mock.bind.assert_called_with(("0.0.0.0", 5001))
            mock.listen.assert_called()
            mock.close.assert_called()
예제 #9
0
def micrOS():
    profiling_info(label='[memUsage] MAIN LOAD')

    # BOOT HOOKs execution
    safe_boot_hook()

    # SET external interrupt with extirqcbf from nodeconfig
    external_interrupt_handler()

    # NETWORK setup
    auto_network_configuration()

    # LOAD Singleton SocketServer [1]
    SocketServer()

    # SET interrupt with timirqcbf from nodeconfig
    interrupt_handler()
    profiling_info(label='[memUsage] SYSTEM IS UP')

    # RUN Singleton SocketServer - main loop [2]
    SocketServer().run()

    # UNEXPECTED RESTART ???
    errlog_add("Unexpected micrOS restart")
예제 #10
0
def send_cmd(host, cmd):
    port = cfgget('socport')
    hostname = None
    if not validate_ipv4(host):
        hostname = host
        host = socket.getaddrinfo(host, port)[-1][4][0]
    if validate_ipv4(host):
        # Socket reply msg
        SocketServer().reply_message("[intercon] {} -> {}:{}:{}".format(cmd, hostname, host, port))
        # Send CMD
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.settimeout(5)
        conn.connect((host, port))
        output = __run_command(conn, cmd)
        __close_connection(conn)
        return output
    else:
        errlog_add("[INTERCON] Invalid host: {}".format(host))
        return None
예제 #11
0
def main():
    job_dispatcher = JobDispatcher()
    server = SocketServer(job_dispatcher)  #用變數去接收class,是一個object
    server.setDaemon(True)
    server.serve()

    # because we set daemon is true, so the main thread has to keep alive
    while True:
        command = input()
        if command == "finish":
            break
    
    server.server_socket.close()
    print("leaving ....... ")
예제 #12
0
def main():

    # Init socket comm
    socketServer = SocketServer()
    socketClient = SocketClient()


    # Start threads
    socketServer.start() # Always start the server before the client
    socketClient.start()
    

    time.sleep(1) # Allow the sockets to be setup before using them

    try:    
        receivedMessages = Queue.Queue() # Init a queue to store received messages in

        # Send/Recv example
        while(True):
            socketClient.send("Hasse gillar kaffe \n") # VERY IMPORTANT!!!! ALWAYS PROVIDE A NEWLINE AT THE END OF THE MESSAGE OR THE RECV FUNCTION WILL NEVER STOP!
            time.sleep(1) # Make sure that our message has been received (Remove in real code)
            receivedMessages = socketServer.getMessages()

            handleMessages(receivedMessages)

    except (KeyboardInterrupt, SystemExit):
        raise

    finally:

        # Let threads die gracefully
        socketClient.kill()
        socketServer.kill()

        # Wait until threads die
        socketClient.join()
        socketServer.join()
예제 #13
0
파일: Plot.py 프로젝트: alec-gurman/SlamBot
import math
import matplotlib.pyplot as plt
import time
import sys
from Draw import Draw
from SocketServer import SocketServer
from filterpy.stats import plot_covariance_ellipse

if __name__ == '__main__':

    print('[SLAMBOT] Connected! Waiting for some points...')

    plt.figure()
    Draw = Draw()
    Draw.draw_base_map()
    server = SocketServer()
    server.connect()

    while True:
        data = server.recieve(4096)
        if data is not None:
            if len(data) > 0:
                u = data[0]
                sigma = data[1]
                #if(len(data) == 13):
                #Recived our state vector, Plot
                axis_marker = Draw.draw_axis_marker(math.degrees(float(u[2])))
                plt.scatter(float(u[0]),
                            float(u[1]),
                            marker=(3, 0, math.degrees(float(u[2])) + 26),
                            color='b',
예제 #14
0
        event.device.stream_emg(True)
        
    def get_emg_data(self):
        with self.lock:
            print("H")

    def on_emg(self, event):
        with self.lock:
            self.emg_data_queue.append((event.emg))
            
            if len(list(self.emg_data_queue))>=number_of_samples:
                data_array.append(list(self.emg_data_queue))
                self.emg_data_queue.clear()
                return False

sock = SocketServer(HOST_PORT)

# This method is responsible for training EMG data
def Test():
    global verification_set
    global number_of_samples

    number_of_samples=1000 
    verification_set = np.zeros((8, number_of_samples))

    while(restart_process() != True):
        pass
    # Wait for 3 seconds until Myo Connect.exe starts
    time.sleep(3)
    
    # Initialize the SDK of Myo Armband
예제 #15
0
from flask import Flask, request
from SocketServer import SocketServer
from Authentication import Authentication
from Response import Response
from ResponseType import ResponseType
from typing import Callable

app = Flask('GatesAPI')

socket_server = SocketServer()

def auth(callback: Callable, request: request, admin: bool = True, id_user: bool = False) -> tuple:
	authentication = Authentication(admin)
	if (authentication.is_authenticated(request)):
		return callback(authentication.get_id_user()) if id_user else callback()
	else:
		return Response(ResponseType.INVALID_CREDENTIALS).message()

@app.route('/start', methods=['POST'])
def start() -> tuple:
	return auth(lambda: socket_server.init('', SocketServer.SOCKET_PORT), request)

@app.route('/stop', methods=['POST'])
def stop() -> tuple:
	return auth(lambda: socket_server.stop(), request)

@app.route('/connect', methods=['POST'])
def connect() -> tuple:
	return auth(lambda: socket_server.accept_connection(), request)

@app.route('/gates', methods=['POST'])
예제 #16
0
 def wrapper(*args, **kwargs):
     return func(*args, **kwargs, msgobj=SocketServer().reply_message)
예제 #17
0
from SocketServer import SocketServer
from CheckInput import CheckInput
from GaduGaduServer import GaduGaduServer
server = SocketServer()
ggServer = GaduGaduServer(server)
print("Enter exit to close server!")
while True:
    server.CheckForNewClient()
    ggServer.Process()
    MESSAGE = CheckInput()
    if MESSAGE == 'exit':
        break
예제 #18
0

#################################################################
#                      MAIN FUNCTION CALLS                      #
#################################################################

profiling_info(label='[1] MAIN BASELOAD')

# BOOT HOOKs execution
safe_boot_hook()
profiling_info(label='[2] AFTER SAFE BOOT HOOK')

# NETWORK setup
if auto_network_configuration is not None: auto_network_configuration()
profiling_info(label='[3] AFTER NETWORK CONFIGURATION')

# LOAD Singleton SocketServer [1]
SocketServer()
profiling_info(label='[4] AFTER SOCKET SERVER CREATION')

# SET interrupt with timirqcbf from nodeconfig
interrupt_handler()
profiling_info(label='[5] AFTER TIMER INTERRUPT SETUP')

# SET external interrupt with extirqcbf from nodeconfig
external_interrupt_handler()
profiling_info(label='[6] AFTER EXTERNAL INTERRUPT SETUP')

# RUN Singleton SocketServer - main loop [2]
SocketServer().run()