Example #1
0
def main():
    # Setup logging
    logger = logging.getLogger('control')
    logger.setLevel(logging.DEBUG)
    filehandler = logging.FileHandler('main.log')
    filehandler.setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    filehandler.setFormatter(formatter)
    console.setFormatter(formatter)
    logger.addHandler(filehandler)
    logger.addHandler(console)

    # Connect to xBee
    com = Communication(COM_CONNECTION_STRING, 0.1)
    logger.debug("Connected to wireless communication tansceiver")

    #Send file
    logger.debug("Sending test file")
    f = open("testFile.txt", "r")
    f1 = f.readlines()
    for x in f1:
        logger.debug(x)
        com.send(x)
    f.close()
    #file sent, inform the receiver
    logger.debug("File sent")
    com.send("EndOfFile")

    # Program end
    logger.debug("Finished program.")
    sys.exit(0)
Example #2
0
    def __init__(self,
                 lancer_exp=True,
                 MatCode=False,
                 db="Points",
                 defaultPoint="Point0",
                 setTimer=True):
        # Initialisation variables
        self.db = filedb.fileDB(db=db)
        self.__lastpoint = Point.get_db_point(defaultPoint, self.db)
        self.__com = Communication('/dev/ttyACM0')
        self.__Oparam = Param()
        self.__Oparam.config()
        self.__Oparam.calib()
        self.__side = Switch.cote()
        if not self.__side:
            self.__lastpoint.mirror()
        self.__move = Move(self.__Oparam.odrv0)
        self.__MatCode = MatCode
        self.__traj = Trajectoire(param=self.__Oparam,
                                  move=self.__move,
                                  initial_point=self.__lastpoint,
                                  Solo=self.__MatCode)
        self.__com.waitEndMove(Communication.MSG["Initialisation"])

        if setTimer:
            self.__lidar = RPLidar(
                '/dev/ttyUSB0')  #self.__lidar = Lidar('/dev/ttyUSB0')
            self.__timer = RIR_timer(
                self.__com, (self.__Oparam, self.__move), self.__lidar,
                lancer_exp)  # Test: placé avant __init_physical
            self.__lidar.start_motor()
            self.set_ready()
    def __init__(self, parent, port, final=False):
        super().__init__(parent)
        self.parent_widget = parent
        self.communication = Communication(GameMode.MULTIPLAYER_ONLINE_HOST,
                                           port)
        self.final = final
        self.board = []

        self.initGameBoard()
        self.move_enemy_thread_mp = MoveEnemyThreadMP(self)
        self.move_enemy_thread_mp.start()
        self.move_bullets_thread_mp = MoveBulletsThreadMP(self)
        self.move_bullets_thread_mp.start()
        self.move_player_thread_mp1 = MovePlayerThreadMP(1, self)
        self.move_player_thread_mp1.start()
        self.move_player_thread_mp2 = MovePlayerThreadMP(2, self)
        self.move_player_thread_mp2.start()
        self.ex_pipe, self.in_pipe = Pipe()

        self.deux_ex_machina_process = DeuxExMachina(
            pipe=self.ex_pipe,
            boardWidth=GameServerFrame.BoardWidth,
            boardHeight=GameServerFrame.BoardHeight)
        self.deux_ex_machina_process.start()

        self.deux_ex_machina_thread = DeuxExMachinaThread(self, True)
        self.deux_ex_machina_thread.start()
Example #4
0
def course_polling(course_title, sched):
    comm = Communication()

    searchable = course_title.split(') ')

    theCourse = courses.objects(course__in=[course_title])
    theCourse = theCourse[0] if len(theCourse) > 0 else theCourse

    if (not len(theCourse) or not len(theCourse.all_emails)):
        print('Removing process for ' + course_title)
        sched.remove_job(course_title)

    all_courses = webadvisorQuery({
        'VAR1': 'F20',
        'VAR3': searchable[1],
        'VAR6': 'G'
    })

    found = None
    for course in all_courses['data'].values():
        if course['Section Name and Title'] == course_title:
            found = course
            break

    if found:
        cap = int(found['Available/ Capacity'].split('/')[0])
        if (cap > 0):
            emails = [email.email for email in theCourse.all_emails]
            comm.sendEmail(emails, course_title)
            theCourse.delete()
Example #5
0
def main():        
    com = Communication()
    sound = Sound()

    try:
        executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
        
        # start MIDI as a concurrent executor
        sound.quit_midi = False
        midi_sender = executor.submit(send_midi, sound)

        # init serial communication
        # ser = com.init_serial()
        com.init_serial()
        
        # start serial as a concurrent executor
        quit_recv = False
        serial_receiver = executor.submit(recv_serial, com, sound)

        # start video stream
        video_stream(com , sound)

        # this block is for stoping process with terminating receive after video_stream()finished
        while True:
            try:
                key = input()
                time.sleep(1) # wait for checking input
                if(key == KEY_RECEIVER_STOP):
                    print("accepted f command for stopping \n")
                    break
                    
                # if anything from standard input, write back to AVR.
                key += "\n"
                com.ser.write(str.encode(key))
            except:
                print(traceback.format_exc())
                print("\nstop receiver and midi sender thread\n")
                exit(1)
        
    except concurrent.futures.CancelledError:
        print(traceback.format_exc())
        print("executor is cancelled\n")
    except:
        print(traceback.format_exc())
    finally:
        print("main is waiting for stopping threas")
        # do not wait the queue empty as AVR is working asynchronouly
        # serial_q.join()
        
        com.quit_recv = True
        sound.quit_midi = True
        # wait until executor(receiver) finishes
        while not serial_receiver.done():
            time.sleep(1)
        
        while not midi_sender.done():
            time.sleep(1)

        print("main finished")
        exit(0)
Example #6
0
    def test_false_url(self):
        url = 'asdfasdfff'
        meas = measurement.Measurement(0, 0, 0, 0, 0, 0)
        com = Communication(url)

        with self.assertRaises(Exception):
            com.post_measurement(meas)
Example #7
0
def main():
    # num = sys.argv[1]
    num = '81'
    print(num)
    env_name = 'SuperMarioBros-{}-{}-v0'.format(num[0], num[1])
    print(env_name)
    communication = Communication(child_num=process_num)

    brain = ACBrain(talker=communication.master, env_name=env_name)

    envs_p = []

    seed = get_seed()
    for i in range(process_num):
        agent = Agent(talker=communication.children[i])
        env_temp = Env(agent, i, seed=seed + i, env_name=env_name)
        envs_p.append(Process(target=env_temp.run, args=()))

    for i in envs_p:
        i.start()

    tfb_p = subprocess.Popen(['tensorboard', '--logdir', "./logs/scalars"])

    brain.run()

    for p in envs_p:
        p.terminate()
    tfb_p.kill()
Example #8
0
    def test_none_data(self):
        url = 'https://optiair.azurewebsites.net/api/'
        meas = None
        com = Communication(url)

        with self.assertRaises(AttributeError):
            com.post_measurement(meas)
Example #9
0
    def test_wrong_url(self):
        url = 'https://optiair.azurewebsites.net/api/asdf'
        meas = measurement.Measurement(0, 0, 0, 0, 0, 0)
        com = Communication(url)

        with self.assertRaises(requests.HTTPError):
            com.post_measurement(meas)
    def __init__(self, parent, mode):
        super(GameBoard, self).__init__(parent)

        self.parent_widget = parent

        self.BoardWidth = 32
        self.BoardHeight = 18
        self.mutex = QMutex()

        # tile width/height in px
        self.TILE_SIZE = 16

        self.mode = mode
        self.commands_1 = []
        self.commands_2 = []

        self.enemies_list = []
        self.bullets_list = []

        self.socket = None
        if mode is GameMode.MULTIPLAYER_ONLINE_HOST or mode is GameMode.MULTIPLAYER_ONLINE_CLIENT:
            self.communnication = Communication(mode, 50005)
            if self.communnication.socket is not None:
                self.socket = self.communnication.socket
                self.conn = self.communnication.conn
            else:
                print("Error on socket creation.")

        self.initGameBoard()
Example #11
0
    def test_motor_control_joysick(self):
        # Testing joystick control
        port = '/dev/tty.usbmodem1433401'
        baudrate = 9600
        timeout = 3
        arduino = Communication(port, baudrate, timeout)
        joystick = Joystick()
        key_q = False
        t = time.time()
        while not key_q:
            key_q = joystick.getJS('R2')
            data_1 = joystick.getJS('axis2')
            data_2 = joystick.getJS('axis3') * 45
            data_3 = '100'
            data = ','.join([str(data_1), str(data_2), data_3])
            if data:
                t = time.time()
                arduino.send(data)
            if time.time() - t > 20:
                key_q = True

            while not arduino.buffer and data:
                arduino.receive()
                if arduino.buffer:
                    print(arduino.buffer)
            arduino.set_buffer(None)
Example #12
0
    def __init__(self, client_id: str, server_host: str, server_port: int,
                 protocol_spec: ProtocolSpec, value_dict: Dict[Secret, int]):
        self.comm = Communication(server_host, server_port, client_id)

        self.client_id = client_id
        self.protocol_spec = protocol_spec
        self.value_dict = value_dict
Example #13
0
 def __init__(self, name, free_rooms, id, coordinates, doctors):
     self.name = name
     self.doctors = self.create_doctors()  # List of created doctors
     self.free_rooms = free_rooms  # int
     self.id = id  # int
     self.coordinates = coordinates  # array [float, float]
     self.communication = Communication(
         self.id)  # Communication with the server
     self.appointments = {}  # dictonary of all appointments
Example #14
0
    def __init__(self):
        self.com = Communication()
        self.com.start()

        self.cap = cv2.VideoCapture(1)
        _, frame = self.cap.read()
        self.height, self.width, _ = frame.shape
        self.etalonnage_top_left = (self.width/2 - self.detection_size, self.height / 2 - self.detection_size)
        self.etalonnage_bottom_right = (self.width/2 + self.detection_size, self.height / 2 + self.detection_size)
Example #15
0
 def __init__(self, device):
     self._GeneralCommands = {
         GeneralCommand.GetDeviceInformation: None,
         GeneralCommand.SetVoltage: None,
         GeneralCommand.GetVoltage: None,
         GeneralCommand.SetCurrent: None,
         GeneralCommand.GetCurrent: None,
         GeneralCommand.SelectChannel: None,
         GeneralCommand.SetOutput: None,
     }
     self.__device = Communication(device)
Example #16
0
def main():
    # Setup logging
    logger = logging.getLogger('control')
    logger.setLevel(logging.DEBUG)
    filehandler = logging.FileHandler('main.log')
    filehandler.setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    filehandler.setFormatter(formatter)
    console.setFormatter(formatter)
    logger.addHandler(filehandler)
    logger.addHandler(console)

    # Connect to xBee
    com = Communication(COM_CONNECTION_STRING, 0.1)

    logger.debug("Connected to wireless communication tansceiver")

    #hardcoded file format
    n_channels = 1
    sample_width = 2
    framerate = 44100
    n_frames = 204800
    comp_type = "NONE"
    comp_name = "not compressed"

    #Send file
    logger.debug("Sending test file")
    f = wave.open("test1.wav", "rb")

    logger.debug("File opened")

    bytesSent = 0
    lastBytesSent = 0
    f1 = f.readframes(n_frames)

    #send file
    for x in f1:
        com.sendAudio(bytes([x]))
        bytesSent = bytesSent + 1
        if bytesSent >= lastBytesSent + 1024:
            lastBytesSent = lastBytesSent + 1024
            logger.debug(bytesSent)

    #file sent
    f.close()
    logger.debug("File sent")

    # Program end
    logger.debug("Finished program.")
    sys.exit(0)
Example #17
0
 def __init__(self, parent=None):
     #**Variables**#
     self.signedIn = False
     self.interface = Interface.Interface()
     self.communication = Communication.Communication()
     self.userList = list()
     self.userListInitialized = False
     self.db = DataCom.DataCom()
     self.buddyList = list()
     self.chatBot = False
     self.pendulimID = None
     #self.emoticons = self.interface.getEmoticons()
     self.firstRun()
Example #18
0
    def __init__(self):
        self.communication = Communication()

        self.runInBackground = True
        self.backgroundTask = QTimer()
        self.backgroundTask.setInterval(10)
        self.backgroundTask.setSingleShot(False)
        self.backgroundTask.timeout.connect(self.main_loop)

        self.lastRefreshTime = 0.0
        self.connecting = False

        self.toolbar = None
        self.console = None
        self.graph = None

        self.consoleEntries = []
        self.consoleEntriesIndex = 0
        self.curveGraphEntries = []
        self.scatterGraphEntries = []
        self.splitters = []
        self.needFullUpdateConsole = False
        self.needSmallUpdateConsole = False
        self.needUpdateCurveGraph = False
        self.needUpdateScatterGraph = False
        self.lastSensorPrintTime = 0

        self.currentTime = 0  # ms
        self.tMin = None  # ms
        self.tMax = 0  # ms
        self.zoom = 0  # ms

        subscriptionTypes = [
            CommandType.SUBSCRIPTION_CURVE_DATA,
            CommandType.SUBSCRIPTION_SCATTER_DATA,
            CommandType.SUBSCRIPTION_TEXT
        ]
        self.subscriptions = []
        for c in COMMAND_LIST:
            if c.type in subscriptionTypes:
                self.subscriptions.append(False)
        self.subscriptions[INFO_CHANNEL] = True
        self.subscriptions[ERROR_CHANNEL] = True
        self.subscriptions[TRACE_CHANNEL] = True
        self.subscriptions[SPY_ORDER_CHANNEL] = True

        self.command_from_id = {}
        for command in COMMAND_LIST:
            self.command_from_id[command.id] = command
Example #19
0
    def __init__(self, camera):

        self.actions = mp.Array('i', [1])

        self.cameras = {
            'usb': 0,
            'china': 'rtsp://192.168.1.11:554/live/0/MAIN',
            'intelbras': 'rtsp://*****:*****@@192.168.1.11:554',
        }

        self.box = mp.Array('i', [0])
        self.battery = mp.Array('i', [0, 0, 0, 0, 0, 0, ])
        self.lat_long_actual = mp.Array('d', [0.0, 0.0])
        self.c = Communication(port='/dev/SERIAL_PORT')
        self.r = Recognition(camera=self.cameras[camera], camera_rasp=False, show_image=True)
Example #20
0
def main():
    communication = Communication(child_num=process_num)

    brain = ACBrain(talker=communication.master)

    envs_p = []
    for i in range(process_num):
        agent = Agent(talker=communication.children[i], seed=i)
        env_temp = Env(agent, i + 1)
        envs_p.append(Process(target=env_temp.run, args=()))

    for i in envs_p:
        i.start()

    brain.run()
def main():
    config = get_config()
    # Wraps arg parse functionallity around train function so that it can be provided as arguments
    parser = argparse.ArgumentParser(
        description='Trains a language model from a wiki dataset')
    parser.add_argument(
        'lm_fit', help='The wiki dump name to train a language model for')
    parser.add_argument('lm_flow',
                        help='Name of the model, used in exported files etc')
    parser.add_argument(
        'fit_dump', help='The wiki dump name to train a language model for')
    parser.add_argument('flow_dump',
                        help='Name of the model, used in exported files etc')
    parser.add_argument(
        '--test-mode',
        help="makes dataset smaller to see if the script actually runs",
        action='store_true')
    parser.add_argument('--epochs',
                        type=int,
                        default=5,
                        help="Number of epochs to run for")
    parser.add_argument('--batch_size',
                        type=int,
                        default=64,
                        help="Batch size")
    parser.add_argument('--gpu', type=int, default=-1, help="Gpu to use")
    parser.add_argument('--out',
                        default='result',
                        help="Folder to put results")
    parser.add_argument('--grad-clip', default=True, help="Clip gradients")
    parser.add_argument('--brpoplen', type=int, default=35)
    parser.add_argument('--resume', default='')
    parser.add_argument('--max-seq-size', default=250000, type=int)
    args = parser.parse_args()
    com = Communication(args.out)
    com.add_text("Type", "Translation via matrix")

    # keep time
    com.add_text("Start date", time.strftime("%c"))
    start = time.time()

    train(com, args.lm_fit, args.lm_flow, args.fit_dump, args.flow_dump,
          args.test_mode, args.epochs, args.batch_size, args.gpu, args.out,
          args.grad_clip, args.brpoplen, args.resume, args.max_seq_size)
    diff = time.time() - start
    com.add_text('time', seconds_to_str(diff))
    com.send_slack(config.get('slack', 'channel'),
                   config.get('slack', 'api_token'))
Example #22
0
    def __init__(self):
        self.db = DataBase(data_base='cache.db')
        self.camera, self.communication = self.read_config()
        self.timer_process = TimerProcess()

        self.r = Recognition(config=self.camera, db=self.db)
        self.c = Communication(config=self.communication,
                               code_recognition=self.r,
                               timer_process=self.timer_process,
                               db=self.db)

        self.station = self.camera.station_id
        self.carts = mp.Array('i', self.r.create_list(12))

        self.connection = self.c.data_call()

        self.QRBE1 = self.c.create_digit('QRBE1,{}'.format(self.station))
    def __init__(self, parent, mode):
        super(GameServerWidget, self).__init__(parent)
        self.is_started = False
        self.port = 50006
        self.mode = mode

        if self.mode == 1:  #multiplayer
            self.game_server_frame1 = GameServerFrame(self, 50005)
        else:
            self.communication = Communication(
                GameMode.MULTIPLAYER_ONLINE_HOST, 50005, 2)

            self.game_server_frame1 = GameServerFrame(self, self.port)
            self.port += 1
            self.game_server_frame2 = GameServerFrame(self, self.port)
            self.port += 1
            self.game_server_frame3 = GameServerFrame(self, self.port, True)
 def __init__(self, oc_driver_config=DEFAULT_CONFIG):
     """
     CONNECTION_STRING
     baud_rat
     Drop_vol # in nL, use to calculate volume in Methods
     xlevel
     ylevel
     inche # mm/inche
     dpi # resolution of the Hp cartdrige (datasheet), dpi=number/inch
     # distance of one nozzle to the next one  round(inche/dpi,3)
     visu_roi
     """
     self.communication = Communication(
         oc_driver_config['connection_string'],
         oc_driver_config['baud_rate'])
     self.communication.setup_log_file(oc_driver_config['log_file_path'])
     self.config = oc_driver_config
     self.config['reso'] = round(self.INCHE / self.config['dpi'], 3)
Example #25
0
    def __init__(
            self,
            client_id: str,
            server_host: str,
            server_port: int,
            protocol_spec: ProtocolSpec,
            value_dict: Dict[Secret, int]
    ):

        self.comm = Communication(server_host, server_port, client_id)

        self.client_id = client_id
        self.protocol_spec = protocol_spec
        self.value_dict = value_dict

        self.secrets = list(value_dict.keys())

        self.own_shares = dict()
Example #26
0
def run():
# the execution of all code shall be started from within this function
    print('Hello World')
    planet = Planet()
    odometry = Odometry()
    movement_functions = Movement(motor_list = (ev3.LargeMotor('outB'), ev3.LargeMotor('outC')), odometry = odometry)
    line_follower = follow.LineFollowing(colour_sensor = ev3.ColorSensor('in2'),
                         ts_list = (ev3.TouchSensor('in1'), ev3.TouchSensor('in4')), movement=movement_functions, odometry = odometry)
    communication = Communication(planet = planet, odometry = odometry)
    communication.connect()
    line_follower.colour_calibration()
    line_follower.line_following()
    communication.first_communication()
    sleep(2)
    line_follower.path_recognising()

    while True:
        #odometry.odometry_calculations()
        line_follower.line_following()
        line_follower.path_recognising()
Example #27
0
def main():
    # Initialisation
    lidar = RPLidar('/dev/ttyUSB0')
    param = Param()
    move = Move(param.odrv0)
    com = Communication('/dev/ttyACM1')

    lidar.start_motor()
    param.config()
    param.calib()
    com.waitEndMove(Communication.MSG["Initialisation"])
    time.sleep(1)

    # Creation du timer
    timer = RIR_timer(com, (param, move), lidar)

    # Lancement du timer
    timer.start_timer()

    # Action pour les tests
    move.translation(50000, [False] * 5)
Example #28
0
def run():
    # DO NOT EDIT
    # the deploy script uses this variable to stop the mqtt client after your program stops or crashes.
    # your script isn't able to close the client after crashing.
    global client
    client = mqtt.Client(
        client_id=str(
            uuid.uuid4()),  # client_id has to be unique among ALL users
        clean_session=False,
        protocol=mqtt.MQTTv31)

    # the execution of all code shall be started from within this function
    # ADD YOUR OWN IMPLEMENTATION HEREAFTER
    bob = Robot()
    bob.drive()
    planet = Planet()
    com = Communication(client, planet)
    bob.setView(Direction.SOUTH)
    com.timer()
    bob.setPosition(com.get_startP())
    if not com.node_scanned():
        com.scan_result(bob.scanPoint(Direction.SOUTH))
    bob.turn_by_direction(com.where_to_go())
    playSound_telekom()
    bob.drive()
    while True:
        #got to point
        com.discovered_path(bob.createMessage())
        position = com.get_korre_pos()
        bob.setPosition(position[0])
        bob.setView(position[1])
        if not com.node_scanned():
            com.scan_result(bob.scanPoint())
        direction = com.where_to_go()
        if direction is None:
            playSound_weAreNumberOne()
            break
        playSound_telekom()
        bob.turn_by_direction(direction)
        bob.drive()
Example #29
0
def main():
    # Setup logging
    logger = logging.getLogger('control')
    logger.setLevel(logging.DEBUG)
    filehandler = logging.FileHandler('main.log')
    filehandler.setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    filehandler.setFormatter(formatter)
    console.setFormatter(formatter)
    logger.addHandler(filehandler)
    logger.addHandler(console)

    # Connect to xBee
    com = Communication(COM_CONNECTION_STRING, 0.1)
    logger.debug("Connected to wireless communication tansceiver")

    #Send file
    logger.debug("Sending coordinates")
    x1 = 23.67
    y1 = 0.1823
    x2 = 121.213
    y2 = 123.123
    x3 = 321.321
    y3 = 657.765
    com.send(x1)
    com.send(y1)
    com.send(x2)
    com.send(y2)
    com.send(x3)
    com.send(y3)
    #file sent, inform the receiver
    logger.debug("Coordinates sent")
    com.send("EndOfFile")

    # Program end
    logger.debug("Finished program.")
    sys.exit(0)
Example #30
0
 def __init__(self, parent=None):
     #**Variables**#
     self.signedIn = False
     self.signedMsnIn = False
     self.interface = Interface.Interface(self.createAcct, self.deleteAcct)
     self.communication = Communication.Communication()
     self.userList = list()
     self.msnList = list()
     self.jabList = list()
     self.userListInitialized = False
     self.db = DataCom.DataCom()
     self.buddyList = list()
     self.status = None
     self.chatBot = False
     self.jabber = list()
     self.msn = list()
     self.howie = False
     self.pendulimID = None
     #self.emoticons = self.interface.getEmoticons()
     self.firstRun()
     self.enableAnsweringAwaychecked = False
     self.facebookcount = 0