コード例 #1
0
    def __init__(self, ser):
        self._last_angles = np.ndarray
        self._last_imu = np.ndarray

        # https://www.pieter-jan.com/node/11
        self.pitch_acc = 0
        self.roll_acc = 0
        self.pitch = 0
        self.roll = 0

        self._tx_thread = Transmitter(name="tx_th", ser=ser)
        self._rx_thread = Receiver(name="rx_th", ser=ser)
        self._rx_thread.set_timeout(0.010)
        self._rx_thread.bind(self.receive_callback)

        self._pub_imu = rp.Publisher('imu_raw', Imu, queue_size=1)
        self._pub_joint_states = rp.Publisher('joint_states',
                                              JointState,
                                              queue_size=1)
        self._motor_map = rp.get_param("~motor_mapping")
        self._imu_calibration = rp.get_param("~imu_calibration")
        for motor in self._motor_map:
            self._motor_map[motor]["subscriber"] = rp.Subscriber(
                motor + "/command", Float64, self.trajectory_callback, motor)
            self._motor_map[motor]["publisher"] = rp.Publisher(
                motor + "/state", JointControllerState, queue_size=1)
            self._motor_map[motor]["value"] = 0.0

        self._publish_timer = rp.Timer(rp.Duration(nsecs=10000000),
                                       self.send_angles)
コード例 #2
0
def main():
    nrx=3
    # Create a tx
    ntx=3
    ta = None
    #ta = SampleRate()
    transmitter = Transmitter(ntx,ta)
    # Create a channel
    
    chan = TraceChan()
    num_chans=1
    length = chan.create_chan(transmitter.Ntx,nrx)

    #ta = OracleRA(chan)
    #transmitter.set_transmit_ra(ta)
    #receiver = Receiver(MaxTputRA(),nrx)
    #receiver = Receiver(MinEngRA(),nrx)
    receiver = Receiver(EngTputRA(),nrx)
    #receiver = Receiver(EffSnrRA(),nrx)
    #receiver = Receiver(RxSampleRate(),nrx)
    #receiver = Receiver(RxOracle(),nrx)

    #length =10
    for num in range(0,length):
        pkt = transmitter.transmit_pkt()
        chan.apply_channel(pkt)
        #print chan.curr_chan
        #print pkt
        
        # Create receiver
        receiver.receive_pkt(pkt)
        ack_pkt = receiver.get_feedback_pkt()
        
        transmitter.process_ack(ack_pkt)
コード例 #3
0
    def __init__(self):
        mainServerIP = globe.components.mainServerIp
        mainServerPort = globe.components.mainServerPort
        self.mainServerAddress = 'http://' + mainServerIP + ':' + mainServerPort

        # Starting receiver flask server process:
        print("Starting the receiver HTTP server...\n")

        self.serverThread = threading.Thread(target=initReceiver, args=())
        self.serverThread.start()
        time.sleep(1)

        self.transmitter = Transmitter(self.mainServerAddress)

        # Send the content of jsonPath to each devices:
        print("\nSending JSON paths to devices...")

        archAddress = globe.content[0][:-1]
        connMapAddress = globe.content[1][:-1]
        data = archAddress + '#' + connMapAddress

        for ip in globe.components.devicesIp:
            address = f'http://{ip}:8484/updateJsonPath'  # f for format

            response = requests.post(address, data)
            if globe.jupyterFlag == 0:
                print(response.ok, response.status_code)

        time.sleep(1)
コード例 #4
0
 def __init__(self):
     self.__transmitter = Transmitter()
     self.__configpath = self.__set_configpath()
     self.__config = self.__init_config()
     self.__default_account = AccountManager.get_default_account()
     self.__accounts = []
     self.__load_accounts_from_config()
コード例 #5
0
 def __init__(self, numOfInputs):
     self.transmitter = Transmitter()
     self.receiver = Receiver()
     self.wirelessChannel = wireless_channel(0.1)
     self.numOfInputs = numOfInputs
     self.sigmaValues = [10, 1, 0.1]
     self.generated_Points = []
     self.colors = ['purple', 'yellow', 'orange']
コード例 #6
0
 def test_set_transmitter_exactly_once(self):
     tt = Transmitter()
     url = 'whee.com'
     username = '******'
     account = Account(url, username, None)
     tt.set_account(account)
     aa = ElyxerEntry()
     aa.set_transmitter(tt)
     self.assertRaises(TransmitterAlreadyExistsError, lambda: aa.set_transmitter(tt))
コード例 #7
0
 def test_set_transmitter_exactly_once(self):
     tt = Transmitter()
     url = 'whee.com'
     username = '******'
     account = Account(url, username, None)
     tt.set_account(account)
     aa = ElyxerEntry()
     aa.set_transmitter(tt)
     self.assertRaises(TransmitterAlreadyExistsError,
                       lambda: aa.set_transmitter(tt))
コード例 #8
0
def main():
    if len(sys.argv) == 6:
        filename = sys.argv[1]
        card_type = sys.argv[2]
        energy_constraint = sys.argv[3]
        chan_pred = eval(sys.argv[4])
        increment = eval(sys.argv[5])
        print "filename: " + str(filename)
    else:
        print "Correct usage: python simulate_maxtput.py trace_file card_type tx/rx pred(True/False)"
        sys.exit(1)

    nrx = 3
    # Create a tx
    ntx = 3
    ta = None
    transmitter = Transmitter(ntx, ta)
    # Create a channel

    chan = TraceChan(filename)
    num_chans = 1
    length = chan.create_chan(transmitter.Ntx, nrx)

    extname = (
        filename.split("/")[-1].split(".")[0]
        + "_"
        + card_type
        + "_"
        + energy_constraint
        + "_pred"
        + str(chan_pred)
        + "_inc"
        + str(increment)
    )
    # print extname
    receiver = PPrReceiver(PPrMinEngRA(card_type, energy_constraint, chan_pred), nrx, extname)

    if length > 10000:
        length = 10000
    # length = 2

    for num in range(0, length):
        itr_tic = time.clock()
        pkt = transmitter.transmit_pkt()
        chan.apply_channel(pkt)
        # print chan.curr_chan
        # print pkt

        # Create receiver
        receiver.receive_pkt(pkt)
        ack_pkt = receiver.get_feedback_pkt()

        transmitter.process_ack(ack_pkt)
        itr_toc = time.clock()
コード例 #9
0
class Run(object):
    def __init__(self):
        channel = "/dev/rfcomm8"
        self.TR = Transmitter(channel)
        self.TR

    def main(self):
        while True:
            #self.TR.sendData("hello")
            result = instance.read()
            if result.is_valid():
                temp = "Temperature: %-3.1f C" % result.temperature
                humid = "Humidity: %-3.1f %%" % result.humidity
                self.TR.sendData("\n" + temp + '\n' + humid + "\n")
コード例 #10
0
    def __init__(self):
        self.drive_msg = DriveMessage()
        self.check_msg = CheckMessage()
        self._bus = can.interface.Bus(bustype='socketcan', channel='can0')
        self.transmitter = Transmitter(self._bus)
        self.receiver = Receiver(self._bus, self.update)
        self.data = CarData()
        self.last_update = time.time()
        self.notifier = can.Notifier(self._bus, [self.receiver])
        self.controller = PIController(proportional=0.05, integral=0.1)

        gpsd.connect()

        self.send_messages()
コード例 #11
0
 def __init__(self):
     self.__transmitter = Transmitter()
     self.__configpath  = self.__set_configpath()
     self.__config      = self.__init_config()
     self.__default_account = AccountManager.get_default_account()
     self.__accounts    = []
     self.__load_accounts_from_config()
コード例 #12
0
def clicked_btn():
    string = r'(25[0-5]|2[0-4][0-9]|[0]|[1]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[0]|[1]?[0-9][0-9]?)){3}'
    ip = IP_entry.get()
    port = int(port_spin.get())
    buff_size = int(Buff_size_spin.get())
    file_name = open_file_entry.get()
    Prog_bar_w.configure(maximum=os.path.getsize(file_name) // buff_size)
    if re.fullmatch(string, ip) and 10000 < int(port) < 65535 and 100 <= int(buff_size) <= 8958 and file_name:
        sender = Transmitter(ip, file_name, buff_size, port)
        t = Thread(target=sender.send, args=(queue,))
        txt.insert("insert",
                   'Sending {} to {} at port {}, UDP data size - {}'.format(os.path.basename(file_name), ip, port,
                                                                            buff_size) + '\n')
        txt.yview('end')
        try:
            t.start()
            check_queue()
        except ConnectionRefusedError:
            txt.insert("insert", "Error" + '\n')
            txt.insert("insert", "-" * 70 + '\n')
            txt.yview('end')
            messagebox.showinfo("Ошибка", "Удаленный компьютер не отвечает")
            Prog_bar_w.stop()
            Prog_bar_w["value"] = 0
        else:
            txt.insert("insert", "Done" + '\n')
            txt.insert("insert", "-" * 70 + '\n')
            txt.yview('end')
            open_file_entry.delete(0, 'end')
            Prog_bar_w.stop()
            Prog_bar_w["value"] = 0
    else:
        messagebox.showinfo("Ошибка", "Некоректные данные сетевого соединения или не выбран файл")
コード例 #13
0
def main():

    if sys.argv[1] == 'leap_motion':
        motion_capturer = MotionCapturerLeapMotion()
    elif sys.argv[1] == 'mouse':
        motion_capturer = MotionCapturerMouse()
    elif sys.argv[1] == 'mix':
        motion_capturer = MotionCapturerLeapAndMouse()

    transmitter = Transmitter(sys.argv[2])

    while True:
        try:
            (pitch, roll, yaw, throttle) = motion_capturer.get_axis_values()
            transmitter.send_axis_values(pitch, roll, yaw, throttle)
        except ValueError:
            print('Ignoring frame')
        except KeyboardInterrupt:
            motion_capturer.shutdown()
コード例 #14
0
	def __init__(self, daemon = False):
		self.__loggingLock = Lock()
		self.__lock = RLock()
		self.__jails = Jails()
		self.__daemon = daemon
		self.__transm = Transmitter(self)
		self.__asyncServer = AsyncServer(self.__transm)
		self.__logLevel = None
		self.__logTarget = None
		# Set logging level
		self.setLogLevel(3)
		self.setLogTarget("STDOUT")
コード例 #15
0
def main():
    if len(sys.argv) == 7:
       filename = sys.argv[1]
       card_type = sys.argv[2]
       energy_constraint = sys.argv[3]
       chan_pred = eval(sys.argv[4])
       threshold = eval(sys.argv[5])
       increment = eval(sys.argv[6])
       print "filename: "+str(filename)
    else:
        print "Correct usage: python simulate_engtput.py trace_file card_type tx/rx pred(True/False) threshold chan_increment"
        sys.exit(1) 

    nrx=3
    # Create a tx
    ntx=3
    ta = None
    transmitter = Transmitter(ntx,ta)
    # Create a channel
    
    chan = TraceChan(filename, increment)
    length = chan.create_chan(transmitter.Ntx,nrx)
 
    extname=filename.split('/')[-1].split('.')[0]+"_"+card_type+"_"+energy_constraint+"_pred"+str(chan_pred)+"th"+str(threshold)+"_inc"+str(increment)
    receiver = Receiver(EngTputRA(card_type,energy_constraint,chan_pred,threshold),nrx,extname)

    if length > 10000: length = 10000

    for num in range(0,length):
        pkt = transmitter.transmit_pkt()
        chan.apply_channel(pkt)
        #print chan.curr_chan
        #print pkt
        
        # Create receiver
        receiver.receive_pkt(pkt)
        ack_pkt = receiver.get_feedback_pkt()
        
        transmitter.process_ack(ack_pkt)
コード例 #16
0
	def __init__(self, midi_in, midi_out, loopback, modes):
		self.midi_in = midi_in
		self.led_control = Transmitter(midi_out)
		self.transmitter = Transmitter(loopback)

		self.active_mode = None
		self.active_bank = 0
		self.button_state = [False] * 12
		self.detune = 0
		self.octave = [0, 0]
		self.split_zone = 0

		self.black_key_indices = [
			1, 3, 6, 8, 10,
		]

		self.modes = modes
		for mode in self.modes:
			mode.register(self)

		# set initial mode on start
		self.set_mode(0)
		print('Ready!')
コード例 #17
0
 def test_upload_entry(self):
     tt = Transmitter()
     tt.set_account(self.account_with_good_password)
     filename = 'test_files/entry_test'
     entry = ElyxerEntry()
     entry.set_transmitter(tt)
     entry.load(filename)
     entry.set_title('WoooYAH!')
     tt.publish_entry(entry)
コード例 #18
0
def main():
    if len(sys.argv) == 5:
       filename = sys.argv[1]
       card_type = sys.argv[2]
       energy_constraint = sys.argv[3]
       chan_pred = eval(sys.argv[4])
       print "filename: "+str(filename)
    else:
        print "Correct usage: python simulate_effsnr.py trace_file card_type tx/rx pred(True/False)"
        sys.exit(1)

    nrx=3
    # Create a tx
    ntx=3
    ta = None
    transmitter = Transmitter(ntx,ta)
    # Create a channel
    
    chan = TraceChan(filename)
    num_chans=1
    length = chan.create_chan(transmitter.Ntx,nrx)
 
    extname=filename.split('/')[-1].split('.')[0]+"_"+card_type+"_"+energy_constraint+"_pred"+str(chan_pred)
    receiver = Receiver(EffSnrRAEng(card_type,energy_constraint,chan_pred),nrx,extname)

    for num in range(0,length):
        pkt = transmitter.transmit_pkt()
        chan.apply_channel(pkt)
        #print chan.curr_chan
        #print pkt
        
        # Create receiver
        receiver.receive_pkt(pkt)
        ack_pkt = receiver.get_feedback_pkt()
        
        transmitter.process_ack(ack_pkt)
コード例 #19
0
 def test_publish_image(self):
     Image.set_abs_reference_dir_from_html_file(self.filename)
     account = AccountManager.get_default_account()
     tt = Transmitter()
     tt.set_account(account)
     image = Image("some <img src='Suzanne.jpg' /> string")
     before = image.get_remote_src()
     self.assertEqual(before, None)
     tt.publish_image(image)
     after = image.get_remote_src()
     self.assertNotEqual(after, None)
def main():

    if len(sys.argv) == 5:
       filename = sys.argv[1]
       card_type = sys.argv[2]
       energy_constraint = sys.argv[3]
       chan_pred = False
       increment = 1
       print "filename: "+str(filename)
    elif len(sys.argv) == 6:
       filename = sys.argv[1]
       card_type = sys.argv[2]
       energy_constraint = sys.argv[3]
       chan_pred = False
       increment = eval(sys.argv[5])
       print "filename: "+str(filename)
    else:
        print "Correct usage: python simulate_effsnr.py trace_file card_type tx/rx pred(True/False) chan_increment"
        sys.exit(1)

    nrx=3
    # Create a tx
    ntx=3
    ta = None
    transmitter = Transmitter(ntx,ta)
    # Create a channel
    
    chan = TraceChan(filename,increment)
    length = chan.create_chan(transmitter.Ntx,nrx)
 
    ta = OraclePPrMaxTputRA(card_type,energy_constraint,chan)
    transmitter.set_transmit_ra(ta)
    extname=ta.name+"_"+filename.split('/')[-1].split('.')[0]+"_"+card_type+"_"+energy_constraint+"_pred"+str(chan_pred)+"_inc"+str(increment)
    receiver = PPrReceiver(RxOracle(card_type,energy_constraint),nrx,extname)

    if length > 10000: length = 10000

    #length =10
    for num in range(0,length):
        pkt = transmitter.transmit_pkt()
        chan.apply_channel(pkt)
        #print chan.curr_chan
        #print pkt
        
        # Create receiver
        receiver.receive_pkt(pkt)
        ack_pkt = receiver.get_feedback_pkt()
        
        transmitter.process_ack(ack_pkt)
コード例 #21
0
                )
        nodes.append(node)
        print(node)

    ################################################################################
    #Determine which node will be the transmitter for the simulation
    ################################################################################
    #boundary check the transmit node index
    tx_node = config['tx_node']
    if tx_node<1: #choose a random transmit node
        tx_node = random.randint(1,config['nodes'])
        print("Randomly Chose Node %d as the transmitter" % tx_node)
    tx_index=min(tx_node, config['nodes'])
    tx_index=max(tx_index, 1)
    tx_node = nodes[tx_index-1]
    transmitter = Transmitter(port=tx_node.phy_port)


    ################################################################################
    #Save all settings complied from defaults, test specific json and command line args as "last_run.json"
    ################################################################################
    with open("last_run.json", 'w') as f:
        json.dump(config, f, indent=2)
       
    ################################################################################
    #Write a spice file with the system setup
    ################################################################################
    with open("cable.p", 'w') as cable:
        cable.write("*lumped transmission line model with %d segments per meter at %d meters\n"\
        % (config['segments_per_meter'], config['length']))
        cable.write("*and a %f meter long cable\n" % config['length'])
コード例 #22
0
class D3MDevice:
	def __init__(self, midi_in, midi_out, loopback, modes):
		self.midi_in = midi_in
		self.led_control = Transmitter(midi_out)
		self.transmitter = Transmitter(loopback)

		self.active_mode = None
		self.active_bank = 0
		self.button_state = [False] * 12
		self.detune = 0
		self.octave = [0, 0]
		self.split_zone = 0

		self.black_key_indices = [
			1, 3, 6, 8, 10,
		]

		self.modes = modes
		for mode in self.modes:
			mode.register(self)

		# set initial mode on start
		self.set_mode(0)
		print('Ready!')

	def update(self):
		message = self.midi_in.get_message()

		if message is None:
			return

		command 	= message[0][0]
		note 		= message[0][1]
		velocity 	= message[0][2]

		# undefined command, send to both channels
		if command != NOTE_ON:
			self.transmitter.send(command, note, velocity, SPLIT_LEFT)
			self.transmitter.send(command, note, velocity, SPLIT_RIGHT)
			return

		# check if keybed is pressed
		if note >= 36 and note <= 96:
			# adjust velocity
			if (note % 12) in self.black_key_indices and velocity > 0:
				velocity -= (int)(math.log(velocity) * 2)
				velocity = max(velocity, 0)
			# select output channel
			zone = ((note - 36) / 12) % NUM_SPLIT_ZONES
			# detune note
			note += self.detune
			# select zone
			if zone >= self.split_zone:
				note += self.octave[SPLIT_RIGHT] * 12
				self.transmitter.send(NOTE_ON, note, velocity, SPLIT_RIGHT)
			else:
				note += self.octave[SPLIT_LEFT] * 12
				self.transmitter.send(NOTE_ON, note, velocity, SPLIT_LEFT)
		# check preset buttons
		elif note >= 0 and note < 12:
			if not self.button_state[note] and velocity == 127:
				self.active_mode.on_preset_pressed(note)
			elif self.button_state[note] and velocity == 0:
				self.active_mode.on_preset_released(note)
		# check preset banks
		elif note >= 14 and note < 24 and velocity == 127:
			bank_index = note - 14
			if bank_index != self.active_bank:
				self.set_mode(bank_index)
				self.active_bank = bank_index

	def cc_send_on(self, note):
		self.transmitter.send(NOTE_ON, note, 127, CONTROL_CHANNEL)

	def cc_send_off(self, note):
		self.transmitter.send(NOTE_OFF, note, 127, CONTROL_CHANNEL)

	def toggle_light(self, number, state = True):
		self.led_control.send(NOTE_ON, number, 127 if state else 0)
		self.button_state[number] = state

	def clear_lights(self):
		for i in range(12):
			self.toggle_light(i, False)

	def set_mode(self, bank_index):
		# set bank lights
		for i in range(10):
			self.led_control.send(NOTE_ON, i + 14, 0)
		self.led_control.send(NOTE_ON, bank_index + 14, 127)

		if self.modes[bank_index] is not self.active_mode:
			self.clear_lights()
			self.active_mode = self.modes[bank_index]
			self.active_mode.on_enter()

	def close(self):
		self.clear_lights()
		for i in range(10):
			self.led_control.send(NOTE_ON, i + 14, 0)
コード例 #23
0
class Car:
    def __init__(self):
        self.drive_msg = DriveMessage()
        self.check_msg = CheckMessage()
        self._bus = can.interface.Bus(bustype='socketcan', channel='can0')
        self.transmitter = Transmitter(self._bus)
        self.receiver = Receiver(self._bus, self.update)
        self.data = CarData()
        self.last_update = time.time()
        self.notifier = can.Notifier(self._bus, [self.receiver])
        self.controller = PIController(proportional=0.05, integral=0.1)

        gpsd.connect()

        self.send_messages()

    def update(self, data: CarData):
        self.last_update = time.time()
        self.data = data
        if self.tx_check(data.rx_check):
            self.periodic_update()
        else:
            self.send_messages()

    def can_error(self):
        self.check_msg.invalid_message_received()
        self.send_messages()

    @property
    def is_outdated(self):
        return time.time() - self.last_update > 1.0

    @property
    def is_ok(self):
        return self.data.has_control and not self.is_outdated

    def periodic_update(self):
        self.increment_msg_counts()
        self.update_from_controller()
        self.send_messages()
        self.clear_errors()

    def increment_msg_counts(self) -> None:
        self.drive_msg.increment_msg_count()
        self.check_msg.increment_msg_count()

    def update_from_controller(self) -> None:
        self.drive_msg.velocity = Driving.to_can(
            self.controller.update(self.velocity))

    def clear_errors(self) -> None:
        self.check_msg.clear_errors()

    def send_messages(self):
        if self.drive_msg is not None:
            self.transmitter.transmit(self.drive_msg)
        if self.check_msg is not None:
            self.transmitter.transmit(self.check_msg)

    def drive(self, v: float, s: float) -> None:
        print(f'Setting velocity {Driving.to_can(int(v))}')
        self.drive_msg.velocity = Driving.to_can(int(v))
        print(f'Setting steering {Steering.to_can(int(s))}')
        self.drive_msg.steering = Steering.to_can(int(s))

    def release_control(self) -> None:
        self.drive_msg.ctrl = 0

    def shutdown(self) -> None:
        self.release_control()
        self.periodic_update()

        time.sleep(0.2)
        self.transmitter.shutdown()
        time.sleep(0.2)
        self._bus.shutdown()

    def tx_check(self, rx_check: int) -> bool:
        if rx_check > self.check_msg.tx_check or self.check_msg.tx_check == 255:
            self.check_msg.set_tx_check(rx_check)
            return True
        return False

    @property
    def velocity(self) -> float:
        return self.data.velocity

    @velocity.setter
    def velocity(self, velocity: Union[int, float]) -> None:
        self.controller.target = velocity
        # self.drive_msg.velocity = Driving.to_can(int(velocity))

    @property
    def steering_angle(self) -> float:
        return self.data.steering_angle

    @steering_angle.setter
    def steering_angle(self, steering: Union[int, float]) -> None:
        self.drive_msg.steering = Steering.to_can(int(steering))

    @property
    def ebrake(self) -> bool:
        return self.check_msg.stop

    @ebrake.setter
    def ebrake(self, enabled: bool) -> None:
        self.check_msg.stop = enabled

    @property
    def gps_position(self):
        return gpsd.get_current().position()
コード例 #24
0
ファイル: switches.py プロジェクト: jdiller/switches
def _send_code(code):
    pi = pigpio.pi()
    tx = Transmitter(pi, PIN)
    tx.send(code)
    time.sleep(1)
    tx.cancel()
コード例 #25
0
ファイル: server.py プロジェクト: jzsiggy/py_uart_transfer
class Server:
  def __init__(self):
    self.message = bytes(0)
    self.transmitter = Transmitter(SERIAL)
    self.location = 'imgs/foto_nova.png'

  def set_location(self):
    # name = input('SPECIFY NAME TO SAVE FILE WITHOUT EXTENSION: ')
    name = 'foto_new2'
    while len(name) < 1:
      print('INVALID FILE NAME')
      name = input('SPECIFY NAME TO SAVE FILE WITHOUT EXTENSION: ')
    self.location = 'imgs/{}.png'.format(name)

  def send_confirmation(self):
    packet = Datagram()
    packet.set_head(
      message_type=3,
      message_id=1,
      num_payloads=0,
      payload_index=0,
      payload_size=0,
      error_type=0,
      restart_index=0
    )
    packet.set_EOP()
    self.transmitter.send(packet.get_datagram())

  def confirm_handshake(self):
    handshake_received = self.transmitter.receive(expected_type='handshake')
    print(handshake_received)
    while not handshake_received:
      print('HANDSHAKE NOT SENT BY CLIENT - LISTENING ON SERIAL PORT {}'.format(SERIAL))
      handshake_received = self.transmitter.receive(expected_type='handshake')
    print('HANDSHAKE RECEIVED')
    self.send_confirmation()
    print('HANDSHAKE CONFIRMED')

  def send_error(self):
    packet = Datagram()
    packet.set_head(
      message_type=0,
      message_id=1,
      num_payloads=0,
      payload_index=0,
      payload_size=0,
      error_type=0,
      restart_index=0
    )
    packet.set_EOP()
    self.transmitter.send(packet.get_datagram())

  def receive_packet(self):
    response = self.transmitter.receive(expected_type='data')
    if not response:
      return 0
    return response # response => tuple(payload, payload_index, num_packets)

  def receive_message(self):
    buffer = bytes()
    last_payload = 0
    while True:
      response = self.receive_packet()
      if not response:
        print('ENCOUNTERED ERROR RECEIVING DATA')
        self.send_error()
        break

      (payload, payload_index, num_packets) = response
      
      if payload_index != last_payload + 1:
        print('PAYLOAD OUT OF ORDER')
        self.send_error()
        break

      last_payload = payload_index

      buffer += payload
      self.send_confirmation()
      print('\n\n\n')
      print(buffer)
      print(payload_index, num_packets)
      print('\n\n\n')

      if payload_index == num_packets:
        break

    with open(self.location, 'wb') as f:
      f.write(buffer)

  def disable(self):
    self.transmitter.disable()
コード例 #26
0
ファイル: server.py プロジェクト: jzsiggy/py_uart_transfer
 def __init__(self):
   self.message = bytes(0)
   self.transmitter = Transmitter(SERIAL)
   self.location = 'imgs/foto_nova.png'
コード例 #27
0
ファイル: sendrecv_coding.py プロジェクト: matthewarkin/E40N
    # Print option summary:
    print 'Parameters in experiment:'
    print '\tSamples per bit:', opt.spb
    print '\tChannel type:', ('Audio' if not opt.bypass else 'Bypass')
    if opt.bypass:
        print '\t  Noise:', opt.noise, ' lag:', opt.lag, 'h: [', opt.h, ']'
    print '\tFrequency:', fc, 'Hz'
    print '\tHamming code n :', opt.cc_len
########################################################

    #instantiate and run the source block
    src = Source(opt.monotone, opt.fname)
    src_payload, databits = src.process()  

    # instantiate and run the transmitter block
    xmitter = Transmitter(fc, opt.samplerate, opt.one, opt.spb, opt.silence, opt.cc_len)
    coded_bits = xmitter.encode(databits)
    coded_bits_with_preamble = xmitter.add_preamble(coded_bits)
    samples = xmitter.bits_to_samples(coded_bits_with_preamble)
    mod_samples = xmitter.modulate(samples)

####################################    
    # create channel instance
    if opt.bypass:
        h = [float(x) for x in opt.h.split(' ')]
        channel = bch.BypassChannel(opt.noise, opt.lag, h)
    else:
        channel = ach.AudioChannel(opt.samplerate, opt.chunksize, opt.prefill)
        
    # transmit the samples, and retrieve samples back from the channel
    try:
コード例 #28
0
def start():
    get_arguments()

    # Transmitter.transmit returns the new size of a block
    new_block_size = Transmitter.transmit(parameter_dict[K], parameter_dict[F])

    # for T trials, repeat the simulation
    for i in range(parameter_dict[T]):
        # clear this trial's variables
        trials_time = 0
        trials_received_frames = 0
        trials_failed_frames = 0

        # Set the first seed for the simulation
        Simulator.set_seed(parameter_dict[TSeeds][i])

        while (trials_time <= parameter_dict[R]):
            trials_received_blocks = 0  # new frame
            trials_failed_blocks = 0  # new frame

            # set the number of blocks to be transmitted in this frame
            transmissions = parameter_dict[K]

            if (parameter_dict[K] == 0):
                transmissions = 1

            # For K blocks (or 1 if K == 0), simulate the transmission
            for j in range(transmissions):  # range starts at 0
                # frame_failure = 0 if block was transmitted successfully
                block_failure = handle_block(new_block_size, parameter_dict[E],
                                             parameter_dict[K])

                # record block success or failure
                if (block_failure > 0):
                    trials_failed_blocks += 1
                else:
                    trials_received_blocks += 1

            # set trials_time to number of bits and response overhead
            trials_time += (parameter_dict[F] +
                            (parameter_dict[K] * Transmitter.r) +
                            parameter_dict[A])
            # update number of transmitted frames
            Statistics.update(Statistics.total_frames)
            # frame failed, resend the frame
            if (trials_failed_blocks >= 1):
                trials_failed_frames += 1
            # the last frame being sent (no longer needed) see forums
            #elif(trials_time > parameter_dict[R]):
            #    pass
            # successful transmition
            else:
                Statistics.update(Statistics.correctly_received_frames)
                trials_received_frames += 1

        #a print("Trial number:", i)
        #a print("Received Frames", trials_received_frames)
        #a print("Failed Frames", trials_failed_frames)

        # Assume: Take all K*(F+r) trials_time units into account
        # even if in last frame
        Statistics.append(
            Statistics.throughput_averages,
            ((parameter_dict[F] * trials_received_frames) / trials_time))

        if (trials_received_frames != 0):
            # Assume: Take all frames into account, even last frame
            Statistics.append(Statistics.frame_averages,
                              (trials_received_frames + trials_failed_frames) /
                              trials_received_frames)
        else:
            Statistics.append(Statistics.frame_averages, 0)

        # Add to total time
        Statistics.statistics_dict[Statistics.total_time] += trials_time

    # Call Print Statements
    #a print()
    #a print("----------------------------------------------")
    print_input(sys.argv)
    Statistics.set_final_values(parameter_dict[F], parameter_dict[R])
    Statistics.print_frame_ci()
    Statistics.print_throughput_ci()
コード例 #29
0
    G_0 = np.array(
        [[(receivers[0].x - tran.x) / r1 - (receivers[1].x - tran.x) / r2,
          (receivers[0].y - tran.y) / r1 - (receivers[1].y - tran.y) / r2],
         [(receivers[0].x - tran.x) / r1 - (receivers[2].x - tran.x) / r3,
          (receivers[0].y - tran.y) / r1 - (receivers[2].y - tran.y) / r3]])

    Q_pinv = np.linalg.pinv(Q)

    crlb = np.linalg.pinv(G_0.transpose() @ Q_pinv @ G_0)

    return crlb


if __name__ == '__main__':
    transmitter = Transmitter([0, 0])

    crlbs = []

    for loc in range(5000, 1000, -100):
        receiver1 = Receiver([-loc, loc], is_center=True)
        receiver2 = Receiver([loc, loc], is_center=False)
        receiver3 = Receiver([loc, -loc], is_center=False)
        receivers = [receiver1, receiver2, receiver3]
        crlb = CRLB(receivers, transmitter)

        crlbs.append(np.sqrt(np.trace(crlb) / crlb.shape[0]))

    print(crlbs)
    plt.plot(crlbs)
    plt.show()
コード例 #30
0
from flask import Flask
from flask import render_template
from flask import redirect
from transmitter import Transmitter
from config import Config
app = Flask(__name__)
config = Config()
transmitter = Transmitter(config)


@app.route('/')
def index_pimator():
    return render_template('index.html',
                           codes=config.codes,
                           application_prefix=config.application_prefix)


@app.route('/outlet/<string:outlet>/<string:state>', methods=['POST'])
def apply_state_to_one_outlet(outlet, state):
    transmitter.apply_state_to_one_outlet(outlet, state)
    return redirect(config.application_prefix, code=302)


@app.route('/outlet/all/<string:state>', methods=['POST'])
def apply_state_to_all_outlets(state):
    transmitter.apply_state_to_all_outlets(state)
    return redirect(config.application_prefix, code=302)


# if __name__ == "__main__":
#     app.run(debug=True, host="0.0.0.0")
コード例 #31
0
#WARNING 'sagemath' required for linear_code.py to run.Run as 'sage main.py'

from sys import argv
from transmitter import Transmitter
from receiver import Receiver
from linear_code import LC
from random import randint

transmitter = Transmitter()
receiver = Receiver()

try:
    if (len(argv) > 1):
        filename = argv[1]
    else:
        filename = raw_input("Insert file name: ")

    try:
        P = list(
            input(
                "\n(Press ENTER to use a default [12, 3] linear code option)\nInsert P matrix as list of lists(rows): "
            ))
    except SyntaxError:
        P = [[0, 1, 1, 1, 0, 1, 0, 1, 0], [0, 0, 0, 1, 1, 1, 0, 1, 0],
             [1, 1, 0, 0, 0, 0, 0, 1, 1]]

    print(
        "Warning: Current code can correct up to {} errors per word!\n".format(
            LC.getErrorCorrectingCapability(P)))
    maxNoise = int(raw_input("Insert max noise per word: "))
コード例 #32
0
 def test_check_credentials_bogus(self):
     tt = Transmitter()
     tt.set_account(self.bogus_account)
     self.assertEquals(tt.check_credentials(), 'host not found') 
コード例 #33
0
ファイル: runner.py プロジェクト: oliverpaadik/kohvi_lora
def runner():

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "process",
        help="select whether the module acts as (t)ransmitter or (r)eceiver")
    parser.add_argument("-d",
                        "--debug",
                        help="turn on extra logging level",
                        action="store_true")
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(
            stream=sys.stdout,
            filemode="a",
            format=
            "%(asctime)s - %(module)-12s - %(levelname)-8s - %(message)s",
            datefmt="%d-%m-%Y %H:%M:%S",
            level=logging.DEBUG)
        logging.debug("Logging level set to DEBUG")
    else:
        # filename="/share/log.txt"
        logging.basicConfig(
            stream=sys.stdout,
            filemode="a",
            format=
            "%(asctime)s - %(module)-12s - %(levelname)-8s - %(message)s",
            datefmt="%d-%m-%Y %H:%M:%S",
            level=logging.INFO)

    if args.process == 't' or args.process == 'T':
        role = Role.transmitter
        logging.debug("Module acting as transmitter")
    elif args.process == 'r' or args.process == 'R':
        role = Role.receiver
        logging.debug("Module acting as receiver")
    else:
        print("Cannot parse the argument, use either 't/T' or 'r/R'")
        sys.exit(-1)

    if role == Role.receiver:
        lora = Receiver(verbose=False)

        try:
            print(lora)
            lora.start()
        except KeyboardInterrupt:
            sys.stdout.flush()
            sys.stderr.write("KeyboardInterrupt\n")
        finally:
            lora.stop()
            sys.stdout.flush()
            logging.debug("Exiting the program")

    elif role == Role.transmitter:
        lora = Transmitter(verbose=False)
        print(lora)
        lora.start()
        logging.debug("Stopping transmitter.")
        lora.stop()
コード例 #34
0
class ApiServer():
    def __init__(self):
        mainServerIP = globe.components.mainServerIp
        mainServerPort = globe.components.mainServerPort
        self.mainServerAddress = 'http://' + mainServerIP + ':' + mainServerPort

        # Starting receiver flask server process:
        print("Starting the receiver HTTP server...\n")

        self.serverThread = threading.Thread(target=initReceiver, args=())
        self.serverThread.start()
        time.sleep(1)

        self.transmitter = Transmitter(self.mainServerAddress)

        # Send the content of jsonPath to each devices:
        print("\nSending JSON paths to devices...")

        archAddress = globe.content[0][:-1]
        connMapAddress = globe.content[1][:-1]
        data = archAddress + '#' + connMapAddress

        for ip in globe.components.devicesIp:
            address = f'http://{ip}:8484/updateJsonPath'  # f for format

            response = requests.post(address, data)
            if globe.jupyterFlag == 0:
                print(response.ok, response.status_code)

        time.sleep(1)

    def getWorkersList(self):
        return globe.components.toString('w')

    def getRoutersList(self):
        return globe.components.toString('r')

    def getSourcesList(self):
        return globe.components.toString('s')

    def getTransmitter(self):
        return self.transmitter

    def stopServer(self):
        receiver.stop()
        return True

    def getQueueData(self):
        received = False

        while not received:
            if not multiProcQueue.empty():
                print("~New result has been created successfully~")
                multiProcQueue.get()  # Get the new result out of the queue
                received = True
            time.sleep(0.1)

    def train(self):
        self.transmitter.train()
        self.getQueueData()
        print('Training - Finished\n')
        return globe.trainResults[-1]

    def predict(self):
        self.transmitter.predict()
        self.getQueueData()
        print('Prediction - Finished\n')
        return globe.predictResults[-1]

    def statistics(self):
        self.transmitter.statistics()
コード例 #35
0
ファイル: server.py プロジェクト: cypressf/python_networks
from transmitter import Transmitter
from receiver import Receiver
import atexit

SEND_ADDRESS = "c"
RECEIVE_ADDRESS = "c"
MINIMUM_BLINK_TIME = 1000

if __name__ == '__main__':
	transmitter = Transmitter(minimum_blink_time = MINIMUM_BLINK_TIME, send_address = SEND_ADDRESS)
	receiver = Receiver(transmitter, minimum_blink_time = MINIMUM_BLINK_TIME, address = RECEIVE_ADDRESS)
	
	def cleanup():
		transmitter.cleanup()
		receiver.cleanup()
		GPIO.cleanup()

	atexit.register(cleanup)

	while True:
		message = input("message: ")
		transmitter.send(message)
コード例 #36
0
ファイル: main.py プロジェクト: Solanar/CMPUT313_Asn1
def start():
    get_arguments()

    # Transmitter.transmit returns the new size of a block
    new_block_size = Transmitter.transmit(parameter_dict[K],
                                          parameter_dict[F])

    # for T trials, repeat the simulation
    for i in range(parameter_dict[T]):
        # clear this trial's variables
        trials_time = 0
        trials_received_frames = 0
        trials_failed_frames = 0

        # Set the first seed for the simulation
        Simulator.set_seed(parameter_dict[TSeeds][i])

        while (trials_time <= parameter_dict[R]):
            trials_received_blocks = 0  # new frame
            trials_failed_blocks = 0    # new frame

            # set the number of blocks to be transmitted in this frame
            transmissions = parameter_dict[K]

            if (parameter_dict[K] == 0):
                transmissions = 1

            # For K blocks (or 1 if K == 0), simulate the transmission
            for j in range(transmissions):  # range starts at 0
                # frame_failure = 0 if block was transmitted successfully
                block_failure = handle_block(new_block_size,
                                             parameter_dict[E],
                                             parameter_dict[K])

                # record block success or failure
                if (block_failure > 0):
                    trials_failed_blocks += 1
                else:
                    trials_received_blocks += 1

            # set trials_time to number of bits and response overhead
            trials_time += (parameter_dict[F] +
                            (parameter_dict[K] * Transmitter.r)
                            + parameter_dict[A])
            # update number of transmitted frames
            Statistics.update(Statistics.total_frames)
            # frame failed, resend the frame
            if(trials_failed_blocks >= 1):
                trials_failed_frames += 1
            # the last frame being sent (no longer needed) see forums
            #elif(trials_time > parameter_dict[R]):
            #    pass
            # successful transmition
            else:
                Statistics.update(Statistics.correctly_received_frames)
                trials_received_frames += 1

        #a print("Trial number:", i)
        #a print("Received Frames", trials_received_frames)
        #a print("Failed Frames", trials_failed_frames)

        # Assume: Take all K*(F+r) trials_time units into account
        # even if in last frame
        Statistics.append(Statistics.throughput_averages,
                          ((parameter_dict[F] * trials_received_frames)
                           / trials_time))

        if(trials_received_frames != 0):
            # Assume: Take all frames into account, even last frame
            Statistics.append(Statistics.frame_averages,
                              (trials_received_frames + trials_failed_frames) /
                              trials_received_frames)
        else:
            Statistics.append(Statistics.frame_averages, 0)

        # Add to total time
        Statistics.statistics_dict[Statistics.total_time] += trials_time

    # Call Print Statements
    #a print()
    #a print("----------------------------------------------")
    print_input(sys.argv)
    Statistics.set_final_values(parameter_dict[F], parameter_dict[R])
    Statistics.print_frame_ci()
    Statistics.print_throughput_ci()
コード例 #37
0
import RPi.GPIO as GPIO
import dht11
import time
import datetime
from transmitter import Transmitter

# initialize GPIO
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)

# read data using pin 17
instance = dht11.DHT11(pin=17)

if __name__ == '__main__':
    channel = "/dev/rfcomm8"
    TR = Transmitter(channel)
    TR
    while True:
        result = instance.read()
        #print("waiting")
        if result.is_valid():
            date = "Last valid input: " + str(datetime.datetime.now())

            temp = "Temperature: %-3.1f C" % result.temperature
            humid = "Humidity: %-3.1f %%" % result.humidity
            TR.sendData(temp + "\n")
            TR.sendData(humid + "\n")
コード例 #38
0
ファイル: probe.py プロジェクト: jamesbtate/ping-server
from collector import Ping
from transmitter import Transmitter

output_queue = None


def enqueue_output(data):
    """ Accepts a dictionary containg send_time and replies[] """
    output_queue.put(data)
    print("enqueued output")


def dequeue_output():
    """ Pops a dictionary from the output queue """
    return output_queue.get()


def collector_run():
    hosts = ('192.168.5.5', '192.168.5.18', '8.8.8.8', 'ucla.edu')
    pinger = Ping(hosts, enqueue_output)
    pinger.run()


if __name__ == '__main__':
    output_queue = queue.Queue()
    collector_thread = threading.Thread(target=collector_run, name="collector")
    recorder_url = 'ws://localhost:8765/'
    transmitter = Transmitter(dequeue_output, recorder_url)
    collector_thread.start()
    transmitter.start()
コード例 #39
0
ファイル: missionctl.py プロジェクト: loetlab-jena/xplorer
else:
	logging.debug("MC running NOT on RPi")

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT) # status LED
GPIO.output(LED, GPIO.HIGH) # switch on to indicate software startup
GPIO.setup(RELEASE, GPIO.OUT) # release pin
GPIO.output(RELEASE, GPIO.LOW) # disable release
GPIO.setup(RELEASE_FB, GPIO.IN) # release feedback pin
GPIO.setup(HEADSHOT, GPIO.OUT) # set shutoff to output
GPIO.output(HEADSHOT, GPIO.LOW) # disable shutoff
GPIO.setup(CAMERA, GPIO.OUT) # set cam power to output
GPIO.output(CAMERA, GPIO.HIGH) # enable camera power

# setup the transmitter thread
txthread = Transmitter()
txthread.setDaemon(True)
txthread.start()

# setup the GPS-listener thread
gpsthread = GPSListener()
gpsthread.setDaemon(True)
gpsthread.start()

# wait for at least a 2D-Fix from the GPS
while GPSListener.fix < 2:
	pass
logging.info("MC GPS fix OK")

# indicate GPS fix on LED 
for i in range(1,15):
    # Print option summary:
    print 'Parameters in experiment:'
    print '\tSamples per bit:', opt.spb
    print '\tChannel type:', ('Audio' if not opt.bypass else 'Bypass')
    if opt.bypass:
        print '\t  Noise:', opt.noise, ' lag:', opt.lag, 'h: [', opt.h, ']'
    print '\tFrequency:', fc, 'Hz'
    print '\tHamming code n :', opt.cc_len
########################################################

    #instantiate and run the source block
    src = Source(opt.monotone, opt.fname)
    src_payload, databits = src.process()

    # instantiate and run the transmitter block
    xmitter = Transmitter(fc, opt.samplerate, opt.one, opt.spb, opt.silence, opt.cc_len)
    coded_bits = xmitter.encode(databits)
    coded_bits_with_preamble = xmitter.add_preamble(coded_bits)
    samples = xmitter.bits_to_samples(coded_bits_with_preamble)
    mod_samples = xmitter.modulate(samples)

####################################
    # create channel instance
    if opt.bypass:
        h = [float(x) for x in opt.h.split(' ')]
        channel = bch.BypassChannel(opt.noise, opt.lag, h)
    else:
        channel = ach.AudioChannel(opt.samplerate, opt.chunksize, opt.prefill)

    # transmit the samples, and retrieve samples back from the channel
    try:
コード例 #41
0
    # Print option summary:
    print 'Parameters in experiment:'
    print '\tSamples per bit:', opt.spb
    print '\tChannel type:', ('Audio' if not opt.bypass else 'Bypass')
    if opt.bypass:
        print '\t  Noise:', opt.noise, ' lag:', opt.lag, 'h: [', opt.h, ']'
    print '\tFrequency:', fc, 'Hz'

    ########################################################

    #instantiate and run the source block
    src = Source(opt.monotone, opt.fname)
    src_payload, databits = src.process()

    # instantiate and run the transmitter block
    xmitter = Transmitter(fc, opt.samplerate, opt.one, opt.spb, opt.silence)
    databits_with_preamble = xmitter.add_preamble(databits)
    samples = xmitter.bits_to_samples(databits_with_preamble)
    mod_samples = xmitter.modulate(samples)

    ####################################
    # create channel instance
    if opt.bypass:
        h = [float(x) for x in opt.h.split(' ')]
        channel = bch.BypassChannel(opt.noise, opt.lag, h)
    else:
        channel = ach.AudioChannel(opt.samplerate, opt.chunksize, opt.prefill)

    # transmit the samples, and retrieve samples back from the channel
    try:
        samples_rx = channel.xmit_and_recv(mod_samples)
コード例 #42
0
 def test_check_credentials_no_password(self):
     tt = Transmitter()
     tt.set_account(self.account_with_no_password)
     self.assertEquals(tt.check_credentials(), True) 
コード例 #43
0
ファイル: main.py プロジェクト: fangbei/email_robot
    logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S",
                    filename=filename,
                    filemode="w")
    console = logging.StreamHandler()
    console.setLevel(logging.NOTSET)
    formatter = logging.Formatter("%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s")
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

if __name__ == '__main__':
    InitLogging()
    handler = Handler()
    receiver = Receiver()
    transmitter = Transmitter()
    receiver.connect()

    td1 = threading.Thread(target=handler.run)
    td2 = threading.Thread(target=receiver.run)
    td3 = threading.Thread(target=transmitter.run)
    td1.start()
    td2.start()
    td3.start()

    # main loop
    while True:
        if handler.is_runing() and receiver.is_runing() and transmitter.is_runing():
            msg = receiver.fetch()
            while msg != None:
                handler.push(msg)
コード例 #44
0
 def test_check_credentials_bad_password(self):
     tt = Transmitter()
     tt.set_account(self.account_with_bad_password)
     self.assertEquals(tt.check_credentials(), 'username/password error') 
コード例 #45
0
from RgbLed import RgbLed
import serial
from time import sleep

from airbornedata import AirborneData
from transmitter import Transmitter

try:
    import struct
except ImportError:
    import ustruct as struct

# Data collection variables
sensor_name = "Construction Hallway"
sensor_id = 2
transmitter = Transmitter()
airborne_data_list = []
########################

# Setup LED
led = RgbLed(17, 27, 22)
########################

# Test LED
led.red()
sleep(.25)
led.green()
sleep(.25)
led.blue()
sleep(.25)
led.magenta()
コード例 #46
0
ファイル: sendrecv.py プロジェクト: wharvey92/ms3
    if opt.bypass:
        print '\t  Noise:', opt.noise, ' lag:', opt.lag, 'h: [', opt.h, ']'
    print '\tFrequency:', fc, 'Hz'

    print '\tSource coding:', ('On' if opt.compress else 'Off')
    print '\tChannel coding:', ('n = %d' % opt.cc_len if opt.cc_len!=0 else 'Off')
    print '\tEncryption:', ('On' if opt.encrypt else 'Off')

########################################################

    #instantiate and run the source block
    src = Source(opt.monotone, opt.fname, opt.compress, opt.encrypt)
    src_bits, src_payload, databits, pubkey = src.process()  
    
    # instantiate and run the transmitter block
    xmitter = Transmitter(fc, opt.samplerate, opt.one, opt.spb, opt.silence, opt.cc_len)
    if opt.cc_len!=0:
        databits = xmitter.encode(databits, opt.cc_len)
    databits_with_preamble = xmitter.add_preamble(databits)
    samples = xmitter.bits_to_samples(databits_with_preamble)
    mod_samples = xmitter.modulate(samples)

####################################    
    # create channel instance
    if opt.bypass:
        h = [float(x) for x in opt.h.split(' ')]
        channel = bch.BypassChannel(opt.noise, opt.lag, h)
        #channel_2 = ach.AudioChannel(opt.samplerate, opt.chunksize, opt.prefill)
    else:
        channel = ach.AudioChannel(opt.samplerate, opt.chunksize, opt.prefill)
        
コード例 #47
0
class AccountManager:

    DEFAULT_ACCOUNT_ID = 0

    def __init__(self):
        self.__transmitter = Transmitter()
        self.__configpath  = self.__set_configpath()
        self.__config      = self.__init_config()
        self.__default_account = AccountManager.get_default_account()
        self.__accounts    = []
        self.__load_accounts_from_config()

    def pass_transmitter(self):
        return self.__transmitter

    def reset_config(self):
        self.__accounts = []
        if os.path.exists(self.__configpath):
            os.remove(self.__configpath)
        self.__config = self.__init_config()

    def get_accounts(self):
        return [self.__default_account] + self.__accounts

    def add_new_account(self, account):
        self.__verify_account(account)
        self.__set_section_id_and_load_account(account)
        self.__add_account_to_config(account)

    def get_recent_account(self):
        id = self.get_recent_id()
        id = int(id)
        return self.get_account_by_id(id)

    def get_recent_id(self):
        id = self.__config.get('DEFAULT', 'last_profile')
        return int(id) 

    def get_account_by_id(self, id):
        self.__record_recent_account(id)
        if id == 0:
            account = self.__default_account
        else:
            account = self.__accounts[id - 1]
        self.__transmitter.set_account(account) 
        return  account
    
    def delete_account_by_id(self, id):
        offset_id = id - 1
        del self.__accounts[offset_id]
        self.__renumber_accounts()


    def __set_section_id_and_load_account(self, account):
        account.set_section_id(self.__next_id())
        self.__accounts.append(account)



    def __load_accounts_from_config(self):
        for section in self.__config.sections():
            section_id = self.__next_id()
            url = self.__config.get(section, 'url')
            username = self.__config.get(section, 'username')
            try:
                password = self.__config.get(section, 'password')
                if password == '': password = None
            except NoOptionError:
                password = None
            new_account = Account(url, username, password)
            new_account.set_section_id(section_id)
            self.__set_section_id_and_load_account(new_account)

    def __verify_account(self, account):
        self.__transmitter.set_account(account)
        self.__transmitter.check_credentials()

    def __next_id(self):
        return len(self.__accounts) + 1

    def __add_account_to_config(self, account):
        id = int(account.get_section_id()) # This will throw an exception if it's not a number
        id = str(id)
        try:
            self.__config.add_section(id)
        except DuplicateSectionError:
            # No need to add it if it's already there
            message = 'a ok'

        self.__config.set(id, 'url', account.get_url())
        self.__config.set(id, 'username', account.get_username())
        if account.get_password():
            self.__config.set(id, 'password', account.get_password())
        self.__save_config_to_file()

    def __save_config_to_file(self):
        with open(self.__configpath, 'wb') as handle: 
            self.__config.write(handle)

    def __record_recent_account(self, id):
        self.__config.set('DEFAULT', 'last_profile', str(id))
        self.__save_config_to_file()

    def __renumber_accounts(self):
        counter = 1
        renumbered_accounts = []
        for account in self.get_accounts():
            account.set_section_id(counter)
            counter += 1 
            renumbered_accounts.append(account)
        self.__accounts = renumbered_accounts
    def __init_config(self):
        config = ConfigParser.ConfigParser()
        if not os.path.exists(self.__configpath):
            # Set up initial config file
            config.set('DEFAULT', 'delay', '1.0') # wait while showing author info
            config.set('DEFAULT', 'cut_flag', '#! CUT MATERIAL') # we remove anything after this in the html
            config.set('DEFAULT', 'last_profile', '0') # use as default input option
            config.set('DEFAULT', 'next_section_n', '1') # next usable profile section number
            with open(self.__configpath, 'wb') as f: config.write(f)
        config.read(self.__configpath)
        return config


    def __set_configpath(self):
        # Determine which operating system is in use
        platform = sys.platform
        linux_relative_path = "~/.lyxblogger/config.cfg"
        try:
            relative_configpath = {'win32' : "~\\lyxblogger\\config.cfg", 
                              'darwin' : "~/.lyxblogger/config.cfg",
                              'linux2' : linux_relative_path,
                              'linux3' : linux_relative_path}[platform]
        except KeyError:
            raise SystemNotFoundError(platform)
        configpath = os.path.expanduser(relative_configpath)
        configdir = os.path.dirname(configpath)
        if not os.path.exists(configdir): os.makedirs(configdir)
        return configpath

    @classmethod
    def get_default_account(cls):
        # we are not going to set the id, because we never save this
        url = 'blogtest.letseatalready.com'
        username = '******'
        password = '******'
        default_account = Account(url, username, password)
        default_account.set_section_id(AccountManager.DEFAULT_ACCOUNT_ID)
        return default_account