def __init__(self, c_instance): self.__c_instance = c_instance self.__components = [] self.__main_display = MainDisplay(self) self.__components.append(self.__main_display) self.__main_display_controller = MainDisplayController(self, self.__main_display) self.__components.append(self.__main_display_controller) self.__time_display = TimeDisplay(self) self.__components.append(self.__time_display) self.__software_controller = SoftwareController(self) self.__components.append(self.__software_controller) self.__transport = Transport(self) self.__components.append(self.__transport) self.__channel_strips = [ ChannelStrip(self, i) for i in range(NUM_CHANNEL_STRIPS) ] for s in self.__channel_strips: self.__components.append(s) self.__master_strip = MasterChannelStrip(self) self.__components.append(self.__master_strip) self.__channel_strip_controller = ChannelStripController(self, self.__channel_strips, self.__master_strip, self.__main_display_controller) self.__components.append(self.__channel_strip_controller) self.__shift_is_pressed = False self.__option_is_pressed = False self.__ctrl_is_pressed = False self.__alt_is_pressed = False self.is_pro_version = False self._received_firmware_version = False self._refresh_state_next_time = 0
def __init__(self, src="", id="", loglevel=0, debug=0): self.ckin = 0 self._owner = 0 self.verbose = 1 fname = os.path.basename(src) ff = os.path.splitext(fname) if src: root = XML.XML_Node(name="doc", src=src, preprocess=1, debug=debug) if id: s = root.child(id=id) else: s = root.child(name="phase") self._name = s["id"] # initialize the equation of state ThermoPhase.__init__(self, xml_phase=s) # initialize the kinetics model ph = [self] Kinetics.__init__(self, xml_phase=s, phases=ph) # initialize the transport model Transport.__init__(self, xml_phase=s, phase=self, model="", loglevel=loglevel)
def __init__(self, src="", id="", loglevel=0, debug=0): self.ckin = 0 self._owner = 0 self.verbose = 1 fname = os.path.basename(src) ff = os.path.splitext(fname) if src: root = XML.XML_Node(name='doc', src=src, preprocess=1, debug=debug) if id: s = root.child(id=id) else: s = root.child(name="phase") self._name = s['id'] # initialize the equation of state ThermoPhase.__init__(self, xml_phase=s) # initialize the kinetics model ph = [self] Kinetics.__init__(self, xml_phase=s, phases=ph) # initialize the transport model Transport.__init__(self, xml_phase=s, phase=self, model='', loglevel=loglevel)
def __init__(self, c_instance): self._NanoKontrol__c_instance = c_instance self._NanoKontrol__current_track = self.song().view.selected_track self._NanoKontrol__current_device = self._NanoKontrol__current_track.view.selected_device self.song().add_tracks_listener(self._NanoKontrol__tracks_changed) self._NanoKontrol__transport_unit = Transport(self) self._NanoKontrol__encoder_unit = Encoders(self, True) self._NanoKontrol__slider_unit = SliderSection(self) self._NanoKontrol__pad_unit = Pads(self)
def __init__(self, id = 0, name = "test face", ip_address = None, node = None): """ id - this is the id of the face in the node name - this is the name of the face transport - this is the networking interface of this face """ self.__id = id self.__name = name self.__node = node self.__transport = Transport(ip_address = ip_address, face = self)
def connect(self): # 创建连接 self.robot = Transport(HOST, PORT) # 设置机器人信息反馈回调函数 self.robot.subscribe_speed(print_speed) self.robot.subscribe_pose(print_pose) # 启动连接 self.robot.connect() keep = threading.Thread(target=self.keep_connection, name='connection') keep.setDaemon(True) keep.start()
def test_Transport_MCNP(): """ Test the default object creation for MCNP input. """ # Read user input inputs = UserInputs(coeusInputPath=INPUTFNAME) inputs.read_inputs() # Read transport input (MCNP Example) trans = Transport(PATH + inputs.transInput) assert_equal(trans.transPath, PATH + "test_mcnp.inp") assert_equal(trans.code, "mcnp6") assert_equal( trans.sampVars, { 'h1': ' 1:5> decimal', 'h2': ' 1:5> decimal', 'h3': ' 1:5> decimal', 'h4': ' 1:5> decimal', 'h5': ' 1:5> decimal', 'h6': ' 1:5> decimal', 'd1': ' 1:3> integer', 'r1': ' 0.5:3> decimal', 'mat1': ' 1,2,3,4,5,6,7,8,9,10,11,12> material' }) assert_equal( trans.corrVars, { 'dens1': ' -2.7,-7.8,-6.5,-8.9,-7.3,-2.7,-16.6,-19.3,-18.7,-11.3,-1.16500e-09,101> mat1', 'nu1': ' 1,2,3,4,5,6,7,8,9,10,11,12> mat1' }) assert_equal( trans.transInput[0:78], "C ****************************************************************************" ) assert_equal(trans.transInput[-12:], "2.010000e+01")
def __init__(self, c_instance): self.__c_instance = c_instance self.__components = [] self.__main_display = MainDisplay(self) self.__components.append(self.__main_display) self.__main_display_controller = MainDisplayController(self, self.__main_display) self.__components.append(self.__main_display_controller) self.__time_display = TimeDisplay(self) self.__components.append(self.__time_display) self.__software_controller = SoftwareController(self) self.__components.append(self.__software_controller) self.__transport = Transport(self) self.__components.append(self.__transport) self.__channel_strips = [ ChannelStrip(self, i) for i in range(NUM_CHANNEL_STRIPS) ] for s in self.__channel_strips: self.__components.append(s) self.__master_strip = MasterChannelStrip(self) self.__components.append(self.__master_strip) self.__channel_strip_controller = ChannelStripController(self, self.__channel_strips, self.__master_strip, self.__main_display_controller) self.__components.append(self.__channel_strip_controller) self.__shift_is_pressed = False self.__option_is_pressed = False self.__ctrl_is_pressed = False self.__alt_is_pressed = False
def handle(self): # handle function must be overrided addr = self.client_address client = self.request log.i('%s connected' % str(addr)) transport = Transport(addr, client) transport.setDaemon(True) transport.start() while True: if not transport.check_status(): transport.shutdown() client.close() log.w('%s disconnected' % str(addr)) break sleep(self.__CHECK_CONNECTION_INTERVAL)
def openFile(self): """Funció per obrir el fitxer de transport per treballar""" fitxer = QtGui.QFileDialog.getOpenFileName(self, "Selecciona un fitxer de Transport", ".", "*.yaml") if not fitxer or fitxer == "": return self.trans = Transport.loadFile(str(fitxer)) self.loadStations() self.mF.setTrans(self.trans) self.a = AStar(self.trans) self.unLockForm()
def openFile(self): """Funció per obrir el fitxer de transport per treballar""" fitxer = QtGui.QFileDialog.getOpenFileName( self, "Selecciona un fitxer de Transport", ".", "*.yaml") if not fitxer or fitxer == "": return self.trans = Transport.loadFile(str(fitxer)) self.loadStations() self.mF.setTrans(self.trans) self.a = AStar(self.trans) self.unLockForm()
def __init__(self, transport=None): """ """ self.alive = True self.transport = transport # Default message flags byte, used if None is specified in method calls self.flags = 0 if transport == None: # use default transport logging.warn("MMP is using default transport") self.transport = Transport() # keep track of how many errors have occured self.errors_rx = 0 self.errors_timeout = 0 self.errors_log = 0 # keep track of how many messages and log strings have been received self.num_log = 0 self.num_msg = 0 # init reader thread self.reader = threading.Thread(target=self.readerThread) self.reader.start()
def __init__(self): if len(sys.argv) < 2: self.host = input("Enter host ip address: ") self.s = Transport() else: self.host = sys.argv[1]
print "./AStar.py fitxer idOrigen idDesti mode distanciaMaxima transbordsMaxims paradesMaximes tempsCaminantMaxim" print print "Els màxims son opcionals. Si es posen, han de ser un enter de -1 a 99 (on -1 és infinit)" print "En canvi, el maxim temps caminant va de 0 a 60, no pot ser infinit." print print "On mode és un enter:" print " 0 = Resposta sense tractar (objecte AStarList en text) " print " 1 = Llista simple python amb el camí òptim (ideal per jocs de proves)" print " 2 = Explicació llegible per humans (Human Readable) " print print "Per exemple: python AStar.py \"./lyon.yaml\" 13 10 0" print sys.exit() try: trans = Transport.loadFile(sys.argv[1]) except: print "Fitxer incorrecte" sys.exit() origen = trans.getStationByID(int(sys.argv[2])) if not origen: print "ID origen incorrecte" sys.exit() desti = trans.getStationByID(int(sys.argv[3])) if not origen: print "ID destí incorrecte" sys.exit() mode = int(sys.argv[4])
def create_instance(c_instance): return Transport(c_instance)
class MackieControl: """Main class that establishes the Mackie Control <-> Live interaction. It acts as a container/manager for all the Mackie Control sub-components like ChannelStrips, Displays and so on. Futher it is glued to Lives MidiRemoteScript C instance, which will forward some notifications to us, and lets us forward some requests that are needed beside the general Live API (see 'send_midi' or 'request_rebuild_midi_map'). """ def __init__(self, c_instance): self.__c_instance = c_instance self.__components = [] self.__main_display = MainDisplay(self) self.__components.append(self.__main_display) self.__main_display_controller = MainDisplayController(self, self.__main_display) self.__components.append(self.__main_display_controller) self.__time_display = TimeDisplay(self) self.__components.append(self.__time_display) self.__software_controller = SoftwareController(self) self.__components.append(self.__software_controller) self.__transport = Transport(self) self.__components.append(self.__transport) self.__channel_strips = [ ChannelStrip(self, i) for i in range(NUM_CHANNEL_STRIPS) ] for s in self.__channel_strips: self.__components.append(s) self.__master_strip = MasterChannelStrip(self) self.__components.append(self.__master_strip) self.__channel_strip_controller = ChannelStripController(self, self.__channel_strips, self.__master_strip, self.__main_display_controller) self.__components.append(self.__channel_strip_controller) self.__shift_is_pressed = False self.__option_is_pressed = False self.__ctrl_is_pressed = False self.__alt_is_pressed = False self.is_pro_version = False self._received_firmware_version = False self._refresh_state_next_time = 0 def disconnect(self): for c in self.__components: c.destroy() def connect_script_instances(self, instanciated_scripts): """Called by the Application as soon as all scripts are initialized. You can connect yourself to other running scripts here, as we do it connect the extension modules (MackieControlXTs). """ try: from MackieControlXT.MackieControlXT import MackieControlXT except: print 'failed to load the MackieControl XT script (might not be installed)' found_self = False right_extensions = [] left_extensions = [] for s in instanciated_scripts: if s is self: found_self = True elif isinstance(s, MackieControlXT): s.set_mackie_control_main(self) if found_self: right_extensions.append(s) else: left_extensions.append(s) raise found_self or AssertionError self.__main_display_controller.set_controller_extensions(left_extensions, right_extensions) self.__channel_strip_controller.set_controller_extensions(left_extensions, right_extensions) def request_firmware_version(self): if not self._received_firmware_version: self.send_midi((240, 0, 0, 102, SYSEX_DEVICE_TYPE, 19, 0, 247)) def application(self): """returns a reference to the application that we are running in""" return Live.Application.get_application() def song(self): """returns a reference to the Live Song that we do interact with""" return self.__c_instance.song() def handle(self): """returns a handle to the c_interface that is needed when forwarding MIDI events via the MIDI map """ return self.__c_instance.handle() def refresh_state(self): for c in self.__components: c.refresh_state() self.request_firmware_version() self._refresh_state_next_time = 30 def is_extension(self): return False def request_rebuild_midi_map(self): """ To be called from any components, as soon as their internal state changed in a way, that we do need to remap the mappings that are processed directly by the Live engine. Dont assume that the request will immediately result in a call to your build_midi_map function. For performance reasons this is only called once per GUI frame.""" self.__c_instance.request_rebuild_midi_map() def build_midi_map(self, midi_map_handle): """New MIDI mappings can only be set when the scripts 'build_midi_map' function is invoked by our C instance sibling. Its either invoked when we have requested it (see 'request_rebuild_midi_map' above) or when due to a change in Lives internal state, a rebuild is needed.""" for s in self.__channel_strips: s.build_midi_map(midi_map_handle) self.__master_strip.build_midi_map(midi_map_handle) for i in range(SID_FIRST, SID_LAST + 1): if i not in function_key_control_switch_ids: Live.MidiMap.forward_midi_note(self.handle(), midi_map_handle, 0, i) Live.MidiMap.forward_midi_cc(self.handle(), midi_map_handle, 0, JOG_WHEEL_CC_NO) def update_display(self): if self._refresh_state_next_time > 0: self._refresh_state_next_time -= 1 if self._refresh_state_next_time == 0: for c in self.__components: c.refresh_state() self.request_firmware_version() for c in self.__components: c.on_update_display_timer() def send_midi(self, midi_event_bytes): """Use this function to send MIDI events through Live to the _real_ MIDI devices that this script is assigned to.""" self.__c_instance.send_midi(midi_event_bytes) def receive_midi(self, midi_bytes): if midi_bytes[0] & 240 == NOTE_ON_STATUS or midi_bytes[0] & 240 == NOTE_OFF_STATUS: note = midi_bytes[1] value = BUTTON_PRESSED if midi_bytes[2] > 0 else BUTTON_RELEASED if note in range(SID_FIRST, SID_LAST + 1): if note in display_switch_ids: self.__handle_display_switch_ids(note, value) if note in channel_strip_switch_ids + fader_touch_switch_ids: for s in self.__channel_strips: s.handle_channel_strip_switch_ids(note, value) if note in channel_strip_control_switch_ids: self.__channel_strip_controller.handle_assignment_switch_ids(note, value) if note in function_key_control_switch_ids: self.__software_controller.handle_function_key_switch_ids(note, value) if note in software_controls_switch_ids: self.__software_controller.handle_software_controls_switch_ids(note, value) if note in transport_control_switch_ids: self.__transport.handle_transport_switch_ids(note, value) if note in marker_control_switch_ids: self.__transport.handle_marker_switch_ids(note, value) if note in jog_wheel_switch_ids: self.__transport.handle_jog_wheel_switch_ids(note, value) elif midi_bytes[0] & 240 == CC_STATUS: cc_no = midi_bytes[1] cc_value = midi_bytes[2] if cc_no == JOG_WHEEL_CC_NO: self.__transport.handle_jog_wheel_rotation(cc_value) elif cc_no in range(FID_PANNING_BASE, FID_PANNING_BASE + NUM_CHANNEL_STRIPS): for s in self.__channel_strips: s.handle_vpot_rotation(cc_no - FID_PANNING_BASE, cc_value) elif midi_bytes[0] == 240 and len(midi_bytes) == 12 and midi_bytes[5] == 20: version_bytes = midi_bytes[6:-2] major_version = version_bytes[1] self.is_pro_version = major_version > 50 self._received_firmware_version = True def can_lock_to_devices(self): return False def suggest_input_port(self): return '' def suggest_output_port(self): return '' def suggest_map_mode(self, cc_no, channel): result = Live.MidiMap.MapMode.absolute if cc_no in range(FID_PANNING_BASE, FID_PANNING_BASE + NUM_CHANNEL_STRIPS): result = Live.MidiMap.MapMode.relative_signed_bit return result def shift_is_pressed(self): return self.__shift_is_pressed def set_shift_is_pressed(self, pressed): self.__shift_is_pressed = pressed def option_is_pressed(self): return self.__option_is_pressed def set_option_is_pressed(self, pressed): self.__option_is_pressed = pressed def control_is_pressed(self): return self.__control_is_pressed def set_control_is_pressed(self, pressed): self.__control_is_pressed = pressed def alt_is_pressed(self): return self.__alt_is_pressed def set_alt_is_pressed(self, pressed): self.__alt_is_pressed = pressed def __handle_display_switch_ids(self, switch_id, value): if switch_id == SID_DISPLAY_NAME_VALUE: if value == BUTTON_PRESSED: self.__channel_strip_controller.toggle_meter_mode() elif switch_id == SID_DISPLAY_SMPTE_BEATS: if value == BUTTON_PRESSED: self.__time_display.toggle_mode()
class MMP: """ """ # byte indicating start of message MSG_SOM = '\1' MSG_STX = '\2' MSG_ETX = '\3' # string used to match logger strings LOGS = ' LOG' # max length of log string LOGS_MAX = 255 def __init__(self, transport=None): """ """ self.alive = True self.transport = transport # Default message flags byte, used if None is specified in method calls self.flags = 0 if transport == None: # use default transport logging.warn("MMP is using default transport") self.transport = Transport() # keep track of how many errors have occured self.errors_rx = 0 self.errors_timeout = 0 self.errors_log = 0 # keep track of how many messages and log strings have been received self.num_log = 0 self.num_msg = 0 # init reader thread self.reader = threading.Thread(target=self.readerThread) self.reader.start() def stop(self): """ """ self.alive = False def readByte(self): """ """ return self.transport.readByte() def write(self, databytes): """ """ self.transport.write(databytes) def nonHandledByte(self, byte): """ """ #print "nh: {:s}".format(byte); pass def logStrReceived(self, logStr): """ """ # don't print leading \t logging.info("MCU: " + logStr[1:]) def calcCS(self, intCS): return (256 - intCS) % 256 def handleMsg(self, msg): """ Called when a message is received. Expected to be overriden in subclasses. """ logging.info("PC RX: {}".format(msg)) def rebootMCU(self): """ Send MCU message telling it to reboot itself.""" self.sendMsg('r', flags=0x0) def sendMsg(self, msgData, flags=None): """ """ # use default flags if not specified as parameter if flags == None: flags = self.flags length = len(msgData) # make up header # checksum cs = length + flags m = pack('<cBBc', self.MSG_SOM, length, flags, self.MSG_STX) # add data for ch in msgData: m += pack('<c', ch) cs += ord(ch) cs = cs % 256 # pack ETX m += pack('<c', self.MSG_ETX) # pack CS # m += pack('<B', self.calcCS(cs)); m += pack('<B', cs) self.write(m) def readerThread(self): """ """ # states SIDLE = 0 SLOG = 1 SSTX = 2 SDATA = 3 SETX = 4 SLEN = 5 SCS = 6 SFLAGS = 7 logi = 0 state = SIDLE logstr = '' msg = MMPMsg() # checksum cs = 0 while self.alive: try: c = self.readByte() if (c != None and len(c) != 0): # char (python string) has been received, #if ( ord(c) >= 32 and ord(c)<=127): # a=c; #else: # a='_' #s="~0x{:02x}={}".format(ord(c),a); #print s, # --------------------------------- if state == SIDLE: if c == self.MSG_SOM: # got start byte logi = 0 state = SLEN msg = MMPMsg() logging.debug("-SOM-") else: if c == self.LOGS[logi]: # got a LOGS char logi += 1 if logi == len(self.LOGS): # Yup, this is a LOG string logstr = self.LOGS state = SLOG logi = 0 else: # nope, false alarm, char received was not start of message, not start of log string logi = 0 self.nonHandledByte(c) # --------------------------------- elif state == SLOG: # we're receiving a log msg if c == '\n': # this is end of log string self.num_log += 1 self.logStrReceived(logstr) state = SIDLE logstr = '' else: logstr = logstr + c if len(logstr) > self.LOGS_MAX: logging.warn( "log string is too long. Truncated: " + logstr + "\n") self.errors_log += 1 self.logStrReceived(logstr) state = SIDLE logstr = '' # --------------------------------- elif state == SLEN: # recived char is message length msg.len = ord(c) cs = msg.len logging.debug("-LEN-") state = SFLAGS elif state == SFLAGS: # recived char is message length msg.flags = ord(c) cs += ord(c) logging.debug("-FLAGS-") state = SSTX elif state == SSTX: if (c == self.MSG_STX): # got STX char as expected logging.debug("-STX-") state = SDATA else: # did not get SSTX char when expected logging.debug("!STX not seen!") self.errors_rx += 1 state = SIDLE elif state == SDATA: # we're receiving msg data. # XXX note: msg must contain at least one byte of data, ie no zero sized data is allowed here msg.data.extend(c) #logging.debug("d:"+c) cs += ord(c) msg.count += 1 if msg.count == msg.len: # that was the last of the data state = SETX elif state == SETX: if (c == self.MSG_ETX): # got ETX char as expected. logging.debug("-ETX-") state = SCS else: # did not get ETX char as expected self.errors_rx += 1 logging.debug("!ETX not seen!") elif state == SCS: if ord(c) == self.calcCS(cs): # checksum was valid, message is complete self.num_msg += 1 self.handleMsg(msg) else: # checksum was invalid self.errors_rx += 1 logging.debug( "!invalid checksum, expected: 0x{:x} got 0x{:x}" .format(self.calcCS(cs), ord(c))) state = SIDLE else: # timeout: no byte received if state != SIDLE: logging.debug("timeout") self.errors_timeout += 1 state = SIDLE pass except Exception, e: logging.error( "Caught exception in reader thread: {}".format(e))
class MackieControl: """Main class that establishes the Mackie Control <-> Live interaction. It acts as a container/manager for all the Mackie Control sub-components like ChannelStrips, Displays and so on. Futher it is glued to Lives MidiRemoteScript C instance, which will forward some notifications to us, and lets us forward some requests that are needed beside the general Live API (see 'send_midi' or 'request_rebuild_midi_map'). """ def __init__(self, c_instance): self.__c_instance = c_instance self.__components = [] self.__main_display = MainDisplay(self) self.__components.append(self.__main_display) self.__main_display_controller = MainDisplayController(self, self.__main_display) self.__components.append(self.__main_display_controller) self.__time_display = TimeDisplay(self) self.__components.append(self.__time_display) self.__software_controller = SoftwareController(self) self.__components.append(self.__software_controller) self.__transport = Transport(self) self.__components.append(self.__transport) self.__channel_strips = [ ChannelStrip(self, i) for i in range(NUM_CHANNEL_STRIPS) ] for s in self.__channel_strips: self.__components.append(s) self.__master_strip = MasterChannelStrip(self) self.__components.append(self.__master_strip) self.__channel_strip_controller = ChannelStripController(self, self.__channel_strips, self.__master_strip, self.__main_display_controller) self.__components.append(self.__channel_strip_controller) self.__shift_is_pressed = False self.__option_is_pressed = False self.__ctrl_is_pressed = False self.__alt_is_pressed = False def disconnect(self): for c in self.__components: c.destroy() def connect_script_instances(self, instanciated_scripts): """Called by the Application as soon as all scripts are initialized. You can connect yourself to other running scripts here, as we do it connect the extension modules (MackieControlXTs). """ try: from MackieControlXT.MackieControlXT import MackieControlXT except: print 'failed to load the MackieControl XT script (might not be installed)' found_self = False right_extensions = [] left_extensions = [] for s in instanciated_scripts: if s is self: found_self = True elif isinstance(s, MackieControlXT): s.set_mackie_control_main(self) if found_self: right_extensions.append(s) else: left_extensions.append(s) raise found_self or AssertionError self.__main_display_controller.set_controller_extensions(left_extensions, right_extensions) self.__channel_strip_controller.set_controller_extensions(left_extensions, right_extensions) def application(self): """returns a reference to the application that we are running in""" return Live.Application.get_application() def song(self): """returns a reference to the Live Song that we do interact with""" return self.__c_instance.song() def handle(self): """returns a handle to the c_interface that is needed when forwarding MIDI events via the MIDI map """ return self.__c_instance.handle() def refresh_state(self): for c in self.__components: c.refresh_state() def is_extension(self): return False def request_rebuild_midi_map(self): """ To be called from any components, as soon as their internal state changed in a way, that we do need to remap the mappings that are processed directly by the Live engine. Dont assume that the request will immediately result in a call to your build_midi_map function. For performance reasons this is only called once per GUI frame.""" self.__c_instance.request_rebuild_midi_map() def build_midi_map(self, midi_map_handle): """New MIDI mappings can only be set when the scripts 'build_midi_map' function is invoked by our C instance sibling. Its either invoked when we have requested it (see 'request_rebuild_midi_map' above) or when due to a change in Lives internal state, a rebuild is needed.""" for s in self.__channel_strips: s.build_midi_map(midi_map_handle) self.__master_strip.build_midi_map(midi_map_handle) for i in range(SID_FIRST, SID_LAST + 1): if i not in function_key_control_switch_ids: Live.MidiMap.forward_midi_note(self.handle(), midi_map_handle, 0, i) Live.MidiMap.forward_midi_cc(self.handle(), midi_map_handle, 0, JOG_WHEEL_CC_NO) def update_display(self): for c in self.__components: c.on_update_display_timer() def send_midi(self, midi_event_bytes): """Use this function to send MIDI events through Live to the _real_ MIDI devices that this script is assigned to.""" self.__c_instance.send_midi(midi_event_bytes) def receive_midi(self, midi_bytes): if midi_bytes[0] & 240 == NOTE_ON_STATUS or midi_bytes[0] & 240 == NOTE_OFF_STATUS: note = midi_bytes[1] value = BUTTON_PRESSED if midi_bytes[2] > 0 else BUTTON_RELEASED if note in range(SID_FIRST, SID_LAST + 1): if note in display_switch_ids: self.__handle_display_switch_ids(note, value) if note in channel_strip_switch_ids + fader_touch_switch_ids: for s in self.__channel_strips: s.handle_channel_strip_switch_ids(note, value) if note in channel_strip_control_switch_ids: self.__channel_strip_controller.handle_assignment_switch_ids(note, value) if note in function_key_control_switch_ids: self.__software_controller.handle_function_key_switch_ids(note, value) if note in software_controls_switch_ids: self.__software_controller.handle_software_controls_switch_ids(note, value) if note in transport_control_switch_ids: self.__transport.handle_transport_switch_ids(note, value) if note in marker_control_switch_ids: self.__transport.handle_marker_switch_ids(note, value) if note in jog_wheel_switch_ids: self.__transport.handle_jog_wheel_switch_ids(note, value) elif midi_bytes[0] & 240 == CC_STATUS: cc_no = midi_bytes[1] cc_value = midi_bytes[2] if cc_no == JOG_WHEEL_CC_NO: self.__transport.handle_jog_wheel_rotation(cc_value) elif cc_no in range(FID_PANNING_BASE, FID_PANNING_BASE + NUM_CHANNEL_STRIPS): for s in self.__channel_strips: s.handle_vpot_rotation(cc_no - FID_PANNING_BASE, cc_value) def can_lock_to_devices(self): return False def suggest_input_port(self): return '' def suggest_output_port(self): return '' def suggest_map_mode(self, cc_no, channel): result = Live.MidiMap.MapMode.absolute if cc_no in range(FID_PANNING_BASE, FID_PANNING_BASE + NUM_CHANNEL_STRIPS): result = Live.MidiMap.MapMode.relative_signed_bit return result def shift_is_pressed(self): return self.__shift_is_pressed def set_shift_is_pressed(self, pressed): self.__shift_is_pressed = pressed def option_is_pressed(self): return self.__option_is_pressed def set_option_is_pressed(self, pressed): self.__option_is_pressed = pressed def control_is_pressed(self): return self.__control_is_pressed def set_control_is_pressed(self, pressed): self.__control_is_pressed = pressed def alt_is_pressed(self): return self.__alt_is_pressed def set_alt_is_pressed(self, pressed): self.__alt_is_pressed = pressed def __handle_display_switch_ids(self, switch_id, value): if switch_id == SID_DISPLAY_NAME_VALUE: if value == BUTTON_PRESSED: self.__channel_strip_controller.toggle_meter_mode() elif switch_id == SID_DISPLAY_SMPTE_BEATS: if value == BUTTON_PRESSED: self.__time_display.toggle_mode()
def mostcalcs(self): ''' Get total latent and/or sensible and/or wastewater heat fluxes for domestic & industrial Assuming spatial units are already consistent and in shapefiles of identical projection :param qfConfig: :param qfParams: :param qfDataSources: :param disaggregated: :param outputFolder: :param logFolder: :return: ''' # Get partitioning and heat of combustion values partitions = Partitions(self.config, self.parameters) props = partitions.fluxProp # Proportion of possible fluxes (latent, wastewater, sensible based on what user selected) to include in results startDates = self.config.dt_start endDates = self.config.dt_end # Set up UTC time bins @ 30 min intervals for i in range(0, len(startDates), 1): bins = pd.date_range(pd.datetime.strptime( startDates[i].strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M') + timedelta(seconds=1800), pd.datetime.strptime( endDates[i].strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M'), tz='UTC', freq='30Min') if i == 0: timeBins = bins else: timeBins = timeBins.append(bins) # Make some aliases for the output layer for brevity outShp = self.ds.outputAreas_spat['shapefile'] outFeatIds = self.ds.outputAreas_spat['featureIds'] outEpsg = self.ds.outputAreas_spat['epsgCode'] # Populate temporal disaggregation objects # Building energy daily loadings (temporal disaggregation from Annual to daily) dailyE = DailyEnergyLoading( self.parameters.city, useUKholidays=self.parameters.useUKholidays) # Each component has 1..n data sources. Add each one, looping over them [dailyE.addLoadings(den['profileFile']) for den in self.ds.dailyEnergy] # Building energy diurnal cycles (temporal disaggregation from daily to half-hourly). These are provided in local time (London) diurnalE = EnergyProfiles( self.parameters.city, use_uk_holidays=self.parameters.useUKholidays, customHolidays=self.parameters.customHolidays) [diurnalE.addDomElec(de['profileFile']) for de in self.ds.diurnDomElec] [diurnalE.addDomGas(dg['profileFile']) for dg in self.ds.diurnDomGas] [diurnalE.addEconomy7(e7['profileFile']) for e7 in self.ds.diurnEco7] [diurnalE.addIndElec(ie['profileFile']) for ie in self.ds.diurnIndElec] [diurnalE.addIndGas(ig['profileFile']) for ig in self.ds.diurnIndGas] # Diurnal traffic patterns diurnalT = TransportProfiles( self.parameters.city, use_uk_holidays=self.parameters.useUKholidays, customHolidays=self.parameters.customHolidays) [ diurnalT.addProfiles(tr['profileFile']) for tr in self.ds.diurnalTraffic ] # Workday metabolism profile hap = HumanActivityProfiles( self.parameters.city, use_uk_holidays=self.parameters.useUKholidays, customHolidays=self.parameters.customHolidays) [hap.addProfiles(ha['profileFile']) for ha in self.ds.diurnMetab] pop = Population() pop.setOutputShapefile(outShp, outEpsg, outFeatIds) [ pop.injectResPop(rp['file'], makeUTC(rp['startDate']), rp['attribute'], rp['EPSG']) for rp in self.processedDataList['resPop'] ] [ pop.injectWorkPop(wp['file'], makeUTC(wp['startDate']), wp['attribute'], wp['EPSG']) for wp in self.processedDataList['workPop'] ] bldgEnergy = EnergyUseData() bldgEnergy.setOutputShapefile(outShp, outEpsg, outFeatIds) [ bldgEnergy.injectDomesticElec(rp['file'], makeUTC(rp['startDate']), rp['attribute'], rp['EPSG']) for rp in self.processedDataList['domElec'] ] [ bldgEnergy.injectDomesticGas(rp['file'], makeUTC(rp['startDate']), rp['attribute'], rp['EPSG']) for rp in self.processedDataList['domGas'] ] [ bldgEnergy.injectEconomy7Elec(rp['file'], makeUTC(rp['startDate']), rp['attribute'], rp['EPSG']) for rp in self.processedDataList['domEco7'] ] [ bldgEnergy.injectIndustrialElec(rp['file'], makeUTC(rp['startDate']), rp['attribute'], rp['EPSG']) for rp in self.processedDataList['indElec'] ] [ bldgEnergy.injectIndustrialGas(rp['file'], makeUTC(rp['startDate']), rp['attribute'], rp['EPSG']) for rp in self.processedDataList['indGas'] ] fc = FuelConsumption(self.ds.fuelConsumption[0]['profileFile']) trans = Transport(fc, self.parameters) trans.setOutputShapefile(outShp, outEpsg, outFeatIds) [ trans.injectFuelConsumption(rp['file'], makeUTC(rp['startDate']), rp['EPSG']) for rp in self.processedDataList['transport'] ] ds = None # Get daily factors df = DailyFact(self.parameters.useUKholidays) # Use UK holidays # Get area of each output feature, along with its identifier areas = (bldgEnergy.domGas.getOutputFeatureAreas()) for tb in timeBins: WH = QF(areas.index.tolist(), tb.to_pydatetime(), 1800, bldgEnergy, diurnalE, dailyE, pop, trans, diurnalT, hap, df, props, self.parameters.heatOfCombustion) # Write out the full time step to a file WH.to_csv(os.path.join(self.modelOutputPath, tb.strftime(self.dateStructure)), index_label='featureId') # Write log files to disk for traceability bldgEnergy.logger.writeFile( os.path.join(self.logPath, 'EnergyUseSpatial.txt')) pop.logger.writeFile( os.path.join(self.logPath, 'PopulationSpatial.txt')) trans.logger.writeFile( os.path.join(self.logPath, 'transportSpatial.txt')) hap.logger.writeFile( os.path.join(self.logPath, 'humanActivityProfiles.txt')) diurnalT.logger.writeFile( os.path.join(self.logPath, 'diurnalTransport.txt')) dailyE.logger.writeFile(os.path.join(self.logPath, 'dailyEnergy.txt'))
def __init__(self, EPS, SIG, DIP, POL, ZROT, locator=None): Transport.__init__(self, EPS, SIG, DIP, POL, ZROT, locator) self.parameters = [] return
class NanoKontrol: __module__ = __name__ __doc__ = ' A controller script for the Korg NanoKontrol ' def __init__(self, c_instance): self._NanoKontrol__c_instance = c_instance self._NanoKontrol__current_track = self.song().view.selected_track self._NanoKontrol__current_device = self._NanoKontrol__current_track.view.selected_device self.song().add_tracks_listener(self._NanoKontrol__tracks_changed) self._NanoKontrol__transport_unit = Transport(self) self._NanoKontrol__encoder_unit = Encoders(self, True) self._NanoKontrol__slider_unit = SliderSection(self) self._NanoKontrol__pad_unit = Pads(self) def application(self): """returns a reference to the application that we are running in """ return Live.Application.get_application() def song(self): """returns a reference to the Live song instance that we do control """ return self._NanoKontrol__c_instance.song() def disconnect(self): """Live -> Script Called right before we get disconnected from Live. """ self.song().remove_tracks_listener(self._NanoKontrol__tracks_changed) def can_lock_to_devices(self): return True def suggest_input_port(self): """Live -> Script Live can ask the script for an input port name to find a suitable one. """ return str('USB NanoKontrol') def suggest_output_port(self): """Live -> Script Live can ask the script for an output port name to find a suitable one. """ return str('USB NanoKontrol') def suggest_map_mode(self, cc_no, channel): """Live -> Script Live can ask the script for a suitable mapping mode for a given CC. """ suggested_map_mode = Live.MidiMap.MapMode.absolute return suggested_map_mode def show_message(self, message): self._NanoKontrol__c_instance.show_message(message) def connect_script_instances(self, instanciated_scripts): """Called by the Application as soon as all scripts are initialized. You can connect yourself to other running scripts here, as we do it connect the extension modules (MackieControlXTs). """ pass def request_rebuild_midi_map(self): """Script -> Live When the internal MIDI controller has changed in a way that you need to rebuild the MIDI mappings, request a rebuild by calling this function This is processed as a request, to be sure that its not too often called, because its time-critical. """ self._NanoKontrol__c_instance.request_rebuild_midi_map() def send_midi(self, midi_event_bytes): """Script -> Live Use this function to send MIDI events through Live to the _real_ MIDI devices that this script is assigned to. """ self._NanoKontrol__c_instance.send_midi(midi_event_bytes) def refresh_state(self): """Live -> Script Send out MIDI to completely update the attached MIDI controller. Will be called when requested by the user, after for example having reconnected the MIDI cables... """ pass def build_midi_map(self, midi_map_handle): """Live -> Script Build DeviceParameter Mappings, that are processed in Audio time, or forward MIDI messages explicitly to our receive_midi_functions. Which means that when you are not forwarding MIDI, nor mapping parameters, you will never get any MIDI messages at all. """ print 'Midi Map reloaded' script_handle = self._NanoKontrol__c_instance.handle() self._NanoKontrol__transport_unit.build_midi_map( script_handle, midi_map_handle) self._NanoKontrol__encoder_unit.build_midi_map(script_handle, midi_map_handle) self._NanoKontrol__slider_unit.build_midi_map(script_handle, midi_map_handle) self._NanoKontrol__pad_unit.build_midi_map(script_handle, midi_map_handle) def update_display(self): """Live -> Script Aka on_timer. Called every 100 ms and should be used to update display relevant parts of the controller """ if self._NanoKontrol__transport_unit: self._NanoKontrol__transport_unit.refresh_state() def receive_midi(self, midi_bytes): """Live -> Script MIDI messages are only received through this function, when explicitly forwarded in 'build_midi_map'. """ if ((midi_bytes[0] & 240) == CC_STATUS): channel = (midi_bytes[0] & 15) cc_no = midi_bytes[1] cc_value = midi_bytes[2] if (list(NANOKONTROL_TRANSPORT).count(cc_no) > 0): self._NanoKontrol__transport_unit.receive_midi_cc( cc_no, cc_value) elif (list(NANOKONTROL_BUTTONS).count(cc_no) > 0): self._NanoKontrol__slider_unit.receive_midi_cc( cc_no, cc_value, channel) elif (list(NANOKONTROL_ENCODERS).count(cc_no) > 0): self._NanoKontrol__encoder_unit.receive_midi_cc( cc_no, cc_value, channel) elif (list(NANOKONTROL_PADS).count(cc_no) > 0): self._NanoKontrol__pad_unit.receive_midi_cc( cc_no, cc_value, channel) elif (midi_bytes[0] == 240): pass def lock_to_device(self, device): self._NanoKontrol__encoder_unit.lock_to_device(device) def unlock_from_device(self, device): self._NanoKontrol__encoder_unit.unlock_from_device(device) def set_appointed_device(self, device): self._NanoKontrol__encoder_unit.set_appointed_device(device) def __tracks_changed(self): self.request_rebuild_midi_map() def bank_changed(self, new_bank): if self._NanoKontrol__encoder_unit.set_bank(new_bank): self.request_rebuild_midi_map() def restore_bank(self, bank): self._NanoKontrol__encoder_unit.restore_bank(bank) self.request_rebuild_midi_map() def instance_identifier(self): return self._NanoKontrol__c_instance.instance_identifier()
def disaggregate(qfDataSources, qfParams, outputFolder): ''' Function that performs all spatial disaggregation of GreaterQF inputs, and writes to output files. Returns dict of information that amounts to a new data sources file :param qfDataSources: GreaterQF Data sources object (contains locations and metadata regarding sharefiles) :param qfParams: GreaterQF config object (contains assumptions where these are needed) :param outputFolder: string path to folder in which to store disaggregated shapefiles :return: dict of {dataName:{shapefileName, startDate, field(s)ToUse} ''' returnDict = {} outShp = qfDataSources.outputAreas_spat['shapefile'] outFeatIds = qfDataSources.outputAreas_spat['featureIds'] outEpsg = qfDataSources.outputAreas_spat['epsgCode'] pop = Population() pop.setOutputShapefile(outShp, outEpsg, outFeatIds) # Population data (may be the same as that used for disaggregation, but still needs specifying explicitly) # These get used to disaggregate energy, so population must be completely populated first # Raw residential population data: disaggregate and save returnDict['resPop'] = [] returnDict['workPop'] = [] returnDict['indElec'] = [] returnDict['indGas'] = [] returnDict['domElec'] = [] returnDict['domGas'] = [] returnDict['domEco7'] = [] returnDict['transport'] = [] for rp in qfDataSources.resPop_spat: pop.setResPop(rp['shapefile'], startTime=makeUTC(rp['startDate']), attributeToUse=rp['attribToUse'], inputFieldId=rp['featureIds'], weight_by=None, epsgCode=rp['epsgCode']) outFile = os.path.join( outputFolder, 'resPop_starting' + rp['startDate'].strftime('%Y-%m-%d') + '.shp') (ds, attrib) = pop.getResPopLayer(makeUTC(rp['startDate'])) saveLayerToFile(ds, outFile, pop.getOutputLayer().crs(), 'Res pop scaled') returnDict['resPop'].append({ 'file': outFile, 'EPSG': rp['epsgCode'], 'startDate': rp['startDate'], 'attribute': attrib, 'featureIds': outFeatIds }) # Raw residential population data: disaggregate and save for wp in qfDataSources.workPop_spat: pop.setWorkPop(wp['shapefile'], startTime=makeUTC(wp['startDate']), attributeToUse=wp['attribToUse'], inputFieldId=wp['featureIds'], weight_by=None, epsgCode=wp['epsgCode']) outFile = os.path.join( outputFolder, 'WorkPop_starting' + wp['startDate'].strftime('%Y-%m-%d') + '.shp') (ds, attrib) = pop.getWorkPopLayer(makeUTC(wp['startDate'])) saveLayerToFile(ds, outFile, pop.getOutputLayer().crs(), 'Work pop scaled') returnDict['workPop'].append({ 'file': outFile, 'EPSG': wp['epsgCode'], 'startDate': wp['startDate'], 'attribute': attrib, 'featureIds': outFeatIds }) # Set up building energy use data: total energy use for each area. bldgEnergy = EnergyUseData() # Industrial electricity, downscaled by workplace population for ie in qfDataSources.indElec_spat: (workpop, workpopattrib) = pop.getWorkPopLayer( makeUTC(ie['startDate']) ) # Note: Population data is used for the output features. This means that population changing over time has to be incorporated bldgEnergy.setOutputShapefile( workpop, workpop.dataProvider().crs().authid().split(':')[1], outFeatIds) bldgEnergy.setIndustrialElec(ie['shapefile'], startTime=makeUTC(ie['startDate']), attributeToUse=ie['attribToUse'], inputFieldId=ie['featureIds'], weight_by=workpopattrib, epsgCode=ie['epsgCode']) (ds, attrib) = bldgEnergy.getIndustrialElecLayer(makeUTC(ie['startDate'])) outFile = os.path.join( outputFolder, 'IndElec_starting' + ie['startDate'].strftime('%Y-%m-%d') + '.shp') saveLayerToFile(ds, outFile, bldgEnergy.getOutputLayer().crs(), 'ind elec gas downscaled') returnDict['indElec'].append({ 'file': outFile, 'EPSG': ie['epsgCode'], 'startDate': ie['startDate'], 'attribute': attrib, 'featureIds': outFeatIds }) # Industrial gas for ig in qfDataSources.indGas_spat: (output, workpopattrib) = pop.getWorkPopLayer(makeUTC( ig['startDate'])) # Disaggregate by workplace pop bldgEnergy.setOutputShapefile( output, output.dataProvider().crs().authid().split(':')[1], outFeatIds) bldgEnergy.setIndustrialGas(ig['shapefile'], startTime=makeUTC(ig['startDate']), attributeToUse=ig['attribToUse'], inputFieldId=ig['featureIds'], weight_by=workpopattrib, epsgCode=ig['epsgCode']) outFile = os.path.join( outputFolder, 'IndGas_starting' + ig['startDate'].strftime('%Y-%m-%d') + '.shp') (ds, attrib) = bldgEnergy.getIndustrialGasLayer(makeUTC(ie['startDate'])) saveLayerToFile(ds, outFile, bldgEnergy.getOutputLayer().crs(), 'ind gas downscaled') returnDict['indGas'].append({ 'file': outFile, 'EPSG': ig['epsgCode'], 'startDate': ig['startDate'], 'attribute': attrib, 'featureIds': outFeatIds }) # Domestic gas for dg in qfDataSources.domGas_spat: (output, respopattrib) = pop.getResPopLayer(makeUTC( dg['startDate'])) # Disaggregate by residential pop bldgEnergy.setOutputShapefile( output, output.dataProvider().crs().authid().split(':')[1], outFeatIds) bldgEnergy.setDomesticGas(dg['shapefile'], startTime=makeUTC(dg['startDate']), attributeToUse=dg['attribToUse'], inputFieldId=dg['featureIds'], weight_by=respopattrib, epsgCode=dg['epsgCode']) outFile = os.path.join( outputFolder, 'DomGas_starting' + dg['startDate'].strftime('%Y-%m-%d') + '.shp') (ds, attrib) = bldgEnergy.getDomesticGasLayer(makeUTC(ie['startDate'])) saveLayerToFile(ds, outFile, bldgEnergy.getOutputLayer().crs(), 'dom gas downscaled') returnDict['domGas'].append({ 'file': outFile, 'EPSG': dg['epsgCode'], 'startDate': dg['startDate'], 'attribute': attrib, 'featureIds': outFeatIds }) # Domestic elec for de in qfDataSources.domElec_spat: (output, respopattrib) = pop.getResPopLayer(makeUTC( dg['startDate'])) # Disaggregate by residential pop if type(respopattrib) is list: respopattrib = respopattrib[0] bldgEnergy.setOutputShapefile( output, output.dataProvider().crs().authid().split(':')[1], outFeatIds) bldgEnergy.setDomesticElec(de['shapefile'], startTime=makeUTC(de['startDate']), attributeToUse=de['attribToUse'], inputFieldId=de['featureIds'], weight_by=respopattrib, epsgCode=de['epsgCode']) outFile = os.path.join( outputFolder, 'DomElec_starting' + de['startDate'].strftime('%Y-%m-%d') + '.shp') (ds, attrib) = bldgEnergy.getDomesticElecLayer(makeUTC(ie['startDate'])) saveLayerToFile(ds, outFile, bldgEnergy.getOutputLayer().crs(), 'dom elec downscaled') returnDict['domElec'].append({ 'file': outFile, 'EPSG': de['epsgCode'], 'startDate': de['startDate'], 'attribute': attrib, 'featureIds': outFeatIds }) # Domestic elec economy 7 for e7 in qfDataSources.eco7_spat: (output, respopattrib) = pop.getResPopLayer(makeUTC( e7['startDate'])) # Disaggregate by residential pop if type(respopattrib) is list: respopattrib = respopattrib[0] bldgEnergy.setOutputShapefile( output, output.dataProvider().crs().authid().split(':')[1], outFeatIds) bldgEnergy.setEconomy7Elec(e7['shapefile'], startTime=makeUTC(e7['startDate']), attributeToUse=e7['attribToUse'], inputFieldId=e7['featureIds'], weight_by=respopattrib, epsgCode=e7['epsgCode']) outFile = os.path.join( outputFolder, 'Eco7_starting' + e7['startDate'].strftime('%Y-%m-%d') + '.shp') (ds, attrib) = bldgEnergy.getEconomy7ElecLayer(makeUTC(ie['startDate'])) saveLayerToFile(ds, outFile, bldgEnergy.getOutputLayer().crs(), 'Economy 7 downscaled') returnDict['domEco7'].append({ 'file': outFile, 'EPSG': e7['epsgCode'], 'startDate': e7['startDate'], 'attribute': attrib, 'featureIds': outFeatIds }) # Set up transport fuel consumption in each output area fc = FuelConsumption(qfDataSources.fuelConsumption[0]['profileFile']) t = Transport(fc, qfParams) t.setOutputShapefile(outShp, outEpsg, outFeatIds) for tr in qfDataSources.transport_spat: sf = t.addTransportData(shapefile=tr['shapefile'], startTime=makeUTC(tr['startDate']), epsgCode=tr['epsgCode'], roadTypeField=tr['class_field'], roadTypeNames=tr['road_types'], speedConversionFactor=tr['speed_multiplier'], inputIdField=tr['featureIds'], totalAADTField=tr['AADT_total'], vAADTFields=tr['AADT_fields'], speedDataField=tr['speed_field']) outFile = os.path.join( outputFolder, 'DailyFuelUse_starting' + tr['startDate'].strftime('%Y-%m-%d') + '.shp') saveLayerToFile(sf, outFile, bldgEnergy.getOutputLayer().crs(), 'Fuel use daily') returnDict['transport'].append({ 'file': outFile, 'EPSG': tr['epsgCode'], 'startDate': tr['startDate'], 'featureIds': outFeatIds }) # Pickle the dictionary as a manifest file with open(os.path.join(outputFolder, 'MANIFEST'), 'wb') as outpickle: pickle.dump(returnDict, outpickle) # Return the output folder containing all this stuff return outputFolder
"""Tests transport framework""" from REST import REST from Transport import Transport TRANSPORT = Transport(debug=True) # HTTP Code tests def test_defined_response(): """Test HTTP expected response""" assert TRANSPORT.check_http_response(200, 200) is True def test_bad_response(): """Tests unexpected response is returns as False""" assert TRANSPORT.check_http_response(999) is False def test_good_http_responses(): """Checks good responses are True""" demo_api = REST(url='postman-echo.com') for code in (200, 201, 204): assert TRANSPORT.check_http_response( demo_api.get("/status/%i" % code).status_code) is True def test_bad_http_responses(): """Checks good responses are False""" demo_api = REST(url='postman-echo.com') for code in (400, 401, 403, 404, 422): assert TRANSPORT.check_http_response(
#coding=utf-8 ''' demo ''' from __future__ import print_function from Transport import Transport from Config import HOST, PORT def print_speed(speed): print(u'[机器人速度] x:', speed[0], ' y:', speed[1], ' w:', speed[2]) def print_pose(pose): print(u'[机器人位置] x:', pose[0], ' y:', pose[1], ' yaw:', pose[2]) if __name__ == "__main__": # 创建连接 robot = Transport(HOST, PORT) # 设置机器人信息反馈回调函数 robot.subscribe_speed(print_speed) robot.subscribe_pose(print_pose) # 启动连接 robot.connect() # 保持连接 robot.keep_alive(5)
class NanoKontrol: __module__ = __name__ __doc__ = ' A controller script for the Korg NanoKontrol ' def __init__(self, c_instance): self._NanoKontrol__c_instance = c_instance self._NanoKontrol__current_track = self.song().view.selected_track self._NanoKontrol__current_device = self._NanoKontrol__current_track.view.selected_device self.song().add_tracks_listener(self._NanoKontrol__tracks_changed) self._NanoKontrol__transport_unit = Transport(self) self._NanoKontrol__encoder_unit = Encoders(self, True) self._NanoKontrol__slider_unit = SliderSection(self) self._NanoKontrol__pad_unit = Pads(self) def application(self): """returns a reference to the application that we are running in """ return Live.Application.get_application() def song(self): """returns a reference to the Live song instance that we do control """ return self._NanoKontrol__c_instance.song() def disconnect(self): """Live -> Script Called right before we get disconnected from Live. """ self.song().remove_tracks_listener(self._NanoKontrol__tracks_changed) def can_lock_to_devices(self): return True def suggest_input_port(self): """Live -> Script Live can ask the script for an input port name to find a suitable one. """ return str('USB NanoKontrol') def suggest_output_port(self): """Live -> Script Live can ask the script for an output port name to find a suitable one. """ return str('USB NanoKontrol') def suggest_map_mode(self, cc_no, channel): """Live -> Script Live can ask the script for a suitable mapping mode for a given CC. """ suggested_map_mode = Live.MidiMap.MapMode.absolute return suggested_map_mode def show_message(self, message): self._NanoKontrol__c_instance.show_message(message) def connect_script_instances(self, instanciated_scripts): """Called by the Application as soon as all scripts are initialized. You can connect yourself to other running scripts here, as we do it connect the extension modules (MackieControlXTs). """ pass def request_rebuild_midi_map(self): """Script -> Live When the internal MIDI controller has changed in a way that you need to rebuild the MIDI mappings, request a rebuild by calling this function This is processed as a request, to be sure that its not too often called, because its time-critical. """ self._NanoKontrol__c_instance.request_rebuild_midi_map() def send_midi(self, midi_event_bytes): """Script -> Live Use this function to send MIDI events through Live to the _real_ MIDI devices that this script is assigned to. """ self._NanoKontrol__c_instance.send_midi(midi_event_bytes) def refresh_state(self): """Live -> Script Send out MIDI to completely update the attached MIDI controller. Will be called when requested by the user, after for example having reconnected the MIDI cables... """ pass def build_midi_map(self, midi_map_handle): """Live -> Script Build DeviceParameter Mappings, that are processed in Audio time, or forward MIDI messages explicitly to our receive_midi_functions. Which means that when you are not forwarding MIDI, nor mapping parameters, you will never get any MIDI messages at all. """ print 'Midi Map reloaded' script_handle = self._NanoKontrol__c_instance.handle() self._NanoKontrol__transport_unit.build_midi_map(script_handle, midi_map_handle) self._NanoKontrol__encoder_unit.build_midi_map(script_handle, midi_map_handle) self._NanoKontrol__slider_unit.build_midi_map(script_handle, midi_map_handle) self._NanoKontrol__pad_unit.build_midi_map(script_handle, midi_map_handle) def update_display(self): """Live -> Script Aka on_timer. Called every 100 ms and should be used to update display relevant parts of the controller """ if self._NanoKontrol__transport_unit: self._NanoKontrol__transport_unit.refresh_state() def receive_midi(self, midi_bytes): """Live -> Script MIDI messages are only received through this function, when explicitly forwarded in 'build_midi_map'. """ if ((midi_bytes[0] & 240) == CC_STATUS): channel = (midi_bytes[0] & 15) cc_no = midi_bytes[1] cc_value = midi_bytes[2] if (list(NANOKONTROL_TRANSPORT).count(cc_no) > 0): self._NanoKontrol__transport_unit.receive_midi_cc(cc_no, cc_value) elif (list(NANOKONTROL_BUTTONS).count(cc_no) > 0): self._NanoKontrol__slider_unit.receive_midi_cc(cc_no, cc_value, channel) elif (list(NANOKONTROL_ENCODERS).count(cc_no) > 0): self._NanoKontrol__encoder_unit.receive_midi_cc(cc_no, cc_value, channel) elif (list(NANOKONTROL_PADS).count(cc_no) > 0): self._NanoKontrol__pad_unit.receive_midi_cc(cc_no, cc_value, channel) elif (midi_bytes[0] == 240): pass def lock_to_device(self, device): self._NanoKontrol__encoder_unit.lock_to_device(device) def unlock_from_device(self, device): self._NanoKontrol__encoder_unit.unlock_from_device(device) def set_appointed_device(self, device): self._NanoKontrol__encoder_unit.set_appointed_device(device) def __tracks_changed(self): self.request_rebuild_midi_map() def bank_changed(self, new_bank): if self._NanoKontrol__encoder_unit.set_bank(new_bank): self.request_rebuild_midi_map() def restore_bank(self, bank): self._NanoKontrol__encoder_unit.restore_bank(bank) self.request_rebuild_midi_map() def instance_identifier(self): return self._NanoKontrol__c_instance.instance_identifier()
def __del__(self): Transport.__del__(self) Kinetics.__del__(self) ThermoPhase.__del__(self)
class MainFrame(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.root = master self.createPage() def createPage(self): Button(self, text='连接', command=self.connect).grid(row=0, sticky=W, pady=10) Label(self, text='vx:').grid(row=1, sticky=E) Label(self, text='vy:').grid(row=2, sticky=E) Label(self, text='vw:').grid(row=3, sticky=E) self.entry_vx = Entry(self) self.entry_vy = Entry(self) self.entry_vw = Entry(self) self.entry_vx.grid(row=1, column=1) self.entry_vy.grid(row=2, column=1) self.entry_vw.grid(row=3, column=1) self.entry_vx.insert(0, '0') self.entry_vy.insert(0, '0') self.entry_vw.insert(0, '0') Button(self, text='设置速度', command=self.set_speed).grid(row=4, column=3, sticky=W, pady=10) Label(self, text='x:').grid(row=5, sticky=E) Label(self, text='y:').grid(row=6, sticky=E) Label(self, text='yaw:').grid(row=7, sticky=E) self.entry_x = Entry(self) self.entry_y = Entry(self) self.entry_yaw = Entry(self) self.entry_x.grid(row=5, column=1) self.entry_y.grid(row=6, column=1) self.entry_yaw.grid(row=7, column=1) self.entry_x.insert(0, '0') self.entry_y.insert(0, '0') self.entry_yaw.insert(0, '0') Button(self, text='设置位置', command=self.set_pose).grid(row=8, column=3, sticky=W, pady=10) def connect(self): # 创建连接 self.robot = Transport(HOST, PORT) # 设置机器人信息反馈回调函数 self.robot.subscribe_speed(print_speed) self.robot.subscribe_pose(print_pose) # 启动连接 self.robot.connect() keep = threading.Thread(target=self.keep_connection, name='connection') keep.setDaemon(True) keep.start() def keep_connection(self): # 保持连接 self.robot.keep_alive(5) def set_speed(self): vx = float(self.entry_vx.get()) vy = float(self.entry_vy.get()) vw = float(self.entry_vw.get()) self.robot.set_speed(vx, vy, vw) def set_pose(self): x = float(self.entry_x.get()) y = float(self.entry_y.get()) yaw = float(self.entry_yaw.get()) self.robot.set_pose(x, y, yaw)
class Face: """ Defines the face class Each node will contain one or more faces eg:- from Face import Face from Transport import Transport id = 1 name = "face1" localhost = '127.0.0.1' transport = Transport() transport.set('127.0.0.1') face = Face(id, name, transport) print(face) print(face.get()) print(face.get_value()) """ def __init__(self, id = 0, name = "test face", ip_address = None, node = None): """ id - this is the id of the face in the node name - this is the name of the face transport - this is the networking interface of this face """ self.__id = id self.__name = name self.__node = node self.__transport = Transport(ip_address = ip_address, face = self) def __str__(self): face = self.get() return str(face) def get_id(self): return self.__id def get_name(self): return self.__name def get_transport(self): return self.__transport def get_node(self): return self.__node def set_transport(self, transport = None): """ :param transport: It is the object of the Transport class :return: True if successful """ try: if isinstance(transport, Transport): self.__transport = transport return True else: raise TypeError("invalid transport") except TypeError: print("incorrect transport format") return False def get(self): id = self.get_id() name = self.get_name() trasport = self.get_transport().get_value() face = {"id" : id, "name" : name, "transport" : trasport} return face def get_value(self): """ returns the face id """ return self.get_id() def send_interest(self, interest): """ send interest from application to the node ( forwarding daemon) """ node = self.get_node() node.send_interest(self, interest) def forward_interest(self, interest): """ Forward interest from node ( forwarding daemon ) to application / networking interfaces """ transport = self.get_transport() transport.send_interest(interest) def receive_interest(self, interest): """ Receive interest from the networking interfaces """ node = self.get_node() node.receive_interest() def send_data(self): """ send data from application to the node ( forwarding daemon) """ pass def forward_data(self, data): """ Forward data from node ( forwarding daemon ) to application / networking interfaces """ transport = self.get_transport() transport.send_data(data) def receive_data(self, data): """ Receive data from the networking interfaces or application and pass it to node """ node = self.get_node() node.receive_data(data, self) def listen(self): self.__transport.listen() def get_dummy_data(self): """ Get dummy data from the sender so that safety messages can be verified properly. :return: Data object """ transport = self.get_transport() data = transport.get_dummy_data() return data