コード例 #1
0
ファイル: potone.py プロジェクト: tatoflam/potone
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)
コード例 #2
0
ファイル: Robot.py プロジェクト: RIR-Legends/CdFR_2019
    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()
コード例 #3
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)
コード例 #4
0
ファイル: worker.py プロジェクト: woudie/guelph_alerts
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()
コード例 #5
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)
コード例 #6
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)
コード例 #7
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
コード例 #8
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)
コード例 #9
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)
コード例 #10
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)
コード例 #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)
コード例 #12
0
class Test(unittest.TestCase):
    def __init__(self, config):
        unittest.TestCase.__init__(self)
        self.config = config
        self.communication = None

    def setUp(self):
        self.communication = Communication(self.config.target_ip,
                                           self.config.target_port,
                                           self.config.protocol_version,
                                           log=log)

    def tearDown(self):
        self.communication.close()
コード例 #13
0
ファイル: backend.py プロジェクト: gobgob/CDR-2020
    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
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'))
コード例 #15
0
ファイル: cli.py プロジェクト: shivam-5/Blockchain
    def __addshipment(self, params):
        if len(params) == 0 or params[0] in ["?", "HELP"]:
            self.__show_command_help(
                usage="addshipment id srclocation destlocation qty",
                description="Enters a shipment into the network."
            )
        elif len(params) == 3:
            shipment_id = params[0]
            src = params[1]
            dest = params[2]
            qty = params[3]

            confirmation = input(
                "Are you sure you want to add this shipment to the blockchain? This action is irreversible without the agreement of all network nodes (y/n): ").upper()

            if confirmation == "Y":
                print("\nAdding to blockchain...")
                blockchain = Blockchain.instance()

                self.node_comm = Communication.instance()

                transaction = blockchain.create_distributor_transaction(shipment_id, blockchain.get_node_id(), src, dest, qty,
                                                                        blockchain.get_node_type(),
                                                                        blockchain.get_node_name())
                self.node_comm.broadcast_transaction(transaction)
                print("Shipment is now pending.\n> ", end="")
コード例 #16
0
    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()
コード例 #17
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
コード例 #18
0
    def __init__(self):
        self.NODE_ID = None
        self.NODE_NAME = None
        self.NODE_TYPE = None
        self.setup_node()
        # Create the blockchain instance for this node if one doesn't exist
        if not os.path.exists("blockchain.pickle"):
            self.blockchain = Blockchain.instance(node_id=self.NODE_ID, node_name=self.NODE_NAME,
                                                  node_type=self.NODE_TYPE)
            print("First time booting! Creating genesis block...")
            self.blockchain.create_genesis()
        else:
            print("Successfully identified blockchain on this device. Loading into memory...")
            loaded_blockchain = self.load_blockchain()
            loaded_pending_transactions = self.load_pending_transactions()
            self.blockchain = Blockchain.instance(loaded_blockchain, loaded_pending_transactions, self.NODE_ID,
                                                  self.NODE_NAME, self.NODE_TYPE)
        API.instance()
        Consensus.instance(self.NODE_NAME)

        self.node_comm = Communication.instance(self.NODE_ID, self.NODE_NAME, self.blockchain, self.NODE_TYPE)
        self.blockchain.set_communication(self.node_comm)
        print(self.NODE_ID, self.NODE_NAME)
        # Send a connection request to other distributor nodes in network
        if self.NODE_TYPE == 'DISTRIBUTOR':
            self.node_comm.notify_connection('connect')
コード例 #19
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()
コード例 #20
0
    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()
コード例 #21
0
ファイル: processIA.py プロジェクト: furmi/simu2014
class ProcessIA():
	"""
	Classe qui va lancer une IA en subprocess.
	"""
	def __init__(self, liste_robots):
		self.__bigrobot = liste_robots[0]
		self.__minirobot = liste_robots[1]
		self.__robots = liste_robots
		self.__hokuyo = Hokuyo(self.__robots)
		self.__communication = Communication(self.__bigrobot, self.__minirobot, self.__hokuyo)
		#communication de data entre l'IA et le simu
		self.__parent_conn, self.__child_conn = Pipe()
		#TODO lancer l'IA
		self.__process = Process(target=test.testIa, args=(self.__child_conn,))
		self.__process.start()
		#on démarre le thread de lecture des données IA renvoyées à travers le pipe
		self.__read_thread = threading.Thread(target=self.__readPipe)
		self.__read_thread.start()
		#on démarre le thread d'écriture des données IA à envoyer à travers le pipe
		self.__write_thread = threading.Thread(target=self.__writePipe)
		self.__write_thread.start()

	def __writePipe(self):
		"""
		Envoie des données à l'IA à travers le Pipe
		Tourne dans un thread
		"""
		while True:
			data = self.__communication.readOrdersAPI()
			if data != -1:
				self.__parent_conn(data)

	def __readPipe(self):
		"""
		Méthode de lecture des données envoyées par l'IA via le pipe.
		recv est bloquant, donc lancé dans un thread
		"""
		while True:
			self.__parseDataIa(self.__parent_conn.recv())

	def __parseDataIa(self, data):
		"""
		Formate les données IA reçues pour les adapter à la méthode
		sendOrderAPI de Communication
		"""
		self.__communication.sendOrderAPI(data[0],data[1],data[2],data[3],data[4])
コード例 #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))
コード例 #23
0
ファイル: smc_party.py プロジェクト: hedi-sassi/smc_project
    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()
コード例 #24
0
 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)
コード例 #25
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)
コード例 #26
0
ファイル: main.py プロジェクト: MarkHermreck/UAS-C2C2-2019
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)
コード例 #27
0
class Device:
    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)

    def __SelectChannel(self, channel):
        self.__device.Write(
            self._GeneralCommands[GeneralCommand.SelectChannel] % channel)

    def SetVoltage(self, channel, voltage):
        self.__SelectChannel(channel)

        self.__device.Write(self._GeneralCommands[GeneralCommand.SetVoltage] %
                            voltage)

    def GetVoltage(self, channel):
        self.__SelectChannel(channel)
        self.__device.Write(self._GeneralCommands[GeneralCommand.GetVoltage])
        val = self.__device.Read(
            self._GeneralCommands[GeneralCommand.GetVoltage].length)
        print "val=" + str(val)

    def SetCurrent(self, channel, current):
        pass

    def GetCurrent(self, channel):
        pass

    def SetOutput(self, channel, state):
        self.__SelectChannel(channel)
        self.__device.Write(self._GeneralCommands[GeneralCommand.SetOutput] %
                            state)
コード例 #28
0
ファイル: main.py プロジェクト: MarkHermreck/UAS-C2C2-2019
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)
コード例 #29
0
ファイル: Pendulim.py プロジェクト: ratanakpek/pendulim
 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()
コード例 #30
0
ファイル: robot.py プロジェクト: ebaustria/RoboLab
    def __init__(self, mqtt_client, logger):
        # Create Planet and planet_name variable
        self.planet = Planet()
        self.planet_name = None

        # Setup Sensors, Motors and Odometry
        self.rm = ev3.LargeMotor("outB")
        self.lm = ev3.LargeMotor("outC")
        self.sound = ev3.Sound()
        self.odometry = Odometry(self.lm, self.rm)
        self.motors = Motors(self.odometry)
        self.cs = ColorSensor(self.motors)
        self.us = Ultrasonic()

        # Setup Communication
        self.communication = Communication(mqtt_client, logger, self)

        # Create variable to write to from communication
        self.start_location = None
        self.end_location = None
        self.path_choice = None
        self.running = True
コード例 #31
0
ファイル: router.py プロジェクト: qruk/dynamic_router
class Router:
    # Собственный адрес маршрутизатора (любой строковый идентификатор), на который будут пересылаться пакеты и который будет находится в таблице маршрутизации другого роутера
    address_id = None

    # Таблица маршрутизации {address1: {port1: ping1, port2: ping2, ...}, address2:...}
    router_table = {}

    # Cловарь порт-объект порта
    ports = {}

    # Список доступных соединений [(host1, port1), (host2, port2), ...]
    # Абстракция физических (проводных) соединений
    connections = []

    # Конфигурация серверной части маршрутизатора
    # config = {port_id: str, host_id: int, server_buffer: int, server_max_queue: int}
    config = {}

    def __init__(self, config, connections, address_id=None):
        self.config = config
        self.connections = connections
        self.address_id = self.router(address_id)
        self.communication = Communication(self)

    def __str__(self):
        return (str(self.config['host_id']) + ':' +
                str(self.config['port_id']))

    def router(self, address_id):
        if not address_id:
            time_id = str('{:.9f}'.format(time())).split('.')
            return time_id[0][:3] + '.' + time_id[1][-9:-6] + '.' + time_id[1][
                -6:-3] + '.' + time_id[1][-3:]
        else:
            return address_id if (type(address_id) is str) else str(address_id)

    def start(self):
        self.communication.start()
コード例 #32
0
ファイル: processIA.py プロジェクト: furmi/simu2014
	def __init__(self, liste_robots):
		self.__bigrobot = liste_robots[0]
		self.__minirobot = liste_robots[1]
		self.__robots = liste_robots
		self.__hokuyo = Hokuyo(self.__robots)
		self.__communication = Communication(self.__bigrobot, self.__minirobot, self.__hokuyo)
		#communication de data entre l'IA et le simu
		self.__parent_conn, self.__child_conn = Pipe()
		#TODO lancer l'IA
		self.__process = Process(target=test.testIa, args=(self.__child_conn,))
		self.__process.start()
		#on démarre le thread de lecture des données IA renvoyées à travers le pipe
		self.__read_thread = threading.Thread(target=self.__readPipe)
		self.__read_thread.start()
		#on démarre le thread d'écriture des données IA à envoyer à travers le pipe
		self.__write_thread = threading.Thread(target=self.__writePipe)
		self.__write_thread.start()
コード例 #33
0
ファイル: groundStation.py プロジェクト: c0nrad/wilfred
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.wilfredCommunication = Communication()
        self.wilfredCommand = Command(self.wilfredCommunication)

        # Motor Sliders
        self.connect(self.motor0SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor0)
        self.connect(self.motor1SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor1)
        self.connect(self.motor2SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor2)
        self.connect(self.motor3SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor3)
        
        # Connect
        self.connect(self.connectButton, SIGNAL("pressed()"), self.connectToWilfred)
        self.connect(self.disconnectButton, SIGNAL("pressed()"), self.disconnectFromWilfred)
        
        # Accelerometer
        self.initAccelerometers()

        # Abort Button
        self.connect(self.abortButton, SIGNAL("pressed()"), self.abortWilfred)
コード例 #34
0
ファイル: run.py プロジェクト: kamilfocus/PKSS
#!/usr/bin/env python3
__author__ = "Rafał Prusak"
__doc__ = "skrypt uruchamiający symylację dostawcy energi"

from communication import Communication
from wheather import WheatherGenerator
from config import Configuration
from model import Model
from logs import Logger
import time
import json

if __name__ == "__main__":

    Logger.init()

    with open('data.txt') as data_file:
        WheatherGenerator.data = json.load(data_file)
    # print(WheatherGenerator.data.keys())

    Configuration.init()
    provider_model = Model()
    communicator = Communication(provider_model)

    while 1:
        # time.sleep(2)
        communicator.run()
コード例 #35
0
ファイル: groundStation.py プロジェクト: c0nrad/wilfred
class GroundStation(QMainWindow, mainWindow.Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.wilfredCommunication = Communication()
        self.wilfredCommand = Command(self.wilfredCommunication)

        # Motor Sliders
        self.connect(self.motor0SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor0)
        self.connect(self.motor1SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor1)
        self.connect(self.motor2SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor2)
        self.connect(self.motor3SpinBox, SIGNAL("valueChanged(int)"), self.updateMotor3)
        
        # Connect
        self.connect(self.connectButton, SIGNAL("pressed()"), self.connectToWilfred)
        self.connect(self.disconnectButton, SIGNAL("pressed()"), self.disconnectFromWilfred)
        
        # Accelerometer
        self.initAccelerometers()

        # Abort Button
        self.connect(self.abortButton, SIGNAL("pressed()"), self.abortWilfred)

    def updateMotor0(self, value):
        goodMessage("updateMotor0: new motor value: ", value)
        self.wilfredCommand.setMotorSpeed(0, value)

    def updateMotor1(self, value):
        goodMessage("updateMotor1: new motor value: ", value)
        self.wilfredCommand.setMotorSpeed(1, value)

    def updateMotor2(self, value):
        goodMessage("updateMotor2: new motor value: ", value)
        self.wilfredCommand.setMotorSpeed(2, value)

    def updateMotor3(self, value):
        goodMessage("updateMotor3: new motor value: ", value)
        self.wilfredCommand.setMotorSpeed(3, value)
        
    def connectToWilfred(self):
        ip = str(self.ipAddressEdit.text()).strip()
        port = int(self.portEdit.text())
        self.wilfredCommunication.setupSocket(ip, port)
        
    def disconnectFromWilfred(self):
        self.wilfredCommunication.closeConnection()

    def initAccelerometers(self):
        timer = QTimer(self);
        self.connect(timer, SIGNAL("timeout()"), self.updateAccelerometer)
        self._counter = 0
        timer.start(1000);

    def updateAccelerometer(self):
        if not self.wilfredCommunication.checkConnection():
            return

        (xAccel, yAccel, zAccel) = self.wilfredCommand.getAccel()
        self.xAccelEdit.setText(str(xAccel))
        self.yAccelEdit.setText(str(yAccel))
        self.zAccelEdit.setText(str(zAccel))

    def abortWilfred(self):

        self.masterMotorSlider.setValue(1)
        self.masterMotorSlider.setValue(0)
        errorMessage("Aborting wilfred")