def cb_initialize_plugin(self): self.config = self.pl_get_current_config_ref() self.t = 0 self.amax = Fourier_Rect.amax self.amplitude = 1 self.max_approx = Fourier_Rect.max_approx self.freq = 1 self.vec = numpy.ones(self.amax * (self.max_approx + 1)) print(['Fourier: process id: ', os.getpid()]) self.HOST = self.config['host']['value'] self.PORT = int(self.config['port']['value']) # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1, self.max_approx): self.block1.add_signal(DSignal('rect' + str(i))) self.pl_send_new_block_list([self.block1]) return True
def test_dblocks(self): dpl_1 = DPlugin() dpl_1.id = 1 dbl_1 = DBlock('Block1') dbl_1.dplugin_id = dpl_1.id dbl_2 = DBlock('Block2') dbl_2.dplugin_id = dpl_1.id #check: add Parameter self.assertTrue(dpl_1.add_dblock(dbl_1)) self.assertTrue(dpl_1.add_dblock(dbl_2)) self.assertFalse(dpl_1.add_dblock(dbl_1)) self.assertFalse(dpl_1.add_dblock(dbl_2)) #Check: count of parameters self.assertEqual(len(dpl_1.get_dblocks().keys()), 2) #Check: rm parameter self.assertTrue(dpl_1.rm_dblock(dbl_1)) self.assertEqual(len(dpl_1.get_dblocks().keys()), 1) self.assertTrue(dpl_1.rm_dblock(dbl_2)) self.assertEqual(len(dpl_1.get_dblocks().keys()), 0)
def cb_initialize_plugin(self): self.t = 0 self.amax = Fourier_Rect_MOD.amax self.amplitude = 1 self.max_approx = Fourier_Rect_MOD.max_approx self.freq = 1 self.vec = numpy.ones(self.amax * (self.max_approx + 1)) print(['Fourier: process id: ', os.getpid()]) self.HOST = "130.149.155.73" self.PORT = 9999 # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1, self.max_approx): self.block1.add_signal(DSignal('rect' + str(i))) self.pl_send_new_block_list([self.block1]) self.pl_set_event_trigger_mode(True) self.goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST, self.PORT)) self.thread.start() return True
def cb_initialize_plugin(self): self.block1 = DBlock('Progress') signal = DSignal('percent') self.block1.add_signal(signal) self.block2 = DBlock('Trigger') signal = DSignal('trigger') self.block2.add_signal(signal) self.block3 = DBlock('ResetTrigger') signal = DSignal('reset') self.block3.add_signal(signal) self.block4 = DBlock('ParaToSig') signal = DSignal('parameter') self.block4.add_signal(signal) blockList = [self.block1, self.block2, self.block3, self.block4] self.pl_send_new_block_list(blockList) self.para3 = DParameter('Choose', default=0, Regex='\d+') para_l = [self.para3] self.pl_send_new_parameter_list(para_l) self.pl_set_event_trigger_mode(True) self.initialized = True return True
def test_remove_signal(self): dblock = DBlock('SinMit_f1') ds_1 = DSignal(CORE_TIME_SIGNAL) dblock.add_signal(ds_1) subscription = DSubscription(dblock) subscription.add_signal(ds_1) self.assertTrue(subscription.rm_signal(ds_1)) self.assertNotIn(ds_1, subscription.get_signals()) self.assertTrue(subscription.add_signal(ds_1))
def test_pl_send_new_block_list(self): self.assertRaises(pe.WrongType, self.basePlugin.pl_send_new_block_list, None) self.assertRaises(pe.WrongLength, self.basePlugin.pl_send_new_block_list, []) blocks = [DBlock('1'), 1, DBlock('3')] self.assertRaises(pe.WrongType, self.basePlugin.pl_send_new_block_list, blocks) blocks = [DBlock('1'), DBlock('2'), DBlock('3')] self.assertRaises(AttributeError, self.basePlugin.pl_send_new_block_list, blocks)
def test_unsubscribe_all(self): #Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_3 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) #Create dblocks d_bl_1 = DBlock('Block_1') d_bl_2 = DBlock('Block_2') #assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name)) self.assertTrue(self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_1.name)) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name)) print(d_bl_1.get_subscribers()) self.assertEqual(len(d_pl_2.get_subscribtions()[d_pl_1.id].keys()), 2) self.dcore.unsubscribe_all(d_pl_2.id) self.assertNotIn(d_pl_1.id, d_pl_2.get_subscribtions()) print(d_bl_1.get_subscribers()) self.assertTrue(len(d_bl_1.get_subscribers())==1) self.assertTrue(len(d_bl_2.get_subscribers())==0) pass
def test_rm_dplugin(self): #Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) #Create dblocks d_bl_1 = DBlock('Block_1') d_bl_2 = DBlock('Block_2') #assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) #create subscribtions self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name) self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name) self.assertEqual(len(d_pl_2.get_subscribtions()[d_pl_1.id]), 2) self.assertEqual(len(d_bl_1.get_subscribers()), 1) self.assertEqual(len(d_bl_2.get_subscribers()), 1) self.dcore.rm_dplugin(d_pl_1.id) #Check if DPlugin d_pl_1 is missing self.assertFalse(self.dcore.get_dplugin_by_id(d_pl_1.id)) #Check if all subscribtions were canceled self.assertEqual(len(d_pl_2.get_subscribtions().keys()), 0) self.assertEqual(len(d_bl_1.get_subscribers()), 0) self.assertEqual(len(d_bl_2.get_subscribers()), 0) pass
def test_add_susbcribers(self): dbl = DBlock('DBlock1') dbl.id = 1 dpl_1 = DPlugin() dpl_1.id = 2 dpl_2 = DPlugin() dpl_2.id = 3 self.assertTrue(dbl.add_subscribers(dpl_1)) self.assertTrue(dbl.add_subscribers(dpl_2)) self.assertEqual(len(dbl.get_subscribers()), 2)
def test_attach_signal(self): dblock = DBlock('SinMit_f1') ds_1 = DSignal(CORE_TIME_SIGNAL) ds_2 = DSignal('f1_1') dblock.add_signal(ds_1) dblock.add_signal(ds_2) subscription = DSubscription(dblock) self.assertTrue(subscription.add_signal(ds_1)) self.assertIn(ds_1, subscription.get_signals()) self.assertFalse(subscription.add_signal(ds_1))
def test_add_susbcribers(self): dbl = DBlock('DBlock1') dbl.id = 1 dpl_1 = DPlugin() dpl_1.id = 2 dpl_2 = DPlugin() dpl_2.id = 3 self.assertTrue(dbl.add_subscribers(dpl_1)) self.assertTrue(dbl.add_subscribers(dpl_2)) self.assertEqual(len(dbl.get_subscribers()),2)
def test_subscribtions(self): dpl_1 = DPlugin() dpl_1.id = 1 dpl_2 = DPlugin() dpl_2.id = 2 dbl_1 = DBlock('DBlock1') dbl_1.id = 3 dbl_1.dplugin_id = dpl_2.id dbl_2 = DBlock('DBlock2') dbl_2.id = 4 dbl_2.dplugin_id = dpl_2.id dpl_2.add_dblock(dbl_1) dpl_2.add_dblock(dbl_2) #Check: subscribe DBlocks self.assertTrue(dpl_1.subscribe(dbl_1)) self.assertTrue(dpl_1.subscribe(dbl_2)) self.assertFalse(dpl_1.subscribe(dbl_1)) self.assertFalse(dpl_1.subscribe(dbl_2)) #Check: count of subscribtions self.assertEqual(len(dpl_1.get_subscribtions()[dpl_2.id].keys()), 2) #Check: unsubscribe DBlock self.assertTrue(dpl_1.unsubscribe(dbl_1)) #Check: count of subscribtions self.assertEqual(len(dpl_1.get_subscribtions().keys()), 1) #Check: count of subscribtions self.assertEqual(len(dpl_1.get_subscribtions()[dpl_2.id].keys()), 1)
def test_rm_all_subscribers(self): #Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_3 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) #Create dblocks d_bl_1 = DBlock('Block_1') d_bl_2 = DBlock('Block_2') #assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name)) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name)) self.assertTrue(self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_1.name)) self.assertTrue(self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_2.name)) self.assertEqual(len(d_bl_1.get_subscribers()), 2) self.assertEqual(len(d_bl_2.get_subscribers()), 2) self.dcore.rm_all_subscribers(d_pl_1.id) self.assertEqual(len(d_bl_1.get_subscribers()), 0) self.assertEqual(len(d_bl_2.get_subscribers()), 0) pass
def cb_initialize_plugin(self): self.t = 0 #print(['ADD: process id: ',os.getpid()] ) self.approx_max = 300 self.fac = 1 self.amax = 20 self.approx = self.approx_max * self.fac self.block1 = DBlock('AddOut1') signal = DSignal('Sum') self.block1.add_signal(signal) self.pl_send_new_block_list([self.block1]) return True
def cb_initialize_plugin(self): self.t = 0 self.amax = Fourier_Rect_MOD.amax self.amplitude = 1 self.max_approx = Fourier_Rect_MOD.max_approx self.freq = 1 self.vec = numpy.ones(self.amax* ( self.max_approx + 1) ) print(['Fourier: process id: ',os.getpid()] ) self.HOST = "130.149.155.73" self.PORT = 9999 # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1,self.max_approx): self.block1.add_signal(DSignal('rect'+str(i))) self.pl_send_new_block_list([self.block1]) self.pl_set_event_trigger_mode(True) self.goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST,self.PORT) ) self.thread.start() return True
def test_delete_block(self): self.assertRaises(pe.WrongType, self.basePlugin.pl_send_delete_block, None) self.assertRaises(AttributeError, self.basePlugin.pl_send_delete_block, 'DBlock') self.assertRaises(AttributeError, self.basePlugin.pl_send_delete_block, DBlock('DBlock'))
def config_loader_subs(self, pl_to_start, subs_to_make, parameters_to_change, signals_to_change): """ Function for callback when timer finished to apply subscriptions and parameter changed of config. :param pl_to_start: list of plugins to start :type pl_to_start: list :param subs_to_make: list of subscriptions to make :type subs_to_make: list :param parameters_to_change: parameter changes to apply :type parameters_to_change: list :param signals_to_change: signal name changes to apply :type signals_to_change: list :return: """ for sub in subs_to_make: self.do_subscribe_uname(sub[0], sub[1], sub[2], sub[3], sub[4]) for para in parameters_to_change: self.do_set_parameter_uname(para[0], para[1], para[2]) for sig in signals_to_change: plugin_uname = sig[0] dblock_name = sig[1] dsignal_uname = sig[2] dsignal_dname = sig[3] self.do_edit_plugin_uname( plugin_uname, DBlock(dblock_name), {'edit': DSignal(dsignal_uname, dsignal_dname)})
def update_block_list(self, ORTDSources): #self.block_id = self.block_id +1 #newBlock = DBlock('SourceGroup'+str(self.block_id)) #self.blocks['SourceGroup'+str(self.block_id)] = newBlock if 'SourceGroup0' in self.blocks: self.pl_send_delete_block('SourceGroup0') newBlock = DBlock('SourceGroup0') self.blocks['SourceGroup0'] = newBlock self.Sources = ORTDSources keys = list(self.Sources.keys()) for key in keys: Source = self.Sources[key] sig_name = Source['SourceName'] newBlock.add_signal(DSignal(sig_name)) self.pl_send_new_block_list([newBlock])
def cb_initialize_plugin(self): self.config = self.pl_get_current_config_ref() self.t = 0 self.amax = Fourier_Rect.amax self.amplitude = 1 self.max_approx = Fourier_Rect.max_approx self.freq = 1 self.vec = numpy.ones(self.amax* ( self.max_approx + 1) ) print(['Fourier: process id: ',os.getpid()] ) self.HOST = self.config['host']['value'] self.PORT = int( self.config['port']['value'] ) # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1,self.max_approx): self.block1.add_signal(DSignal('rect'+str(i))) self.pl_send_new_block_list([self.block1]) return True
def update_block_list(self,ORTDSources): #self.block_id = self.block_id +1 #newBlock = DBlock('SourceGroup'+str(self.block_id)) #self.blocks['SourceGroup'+str(self.block_id)] = newBlock if 'SourceGroup0' in self.blocks: self.pl_send_delete_block('SourceGroup0') newBlock = DBlock('SourceGroup0') self.blocks['SourceGroup0'] = newBlock self.Sources = ORTDSources keys = list(self.Sources.keys()) for key in keys: Source = self.Sources[key] sig_name = Source['SourceName'] newBlock.add_signal(DSignal(sig_name)) self.pl_send_new_block_list([newBlock])
def test_subscribe(self): # Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) # Create dblocks d_bl_1 = DBlock("Block_1") d_bl_2 = DBlock("Block_2") # assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name)) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name)) self.assertTrue(d_pl_2.id in d_bl_1.get_subscribers()) self.assertTrue(d_pl_2.id in d_bl_2.get_subscribers())
def test_subscribe_signals(self): #Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_3 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) #Create dblocks d_bl_1 = DBlock('Block1') d_bl_2 = DBlock('Block2') #assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name) self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name) self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_1.name) self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_2.name) self.assertTrue(self.dcore.subscribe_signals(d_pl_2.id, d_pl_1.id, d_bl_1.name, [1, 2, 3])) self.assertTrue(self.dcore.subscribe_signals(d_pl_2.id, d_pl_1.id, d_bl_2.name, [6, 4, 5])) self.assertTrue(self.dcore.subscribe_signals(d_pl_3.id, d_pl_1.id, d_bl_1.name, [9])) self.assertTrue(self.dcore.subscribe_signals(d_pl_3.id, d_pl_1.id, d_bl_2.name, [17,19,18])) subscription = d_pl_2.get_subscribtions()[d_pl_1.id][d_bl_1.name] self.assertIn(1, subscription.get_signals()) self.assertIn(2, subscription.get_signals()) self.assertIn(3, subscription.get_signals()) subscription = d_pl_3.get_subscribtions()[d_pl_1.id][d_bl_2.name] self.assertIn(19, subscription.get_signals()) self.assertIn(17, subscription.get_signals()) self.assertIn(18, subscription.get_signals()) subscription = d_pl_3.get_subscribtions()[d_pl_1.id][d_bl_1.name] self.assertIn(9, subscription.get_signals())
def test_rm_dplugin(self): # Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) # Create dblocks d_bl_1 = DBlock("Block_1") d_bl_2 = DBlock("Block_2") # assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) # create subscribtions self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name) self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name) self.assertEqual(len(d_pl_2.get_subscribtions()[d_pl_1.id]), 2) self.assertEqual(len(d_bl_1.get_subscribers()), 1) self.assertEqual(len(d_bl_2.get_subscribers()), 1) self.dcore.rm_dplugin(d_pl_1.id) # Check if DPlugin d_pl_1 is missing self.assertFalse(self.dcore.get_dplugin_by_id(d_pl_1.id)) # Check if all subscribtions were canceled self.assertEqual(len(d_pl_2.get_subscribtions().keys()), 0) self.assertEqual(len(d_bl_1.get_subscribers()), 0) self.assertEqual(len(d_bl_2.get_subscribers()), 0) pass
def test_unsubscribe_all(self): # Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_3 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) # Create dblocks d_bl_1 = DBlock("Block_1") d_bl_2 = DBlock("Block_2") # assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name)) self.assertTrue(self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_1.name)) self.assertTrue(self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name)) print(d_bl_1.get_subscribers()) self.assertEqual(len(d_pl_2.get_subscribtions()[d_pl_1.id].keys()), 2) self.dcore.unsubscribe_all(d_pl_2.id) self.assertNotIn(d_pl_1.id, d_pl_2.get_subscribtions()) print(d_bl_1.get_subscribers()) self.assertTrue(len(d_bl_1.get_subscribers()) == 1) self.assertTrue(len(d_bl_2.get_subscribers()) == 0) pass
def pl_create_DBlock(self, block_name): """ Creates a DBlock for use in a PaPI Plugin. :param block_name: Name of the block :type block_name: str :return: DBlock Object or None in case of error """ if isinstance(block_name, str): block = DBlock(name=block_name) return block else: return None
def test_parameterChanges(self): self.assertRaises(pe.WrongType, self.basePlugin.pl_emit_event, None, None) self.assertRaises(AttributeError, self.basePlugin._send_parameter_change, None, "DBlock") self.assertRaises(AttributeError, self.basePlugin.pl_emit_event, None, "DEvent") self.assertRaises(AttributeError, self.basePlugin._send_parameter_change, None, DBlock("Block")) self.assertRaises(AttributeError, self.basePlugin.pl_emit_event, None, DEvent("Event"))
def test_unsubscribe_signals(self): # Create dplugins d_pl_1 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_2 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) d_pl_3 = self.dcore.add_plugin(None, 1, None, None, None, self.dcore.create_id()) # Create dblocks d_bl_1 = DBlock("Block1") d_bl_2 = DBlock("Block2") # assign dblocks to DPlugin d_pl_1 d_pl_1.add_dblock(d_bl_1) d_pl_1.add_dblock(d_bl_2) self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_1.name) self.dcore.subscribe(d_pl_2.id, d_pl_1.id, d_bl_2.name) self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_1.name) self.dcore.subscribe(d_pl_3.id, d_pl_1.id, d_bl_2.name) self.dcore.subscribe_signals(d_pl_2.id, d_pl_1.id, d_bl_1.name, [1, 2, 3]) self.dcore.subscribe_signals(d_pl_2.id, d_pl_1.id, d_bl_2.name, [6, 4, 5]) self.dcore.subscribe_signals(d_pl_3.id, d_pl_1.id, d_bl_1.name, [9]) self.dcore.subscribe_signals(d_pl_3.id, d_pl_1.id, d_bl_2.name, [17, 19, 18]) self.assertTrue(self.dcore.unsubscribe_signals(d_pl_2.id, d_pl_1.id, d_bl_1.name, [1, 2])) subscription = d_pl_2.get_subscribtions()[d_pl_1.id][d_bl_1.name] self.assertNotIn(1, subscription.get_signals()) self.assertNotIn(2, subscription.get_signals()) self.assertIn(3, subscription.get_signals()) self.assertEqual(len(d_bl_1.get_subscribers()), 2) self.assertTrue(self.dcore.unsubscribe_signals(d_pl_2.id, d_pl_1.id, d_bl_1.name, [3])) self.assertEqual(len(d_bl_1.get_subscribers()), 1)
def cb_initialize_plugin(self): self.t = 0 #print(['ADD: process id: ',os.getpid()] ) self.approx_max = 300 self.fac= 1 self.amax = 20 self.approx = self.approx_max*self.fac self.block1 = DBlock('AddOut1') signal = DSignal('Sum') self.block1.add_signal(signal) self.pl_send_new_block_list([self.block1]) return True
def cb_initialize_plugin(self): # --------------------------- # Read configuration # --------------------------- # -------------------------------- # Create Widget # -------------------------------- self.ConsoleW = PaPIConsoleWidget(plugin=self) # This call is important, because the background structure needs to know the used widget! # In the background the qmidiwindow will becreated and the widget will be added self.pl_set_widget_for_internal_usage(self.ConsoleW) self.ConsoleW.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.ConsoleW.customContextMenuRequested.connect( self.show_context_menu) block = DBlock('Command') self.pl_send_new_block_list([block]) return True
def cb_initialize_plugin(self): config = self.pl_get_current_config_ref() self.t = 0 self.amax = int(config['amax']['value']) self.f = float(config['f']['value']) self.block1 = DBlock('SinMit_f1') signal = DSignal('f1_1') signal.dname = 'f1_f1DNAME' self.block1.add_signal(signal) self.block2 = DBlock('SinMit_f2') signal = DSignal('f2_1') self.block2.add_signal(signal) self.block3 = DBlock('SinMit_f3') signal = DSignal('f3_1') self.block3.add_signal(signal) signal = DSignal('f3_2') self.block3.add_signal(signal) signal = DSignal('f3_scalar') self.block3.add_signal(signal) #self.block4 = self.create_new_block('Sin4', [CORE_TIME_SIGNAL,'f3_1','f3_2', 'Scalar'], [ 'numpy_vec', 'numpy_vec', 'numpy_vec', 'int'], 100 ) blockList = [self.block1, self.block2, self.block3] self.pl_send_new_block_list(blockList) self.para3 = DParameter('Frequenz Block SinMit_f3', default= 0.3, Regex='[0-9]+.[0-9]+') para_l = [self.para3] self.pl_send_new_parameter_list(para_l) print('Sinus started working') return True
class Trigger(dpp_base): def __init__(self): self.initialized = False def cb_initialize_plugin(self): self.block1 = DBlock('Progress') signal = DSignal('percent') self.block1.add_signal(signal) self.block2 = DBlock('Trigger') signal = DSignal('trigger') self.block2.add_signal(signal) self.block3 = DBlock('ResetTrigger') signal = DSignal('reset') self.block3.add_signal(signal) self.block4 = DBlock('ParaToSig') signal = DSignal('parameter') self.block4.add_signal(signal) blockList = [self.block1, self.block2, self.block3, self.block4] self.pl_send_new_block_list(blockList) self.para3 = DParameter('Choose', default=0, Regex='\d+') para_l = [self.para3] self.pl_send_new_parameter_list(para_l) self.pl_set_event_trigger_mode(True) self.initialized = True return True def cb_pause(self): pass def cb_resume(self): pass def cb_execute(self, Data=None, block_name = None, plugin_uname = None): pass def cb_set_parameter(self, name, value): if not self.initialized: return value = int(float(value)) if name == self.para3.name: if value == 0: self.pl_send_new_data('Progress', [0], {'percent': [20]}) if value == 1: self.pl_send_new_data('Trigger', [0], {'trigger': [0]}) if value == 2: self.pl_send_new_data('ResetTrigger', [0], {'reset': [0]}) if value > 3: self.pl_send_new_data('ParaToSig', [0], {'parameter': [value]}) def cb_get_plugin_configuration(self): config = { } return config def cb_quit(self): print('Trigger: will quit') def cb_plugin_meta_updated(self): pass
class Add(dpp_base): def cb_initialize_plugin(self): self.t = 0 #print(['ADD: process id: ',os.getpid()] ) self.approx_max = 300 self.fac= 1 self.amax = 20 self.approx = self.approx_max*self.fac self.block1 = DBlock('AddOut1') signal = DSignal('Sum') self.block1.add_signal(signal) self.pl_send_new_block_list([self.block1]) return True def cb_pause(self): pass def cb_resume(self): pass def cb_execute(self, Data=None, block_name = None, plugin_uname = None): #self.approx = round(self.approx_max*self.para1.value) # self.vec[1] = 0 # self.vec[0] = Data[0] # vec = numpy.zeros( (1, 2) ) #for i in range(self.amax): #for k in range(1,self.approx): # self.vec[i+self.amax] += Data[i + (k+1)*self.amax] #self.vec[1, i] = Data[k, i] # Get Time Vector # vec[0, :] = Data[CORE_TIME_SIGNAL] # n_rows = Data.shape[0] # n_cols = Data.shape[1] first_element = True for signal_name in Data: if signal_name is not CORE_TIME_SIGNAL: signal = Data[signal_name] if first_element is True: first_element = False result = signal else: result = numpy.add(result, signal) self.pl_send_new_data('AddOut1', Data[CORE_TIME_SIGNAL], {'Sum':result}) def cb_set_parameter(self, name, value): pass def cb_quit(self): print('Add: will quit') def cb_plugin_meta_updated(self): pass def cb_get_plugin_configuration(self): return {}
class Fourier_Rect_MOD(iop_base): max_approx = 20 amax = 20 def cb_initialize_plugin(self): self.t = 0 self.amax = Fourier_Rect_MOD.amax self.amplitude = 1 self.max_approx = Fourier_Rect_MOD.max_approx self.freq = 1 self.vec = numpy.ones(self.amax * (self.max_approx + 1)) print(['Fourier: process id: ', os.getpid()]) self.HOST = "130.149.155.73" self.PORT = 9999 # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1, self.max_approx): self.block1.add_signal(DSignal('rect' + str(i))) self.pl_send_new_block_list([self.block1]) self.pl_set_event_trigger_mode(True) self.goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST, self.PORT)) self.thread.start() return True def cb_pause(self): self.goOn = False self.thread.join() def cb_resume(self): self.goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST, self.PORT)) self.thread.start() def thread_execute(self, host, port): #self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #self.sock.setblocking(0) vec = numpy.zeros((self.max_approx, (self.amax))) while self.goOn: self.sock.sendto(b'GET', (self.HOST, self.PORT)) try: received = self.sock.recv(60000) except socket.error: pass else: data = pickle.loads(received) vech = {} t = data[0 * self.amax:(0 + 1) * self.amax] for i in range(self.max_approx): vech['rect' + str(i)] = data[i * self.amax:(i + 1) * self.amax] self.pl_send_new_data('Rectangle', t, vech) time.sleep(0.001 * self.amax) def cb_execute(self, Data=None, block_name=None, plugin_uname=None): print("EXECUTE FUNC") pass def cb_set_parameter(self, name, value): pass def cb_quit(self): self.goOn = False self.thread.join() def cb_plugin_meta_updated(self): pass def cb_get_plugin_configuration(self): return {}
class Fourier_Rect(iop_base): max_approx = 20 amax = 20 def cb_initialize_plugin(self): self.config = self.pl_get_current_config_ref() self.t = 0 self.amax = Fourier_Rect.amax self.amplitude = 1 self.max_approx = Fourier_Rect.max_approx self.freq = 1 self.vec = numpy.ones(self.amax * (self.max_approx + 1)) print(['Fourier: process id: ', os.getpid()]) self.HOST = self.config['host']['value'] self.PORT = int(self.config['port']['value']) # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1, self.max_approx): self.block1.add_signal(DSignal('rect' + str(i))) self.pl_send_new_block_list([self.block1]) return True def cb_pause(self): pass def cb_resume(self): pass def cb_execute(self, Data=None, block_name=None, plugin_uname=None): # amount of elements per vector: self.amax # amount of vectors : self.max_approx+1 vec = numpy.zeros((self.max_approx, (self.amax))) # print("Amax: " + str(self.amax+1)) # print("Max_Approx" + str(self.max_approx)) # As you can see, there is no connect() call; UDP has no connections. # Instead, data is directly sent to the recipient via sendto(). self.sock.sendto(b'GET', (self.HOST, self.PORT)) try: received = self.sock.recv(60000) except socket.error: pass else: data = pickle.loads(received) vech = {} t = data[0 * self.amax:(0 + 1) * self.amax] for i in range(self.max_approx): vech['rect' + str(i)] = data[i * self.amax:(i + 1) * self.amax] self.pl_send_new_data('Rectangle', t, vech) time.sleep(0.001 * self.amax) def cb_set_parameter(self, name, value): pass def cb_quit(self): print('Fourier_Rect: will quit') def cb_get_plugin_configuration(self): config = { 'name': { 'value': 'Fourier' }, 'host': { 'value': "130.149.155.73", 'regex': '\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}', 'advanced': '1' }, 'port': { 'value': 9999, 'regex': '\d{1,5}', 'advanced': '1' } } return config def cb_plugin_meta_updated(self): pass
class Fourier_Rect(iop_base): max_approx = 20 amax = 20 def cb_initialize_plugin(self): self.config = self.pl_get_current_config_ref() self.t = 0 self.amax = Fourier_Rect.amax self.amplitude = 1 self.max_approx = Fourier_Rect.max_approx self.freq = 1 self.vec = numpy.ones(self.amax* ( self.max_approx + 1) ) print(['Fourier: process id: ',os.getpid()] ) self.HOST = self.config['host']['value'] self.PORT = int( self.config['port']['value'] ) # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1,self.max_approx): self.block1.add_signal(DSignal('rect'+str(i))) self.pl_send_new_block_list([self.block1]) return True def cb_pause(self): pass def cb_resume(self): pass def cb_execute(self, Data=None, block_name = None, plugin_uname = None): # amount of elements per vector: self.amax # amount of vectors : self.max_approx+1 vec = numpy.zeros( (self.max_approx, (self.amax) )) # print("Amax: " + str(self.amax+1)) # print("Max_Approx" + str(self.max_approx)) # As you can see, there is no connect() call; UDP has no connections. # Instead, data is directly sent to the recipient via sendto(). self.sock.sendto(b'GET', (self.HOST, self.PORT) ) try: received = self.sock.recv(60000) except socket.error: pass else: data = pickle.loads(received) vech = {} t = data[0*self.amax:(0+1)*self.amax] for i in range(self.max_approx): vech['rect'+str(i)] = data[i*self.amax:(i+1)*self.amax] self.pl_send_new_data('Rectangle', t, vech) time.sleep(0.001*self.amax ) def cb_set_parameter(self, name, value): pass def cb_quit(self): print('Fourier_Rect: will quit') def cb_get_plugin_configuration(self): config = { 'name': { 'value': 'Fourier' }, 'host': { 'value': "130.149.155.73", 'regex': '\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}', 'advanced' : '1' }, 'port': { 'value': 9999, 'regex': '\d{1,5}', 'advanced' : '1' }} return config def cb_plugin_meta_updated(self): pass
def test_rm_subscribers(self): dbl = DBlock('DBlock1') dbl.id = 1 dpl_1 = DPlugin() dpl_1.id = 2 dpl_2 = DPlugin() dpl_2.id = 3 dbl.add_subscribers(dpl_1) dbl.add_subscribers(dpl_2) self.assertEqual(len(dbl.get_subscribers()),2) dbl.rm_subscriber(dpl_1) self.assertEqual(len(dbl.get_subscribers()),1) dbl.rm_subscriber(dpl_2) self.assertEqual(len(dbl.get_subscribers()),0) self.assertFalse(dbl.rm_subscriber(dpl_1))
class Trigger(dpp_base): def __init__(self): self.initialized = False def cb_initialize_plugin(self): self.block1 = DBlock('Progress') signal = DSignal('percent') self.block1.add_signal(signal) self.block2 = DBlock('Trigger') signal = DSignal('trigger') self.block2.add_signal(signal) self.block3 = DBlock('ResetTrigger') signal = DSignal('reset') self.block3.add_signal(signal) self.block4 = DBlock('ParaToSig') signal = DSignal('parameter') self.block4.add_signal(signal) blockList = [self.block1, self.block2, self.block3, self.block4] self.pl_send_new_block_list(blockList) self.para3 = DParameter('Choose', default=0, Regex='\d+') para_l = [self.para3] self.pl_send_new_parameter_list(para_l) self.pl_set_event_trigger_mode(True) self.initialized = True return True def cb_pause(self): pass def cb_resume(self): pass def cb_execute(self, Data=None, block_name=None, plugin_uname=None): pass def cb_set_parameter(self, name, value): if not self.initialized: return value = int(float(value)) if name == self.para3.name: if value == 0: self.pl_send_new_data('Progress', [0], {'percent': [20]}) if value == 1: self.pl_send_new_data('Trigger', [0], {'trigger': [0]}) if value == 2: self.pl_send_new_data('ResetTrigger', [0], {'reset': [0]}) if value > 3: self.pl_send_new_data('ParaToSig', [0], {'parameter': [value]}) def cb_get_plugin_configuration(self): config = {} return config def cb_quit(self): print('Trigger: will quit') def cb_plugin_meta_updated(self): pass
def test_rm_subscribers(self): dbl = DBlock('DBlock1') dbl.id = 1 dpl_1 = DPlugin() dpl_1.id = 2 dpl_2 = DPlugin() dpl_2.id = 3 dbl.add_subscribers(dpl_1) dbl.add_subscribers(dpl_2) self.assertEqual(len(dbl.get_subscribers()), 2) dbl.rm_subscriber(dpl_1) self.assertEqual(len(dbl.get_subscribers()), 1) dbl.rm_subscriber(dpl_2) self.assertEqual(len(dbl.get_subscribers()), 0) self.assertFalse(dbl.rm_subscriber(dpl_1))
class Sinus(iop_base): def cb_initialize_plugin(self): config = self.pl_get_current_config_ref() self.t = 0 self.amax = int(config['amax']['value']) self.f = float(config['f']['value']) self.block1 = DBlock('SinMit_f1') signal = DSignal('f1_1') signal.dname = 'f1_f1DNAME' self.block1.add_signal(signal) self.block2 = DBlock('SinMit_f2') signal = DSignal('f2_1') self.block2.add_signal(signal) self.block3 = DBlock('SinMit_f3') signal = DSignal('f3_1') self.block3.add_signal(signal) signal = DSignal('f3_2') self.block3.add_signal(signal) signal = DSignal('f3_scalar') self.block3.add_signal(signal) #self.block4 = self.create_new_block('Sin4', [CORE_TIME_SIGNAL,'f3_1','f3_2', 'Scalar'], [ 'numpy_vec', 'numpy_vec', 'numpy_vec', 'int'], 100 ) blockList = [self.block1, self.block2, self.block3] self.pl_send_new_block_list(blockList) self.para3 = DParameter('Frequenz Block SinMit_f3', default= 0.3, Regex='[0-9]+.[0-9]+') para_l = [self.para3] self.pl_send_new_parameter_list(para_l) print('Sinus started working') return True def cb_pause(self): print('Sinus pause') pass def cb_resume(self): print('Sinus resume') pass def cb_execute(self, Data=None, block_name = None, plugin_uname = None): vec = numpy.zeros( (2,self.amax)) vec2 = numpy.zeros((2,self.amax)) vec3 = numpy.zeros((3,self.amax)) for i in range(self.amax): vec[0, i] = self.t vec[1, i] = math.sin(2*math.pi*0.8*self.t) vec2[0, i] = self.t vec2[1, i] = math.sin(2*math.pi*0.5*self.t) vec3[0, i] = self.t vec3[1, i] = math.sin(2*math.pi*self.para3.value*self.t) vec3[2, i] = math.sin(2*math.pi*0.1*self.t) self.t += 0.005 self.pl_send_new_data('SinMit_f1' ,vec[0].tolist() , {'f1_1': vec[1] } ) self.pl_send_new_data('SinMit_f2', vec2[0].tolist(), {'f2_1': vec2[1]} ) self.pl_send_new_data('SinMit_f3', vec3[0].tolist(), {'f3_1': vec3[1], 'f3_2': vec3[2], 'f3_scalar': [10,10,10] } ) time.sleep(self.amax*0.005) def cb_set_parameter(self, name, value): if name == self.para3.name: self.para3.value = float(value) def cb_get_plugin_configuration(self): config = { "amax": { 'value': 3, 'regex': '[0-9]+' }, 'f': { 'value': "1", 'regex': '\d+.{0,1}\d*' }} return config def cb_quit(self): print('Sinus: will quit') def cb_plugin_meta_updated(self): pass
def cb_initialize_plugin(self): # -------------------------------- # Step 0: Read documentation: http://tub-control.github.io/PaPI/ # -------------------------------- # -------------------------------- # Step 1: Read configuration items (startup cfg) # OPTIONAL # -------------------------------- # Please read the Documentation of pl_get_config_element() to understand what is happening here. # e.g. a configuration item named 'offset' is read. offset = self.pl_get_config_element('offset') offset = float(offset) if offset is not None else 0 # -------------------------------- # Step 2:Define blocks for output signals and define signals of blocks! # OPTIONAL # -------------------------------- # Here: block called CPU_LOAD with 2 signals for Core1 and Core2 blockLoad = DBlock('CPU_LOAD') sig_core1 = DSignal('Load_C1') sig_core2 = DSignal('Load_C2') blockLoad.add_signal(sig_core1) blockLoad.add_signal(sig_core2) self.pl_send_new_block_list([blockLoad]) # -------------------------------- # Step 3: Define parameter that are offered to PaPI # OPTIONAL # Sub-Step 1: Create Parameter Object # Sub-Step 2: Send list of Parameter Objects created to PaPI # -------------------------------- # use self. to remember the parameter object in this class/context for own usage! # e.g. parameter named parameterName1 is created! # Refer to the Doc of DParameter to read about advanced usages! self.parameter1 = DParameter('parameterName1') self.parameter2 = DParameter('parameterName2') self.pl_send_new_parameter_list([self.parameter1, self.parameter1]) # -------------------------------- # Step 4: Set the plugin trigger mode # OPTIONAL # In most cases for IOP you will leave it default, for DPP you will set it to true # Default will mean, that PaPI will decide on it. # -------------------------------- self.pl_set_event_trigger_mode('default') # -------------------------------- # Step 5: Developer and Plugin specific configuration # OPTIONAL # -------------------------------- # -------------------------------- # Step 6: Return Value # OBLIGATORY # Return True if the everything is alright! # False will lead to PaPI not starting this Plugin! # -------------------------------- return True
class Add(dpp_base): def cb_initialize_plugin(self): self.t = 0 #print(['ADD: process id: ',os.getpid()] ) self.approx_max = 300 self.fac = 1 self.amax = 20 self.approx = self.approx_max * self.fac self.block1 = DBlock('AddOut1') signal = DSignal('Sum') self.block1.add_signal(signal) self.pl_send_new_block_list([self.block1]) return True def cb_pause(self): pass def cb_resume(self): pass def cb_execute(self, Data=None, block_name=None, plugin_uname=None): #self.approx = round(self.approx_max*self.para1.value) # self.vec[1] = 0 # self.vec[0] = Data[0] # vec = numpy.zeros( (1, 2) ) #for i in range(self.amax): #for k in range(1,self.approx): # self.vec[i+self.amax] += Data[i + (k+1)*self.amax] #self.vec[1, i] = Data[k, i] # Get Time Vector # vec[0, :] = Data[CORE_TIME_SIGNAL] # n_rows = Data.shape[0] # n_cols = Data.shape[1] first_element = True for signal_name in Data: if signal_name is not CORE_TIME_SIGNAL: signal = Data[signal_name] if first_element is True: first_element = False result = signal else: result = numpy.add(result, signal) self.pl_send_new_data('AddOut1', Data[CORE_TIME_SIGNAL], {'Sum': result}) def cb_set_parameter(self, name, value): pass def cb_quit(self): print('Add: will quit') def cb_plugin_meta_updated(self): pass def cb_get_plugin_configuration(self): return {}
def cb_initialize_plugin(self): print('ORTD', self.__id__, ':process id', os.getpid()) self.config = self.pl_get_current_config_ref() # open UDP self.HOST = self.config['address']['value'] self.SOURCE_PORT = int(self.config['source_port']['value']) self.OUT_PORT = int(self.config['out_port']['value']) self.LOCALBIND_HOST = '' # config['source_address']['value'] #CK self.sendOnReceivePort = True if self.config['SendOnReceivePort'][ 'value'] == '1' else False self.UseSocketIO = True if self.config['UseSocketIO'][ 'value'] == '1' else False if self.UseSocketIO: self.SocketIOPort = int(self.config['socketio_port']['value']) #self.sendOnReceivePort = True # NOTE: remove this #self.UseSocketIO = True # NOTE: remove this print("SendOnReceivePort = ", self.sendOnReceivePort) print("UseSocketIO = ", self.UseSocketIO) self.PAPI_SIMULINK_BLOCK = False self.separate = int(self.config['SeparateSignals']['value']) self.onlyInitialConfig = self.config['OnlyInitialConfig'][ 'value'] == '1' self.hasInitialConfig = False if (not self.sendOnReceivePort): # SOCK_DGRAM is the socket type to use for UDP sockets self.sock_parameter = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock_parameter.setblocking(1) self.ControlBlock = DBlock('ControllerSignals') self.ControlBlock.add_signal(DSignal('ControlSignalReset')) self.ControlBlock.add_signal(DSignal('ControlSignalCreate')) self.ControlBlock.add_signal(DSignal('ControlSignalSub')) self.ControlBlock.add_signal(DSignal('ControllerSignalParameter')) self.ControlBlock.add_signal(DSignal('ControllerSignalClose')) self.ControlBlock.add_signal(DSignal('ActiveTab')) self.pl_send_new_block_list([self.ControlBlock]) self.t = 0 self.pl_set_event_trigger_mode(True) self.sock_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if (not self.sendOnReceivePort): self.sock_recv.bind((self.LOCALBIND_HOST, self.SOURCE_PORT)) # CK print("UDP_Plugin-plugin listening on: ", self.LOCALBIND_HOST, ":", self.SOURCE_PORT) #CK else: print("---- Using client UDP mode (not binding to a port) ----") self.sock_recv.settimeout(1) self.thread_goOn = True self.lock = threading.Lock() self.thread = threading.Thread(target=self.thread_execute) self.thread.start() if self.UseSocketIO: print("Using socket.io connection on port", self.SocketIOPort) self.thread_socket_goOn = True self.thread_socketio = threading.Thread( target=self.thread_socketio_execute) self.blocks = {} self.Sources = {} self.parameters = {} self.signal_values = {} self.block_id = 0 self.config_complete = False self.config_buffer = {} self.timer = Timer(3, self.callback_timeout_timer) self.timer_active = False self.ConsoleBlock = DBlock('ConsoleSignals') self.ConsoleBlock.add_signal(DSignal('MainSignal')) self.pl_send_new_block_list([self.ConsoleBlock]) self.consoleIn = DParameter('consoleIn', default='') self.pl_send_new_parameter_list([self.consoleIn]) if self.UseSocketIO: self.thread_socketio.start() return True
class UDP_Plugin(iop_base): def cb_get_plugin_configuration(self): config = { 'address': { 'value': '127.0.0.1', 'advanced': '1' }, 'source_port': { 'value': '20000', 'advanced': '1' }, 'out_port': { 'value': '20001', 'advanced': '1' }, 'Cfg_Path': { 'value': '/home/control/PycharmProjects/PaPI/data_sources/ORTD/DataSourceExample/ProtocollConfig.json', 'type': 'file', 'advanced': '0' }, 'SeparateSignals': { 'value': '0', 'advanced': '1' }, 'SendOnReceivePort': { 'value': '0', # NOTE: chnage back to 0 'advanced': '1', 'display_text': 'Use same port for send and receive' }, "UseSocketIO": { 'value': '0', # NOTE: change back to 0 !! 'advanced': '1', 'tooltip': 'Use socket.io connection to node.js target-server', 'type': 'bool' }, 'socketio_port': { 'value': '8091', 'advanced': '1' }, "OnlyInitialConfig": { 'value': '0', 'tooltip': 'Use only first configuration, ignore further configurations.', 'type': 'bool' } } return config def cb_initialize_plugin(self): print('ORTD', self.__id__, ':process id', os.getpid()) self.config = self.pl_get_current_config_ref() # open UDP self.HOST = self.config['address']['value'] self.SOURCE_PORT = int(self.config['source_port']['value']) self.OUT_PORT = int(self.config['out_port']['value']) self.LOCALBIND_HOST = '' # config['source_address']['value'] #CK self.sendOnReceivePort = True if self.config['SendOnReceivePort'][ 'value'] == '1' else False self.UseSocketIO = True if self.config['UseSocketIO'][ 'value'] == '1' else False if self.UseSocketIO: self.SocketIOPort = int(self.config['socketio_port']['value']) #self.sendOnReceivePort = True # NOTE: remove this #self.UseSocketIO = True # NOTE: remove this print("SendOnReceivePort = ", self.sendOnReceivePort) print("UseSocketIO = ", self.UseSocketIO) self.PAPI_SIMULINK_BLOCK = False self.separate = int(self.config['SeparateSignals']['value']) self.onlyInitialConfig = self.config['OnlyInitialConfig'][ 'value'] == '1' self.hasInitialConfig = False if (not self.sendOnReceivePort): # SOCK_DGRAM is the socket type to use for UDP sockets self.sock_parameter = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock_parameter.setblocking(1) self.ControlBlock = DBlock('ControllerSignals') self.ControlBlock.add_signal(DSignal('ControlSignalReset')) self.ControlBlock.add_signal(DSignal('ControlSignalCreate')) self.ControlBlock.add_signal(DSignal('ControlSignalSub')) self.ControlBlock.add_signal(DSignal('ControllerSignalParameter')) self.ControlBlock.add_signal(DSignal('ControllerSignalClose')) self.ControlBlock.add_signal(DSignal('ActiveTab')) self.pl_send_new_block_list([self.ControlBlock]) self.t = 0 self.pl_set_event_trigger_mode(True) self.sock_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if (not self.sendOnReceivePort): self.sock_recv.bind((self.LOCALBIND_HOST, self.SOURCE_PORT)) # CK print("UDP_Plugin-plugin listening on: ", self.LOCALBIND_HOST, ":", self.SOURCE_PORT) #CK else: print("---- Using client UDP mode (not binding to a port) ----") self.sock_recv.settimeout(1) self.thread_goOn = True self.lock = threading.Lock() self.thread = threading.Thread(target=self.thread_execute) self.thread.start() if self.UseSocketIO: print("Using socket.io connection on port", self.SocketIOPort) self.thread_socket_goOn = True self.thread_socketio = threading.Thread( target=self.thread_socketio_execute) self.blocks = {} self.Sources = {} self.parameters = {} self.signal_values = {} self.block_id = 0 self.config_complete = False self.config_buffer = {} self.timer = Timer(3, self.callback_timeout_timer) self.timer_active = False self.ConsoleBlock = DBlock('ConsoleSignals') self.ConsoleBlock.add_signal(DSignal('MainSignal')) self.pl_send_new_block_list([self.ConsoleBlock]) self.consoleIn = DParameter('consoleIn', default='') self.pl_send_new_parameter_list([self.consoleIn]) if self.UseSocketIO: self.thread_socketio.start() return True def SIO_callback_SCISTOUT(self, data): # Got a chunk of data from a console interface in the target server self.sio_count += 1 self.pl_send_new_data(self.ConsoleBlock.name, [self.sio_count], {'MainSignal': data['Data']}) def SIO_callback_PAPICONFIG(self, data): # Got a new PaPI plugin configuration in JSON-format via socket.io connection # currently the config is transmitted via ORTD packets that may also be encapsulated into socket.io # added 12.8.15, CK print("Got a new config in JSON/socket.io format") print(data) self.check_and_process_cfg(data) # TODO: Test this def SIO_callback_ORTDPACKET(self, data): # Got an encapsulated packet from ORTD, not transfered via UDP but encapsulated within the socket.io connection #print ("Got data packet from ORTD via socket.io") #print (data) self.process_received_package( base64.b64decode(data)) # data must be a binary blob def thread_socketio_execute(self): #self.sio = SocketIO('localhost', 8091, LoggingNamespace) #self.sio.on('SCISTOUT',self.callback_SCISTOUT) while True: try: with SocketIO(self.HOST, self.SocketIOPort, LoggingNamespace) as self.sio: self.sio.on('SCISTOUT', self.SIO_callback_SCISTOUT) self.sio.on('PAPICONFIG', self.SIO_callback_PAPICONFIG) self.sio.on('ORTDPACKET', self.SIO_callback_ORTDPACKET) self.request_new_config_from_ORTD() self.sio_count = 0 while self.thread_socket_goOn: self.sio.wait(seconds=1) except: print("Something failed within socket.io") def cb_pause(self): self.lock.acquire() self.thread_goOn = False self.lock.release() self.thread.join() def cb_resume(self): self.thread_goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST, self.SOURCE_PORT)) self.thread.start() def thread_execute(self): time.sleep(2) # TODO: Grrr. do not use sleep for thread sync... #try: if not self.UseSocketIO: self.request_new_config_from_ORTD() goOn = True newData = False signal_values = {} while goOn: try: if not self.sendOnReceivePort: rev = self.sock_recv.recv( 65507 ) # not feasible for network connection other than loopback else: #print ("---- Waiting for data ----") rev, server = self.sock_recv.recvfrom( 65507 ) # not feasible for network connection other than loopback #print ("---- got ----") #print (rev) except socket.timeout: # print('timeout') newData = False except socket.error: print('ORTD got socket error') else: newData = True if newData: self.process_received_package(rev) # check if thread should go on self.lock.acquire() goOn = self.thread_goOn self.lock.release() # Thread ended self.sock_recv.close() def process_received_package(self, rev): SenderId, Counter, SourceId = struct.unpack_from('<iii', rev) if SourceId == -1 and len(self.blocks) > 0: # data stream finished self.process_finished_action(SourceId, rev) self.signal_values = {} if SourceId >= 0 and len(self.blocks) > 0: # got data stream self.process_data_stream(SourceId, rev) if SourceId == -2: # new config in ORTD available # send trigger to get new config self.request_new_config_from_ORTD() self.config_complete = False self.config_buffer = {} if SourceId == -100: self.PAPI_SIMULINK_BLOCK = True # got data stream from the PaPI-Simulink Block self.process_papi_data_stream(rev) if SourceId == -4: self.PAPI_SIMULINK_BLOCK = False # new configItem # print("Part of a new configuration"); # receive new config item and execute cfg in PaPI # unpack package i = 16 # Offset: 4 ints unp = '' while i < len(rev): unp = unp + str(struct.unpack_from('<s', rev, i)[0])[2] i += 1 if int(Counter) not in self.config_buffer: self.config_buffer[int(Counter)] = unp else: if self.config_buffer[int(Counter)] != unp: self.config_buffer = {} # Check counter key series for holes counters = list(self.config_buffer.keys()) counters.sort() i = 1 config_file = '' self.config_complete = True for c in counters: if i == c: config_file += self.config_buffer[c] i += 1 else: self.config_complete = False break if self.config_complete: if not self.check_and_process_cfg(config_file): self.start_timeout_timer() else: self.stop_timeout_timer() else: self.start_timeout_timer() def start_timeout_timer(self): if not self.timer_active: self.timer = Timer(3, self.callback_timeout_timer) self.timer.start() self.timer_active = True else: self.timer.cancel() self.timer = Timer(3, self.callback_timeout_timer) self.timer.start() def stop_timeout_timer(self): if self.timer_active: self.timer.cancel() self.timer_active = False #self.config_buffer = {} def callback_timeout_timer(self): print('ORTD_PLUGIN: Config timeout, requesting a new config') self.timer_active = False self.config_buffer = {} self.request_new_config_from_ORTD() def request_new_config_from_ORTD(self): Counter = 1 data = struct.pack('<iiid', 12, Counter, int(-3), float(0)) if self.UseSocketIO: print("Requesting config via socket.io") self.sio.emit('ORTDPACKET', base64.b64encode(data).decode('ascii')) # TODO test this else: if not self.sendOnReceivePort: self.sock_parameter.sendto(data, (self.HOST, self.OUT_PORT)) else: self.sock_recv.sendto(data, (self.HOST, self.SOURCE_PORT)) def check_and_process_cfg(self, config_file): try: # config completely received # extract new configuration cfg = json.loads(config_file) ORTDSources, ORTDParameters, plToCreate, \ plToClose, subscriptions, paraConnections, activeTab = self.extract_config_elements(cfg) if self.hasInitialConfig and self.onlyInitialConfig: return True self.hasInitialConfig = True self.update_block_list(ORTDSources) self.update_parameter_list(ORTDParameters) self.process_papi_configuration(plToCreate, plToClose, subscriptions, paraConnections, activeTab) return True except ValueError as e: return False def process_papi_configuration(self, toCreate, toClose, subs, paraConnections, activeTab): self.pl_send_new_data( 'ControllerSignals', [1], { 'ControlSignalReset': 1, 'ControlSignalCreate': None, 'ControlSignalSub': None, 'ControllerSignalParameter': None, 'ControllerSignalClose': None, 'ActiveTab': None }) self.pl_send_new_data( 'ControllerSignals', [1], { 'ControlSignalReset': 0, 'ControlSignalCreate': toCreate, 'ControlSignalSub': subs, 'ControllerSignalParameter': paraConnections, 'ControllerSignalClose': toClose, 'ActiveTab': activeTab }) def parse_json_stream(self, stream): decoder = json.JSONDecoder() while stream: obj, idx = decoder.raw_decode(stream) yield obj stream = stream[idx:].lstrip() def update_parameter_list(self, ORTDParameter): newList = {} for para_id in ORTDParameter: para_name = ORTDParameter[para_id]['ParameterName'] if para_name in self.parameters: para_object = self.parameters.pop(para_name) else: val_count = int(ORTDParameter[para_id]['NValues']) opt_object = OptionalObject(para_id, val_count) if "initial_value" in ORTDParameter[para_id]: val = ORTDParameter[para_id]['initial_value'] if val_count > 1: val = val[1:-1] init_value = list(map(float, val.split(','))) else: init_value = float(val) else: init_value = 0 para_object = DParameter(para_name, default=str(init_value), OptionalObject=opt_object) self.pl_send_new_parameter_list([para_object]) newList[para_name] = para_object toDeleteDict = self.parameters self.parameters = newList for par in toDeleteDict: self.pl_send_delete_parameter(par) def update_block_list(self, ORTDSources): #self.block_id = self.block_id +1 #newBlock = DBlock('SourceGroup'+str(self.block_id)) #self.blocks['SourceGroup'+str(self.block_id)] = newBlock if 'SourceGroup0' in self.blocks: self.pl_send_delete_block('SourceGroup0') newBlock = DBlock('SourceGroup0') self.blocks['SourceGroup0'] = newBlock self.Sources = ORTDSources keys = list(self.Sources.keys()) for key in keys: Source = self.Sources[key] sig_name = Source['SourceName'] newBlock.add_signal(DSignal(sig_name)) self.pl_send_new_block_list([newBlock]) # Remove BLOCKS #if 'SourceGroup'+str(self.block_id-1) in self.blocks: #self.pl_send_delete_block(self.blocks.pop('SourceGroup'+str(self.block_id-1)).name) def process_papi_data_stream(self, rev): timestamp = None offset = 4 * 4 for i in range(len(self.Sources)): try: val = [] # offset += i*(4+4+4) # Get current signal ID: # signal_id,data = struct.unpack_from('<id', rev, offset) signal_id, data = struct.unpack_from('<id', rev, offset) # print('Offset=' + str(offset)) # # print('SignalID: ' + str(signal_id)) # print('Data: ' + str(data)) if str(signal_id) in self.Sources: Source = self.Sources[str(signal_id)] NValues = int(Source['NValues_send']) # print("NValues : " + str(NValues)) #print("Offset:" + str(offset)) offset += 4 for n in range(NValues): # print('#Value=' + str(n)) # print('Offset=' + str(offset)) try: data = struct.unpack_from('<d', rev, offset)[0] # print('Data=' + str(data)) val.append(data) except struct.error: # print(sys.exc_info()[0]) # print('!!!! except !!!!') val.append(0) offset += 8 # print('Data: ' + str(val)) # if NValues > 1: # signal_id,data = struct.unpack_from('<id%sd' %NValues, rev, offset) # offset += (NValues-1)*(4+4) if self.Sources[str(signal_id)]["SourceName"] == "time": timestamp = val[0] self.signal_values[signal_id] = val #print("Signal: " + str(signal_id) + " Data: " + str(data) ); except struct.error: print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno)) print(sys.exc_info()[1]) print("Can't unpack.") self.process_finished_action(-1, None, timestamp) def process_data_stream(self, SourceId, rev): # Received a data packet # Lookup the Source behind the given SourceId if str(SourceId) in self.Sources: Source = self.Sources[str(SourceId)] NValues = int(Source['NValues_send']) # Read NVales from the received packet val = [] for i in range(NValues): try: val.append(struct.unpack_from('<d', rev, 3 * 4 + i * 8)[0]) except: val.append(0) self.signal_values[SourceId] = val else: dp_info = self.pl_get_dplugin_info() print('ORTD_PLUGIN - ' + dp_info.uname + ': received data with an unknown id (' + str(SourceId) + ')') def process_finished_action(self, SourceId, rev, timestamp=None): if SourceId == -1: # unpack group ID # GroupId = struct.unpack_from('<i', rev, 3 * 4)[0] self.t += 1.0 keys = list(self.signal_values.keys()) keys.sort( ) # REMARK: Die liste keys nur einmal sortieren; bei initialisierung signals_to_send = {} for key in keys: if str(key) in self.Sources: sig_name = self.Sources[str(key)]['SourceName'] signals_to_send[sig_name] = self.signal_values[key] if len(list(self.blocks.keys())) > 0: block = list(self.blocks.keys())[0] if len(self.blocks[block].signals) == len(signals_to_send) + 1: if timestamp is None: self.pl_send_new_data(block, [self.t], signals_to_send) else: self.pl_send_new_data(block, [timestamp], signals_to_send) def cb_execute(self, Data=None, block_name=None, plugin_uname=None): raise Exception('Should not be called!') def cb_set_parameter(self, name, value): if name in self.parameters: parameter = self.parameters[name] Pid = parameter.OptionalObject.ORTD_par_id Counter = 111 if value is not None: data = None # get values in float from string valueCast = ast.literal_eval(value) # check is it is a list, if not, cast to list if not isinstance(valueCast, list): valueCast = [valueCast] if self.PAPI_SIMULINK_BLOCK: data = struct.pack('<iii%sd' % len(valueCast), 12, Counter, int(Pid), *valueCast) else: data = struct.pack('<iii%sd' % len(valueCast), 12, Counter, int(Pid), *valueCast) #if isinstance(valueCast, list): #data += struct.pack('%sd' %len(valueCast),*valueCast) # for i in range(0,len(valueCast)): # data += struct.pack('<d',valueCast[i]) #else: # data += struct.pack('d',float(value)) if self.UseSocketIO: print("Setting parameter via socket.io") self.sio.emit('ORTDPACKET', base64.b64encode(data).decode('ascii')) # TODO test this else: if not self.sendOnReceivePort: self.sock_parameter.sendto(data, (self.HOST, self.OUT_PORT)) else: self.sock_recv.sendto(data, (self.HOST, self.SOURCE_PORT)) else: if name == 'consoleIn': self.sio.emit('ConsoleCommand', { 'ConsoleId': '1', 'Data': value }) def cb_quit(self): self.lock.acquire() self.thread_goOn = False self.lock.release() self.thread.join() if not self.sendOnReceivePort: self.sock_parameter.close() print('ORTD-Plugin will quit') def cb_plugin_meta_updated(self): pass def plconf(self): cfg = {} subs = {} paras = {} close = {} if 'PaPIConfig' in self.ProtocolConfig: if 'ToCreate' in self.ProtocolConfig['PaPIConfig']: cfg = self.ProtocolConfig['PaPIConfig']['ToCreate'] if 'ToSub' in self.ProtocolConfig['PaPIConfig']: subs = self.ProtocolConfig['PaPIConfig']['ToSub'] if 'ToControl' in self.ProtocolConfig['PaPIConfig']: paras = self.ProtocolConfig['PaPIConfig']['ToControl'] if 'ToClose' in self.ProtocolConfig['PaPIConfig']: close = self.ProtocolConfig['PaPIConfig']['ToClose'] return cfg, subs, paras, close def extract_config_elements(self, configuration): plToCreate = {} subscriptions = {} paraConnections = {} plToClose = {} ORTDSources = {} ORTDParameters = {} activeTab = 'PaPI-Tab' if 'PaPIConfig' in configuration: if 'ToCreate' in configuration['PaPIConfig']: plToCreate = configuration['PaPIConfig']['ToCreate'] if 'ToSub' in configuration['PaPIConfig']: subscriptions = configuration['PaPIConfig']['ToSub'] if 'ToControl' in configuration['PaPIConfig']: paraConnections = configuration['PaPIConfig']['ToControl'] if 'ToClose' in configuration['PaPIConfig']: plToClose = configuration['PaPIConfig']['ToClose'] if 'ActiveTab' in configuration['PaPIConfig']: activeTab = configuration['PaPIConfig']['tab'] if 'SourcesConfig' in configuration: ORTDSources = configuration['SourcesConfig'] if 'ParametersConfig' in configuration: ORTDParameters = configuration['ParametersConfig'] return ORTDSources, ORTDParameters, plToCreate, plToClose, subscriptions, paraConnections, activeTab
class Fourier_Rect_MOD(iop_base): max_approx = 20 amax = 20 def cb_initialize_plugin(self): self.t = 0 self.amax = Fourier_Rect_MOD.amax self.amplitude = 1 self.max_approx = Fourier_Rect_MOD.max_approx self.freq = 1 self.vec = numpy.ones(self.amax* ( self.max_approx + 1) ) print(['Fourier: process id: ',os.getpid()] ) self.HOST = "130.149.155.73" self.PORT = 9999 # SOCK_DGRAM is the socket type to use for UDP sockets self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setblocking(0) self.block1 = DBlock('Rectangle') for i in range(1,self.max_approx): self.block1.add_signal(DSignal('rect'+str(i))) self.pl_send_new_block_list([self.block1]) self.pl_set_event_trigger_mode(True) self.goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST,self.PORT) ) self.thread.start() return True def cb_pause(self): self.goOn = False self.thread.join() def cb_resume(self): self.goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST,self.PORT) ) self.thread.start() def thread_execute(self,host,port): #self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #self.sock.setblocking(0) vec = numpy.zeros( (self.max_approx, (self.amax) )) while self.goOn: self.sock.sendto(b'GET', (self.HOST, self.PORT) ) try: received = self.sock.recv(60000) except socket.error: pass else: data = pickle.loads(received) vech = {} t = data[0*self.amax:(0+1)*self.amax] for i in range(self.max_approx): vech['rect'+str(i)] = data[i*self.amax:(i+1)*self.amax] self.pl_send_new_data('Rectangle', t, vech) time.sleep(0.001*self.amax ) def cb_execute(self, Data=None, block_name = None, plugin_uname = None): print("EXECUTE FUNC") pass def cb_set_parameter(self, name, value): pass def cb_quit(self): self.goOn = False self.thread.join() def cb_plugin_meta_updated(self): pass def cb_get_plugin_configuration(self): return {}
def cb_initialize_plugin(self): # -------------------------------- # Step 0: Read documentation: http://tub-control.github.io/PaPI/ # -------------------------------- # -------------------------------- # Step 1: Read configuration items (startup cfg) # OPTIONAL # -------------------------------- # Please read the Documentation of pl_get_config_element() to understand what is happening here. # e.g. a configuration item named 'offset' is read. offset = self.pl_get_config_element('offset') offset = float(offset) if offset is not None else 0 # -------------------------------- # Step 2:Define blocks for output signals and define signals of blocks! # OPTIONAL # -------------------------------- # Here: block called CPU_LOAD with 2 signals for Core1 and Core2 blockLoad = DBlock('CPU_LOAD') sig_core1 = DSignal('Load_C1') sig_core2 = DSignal('Load_C2') blockLoad.add_signal(sig_core1) blockLoad.add_signal(sig_core2) self.pl_send_new_block_list([blockLoad]) # -------------------------------- # Step 3: Define parameter that are offered to PaPI # OPTIONAL # Sub-Step 1: Create Parameter Object # Sub-Step 2: Send list of Parameter Objects created to PaPI # -------------------------------- # use self. to remember the parameter object in this class/context for own usage! # e.g. parameter named parameterName1 is created! # Refer to the Doc of DParameter to read about advanced usages! self. parameter1 = DParameter('parameterName1') self. parameter2 = DParameter('parameterName2') self.pl_send_new_parameter_list([self.parameter1, self.parameter1]) # -------------------------------- # Step 4: Set the plugin trigger mode # OPTIONAL # In most cases for IOP you will leave it default, for DPP you will set it to true # Default will mean, that PaPI will decide on it. # -------------------------------- self.pl_set_event_trigger_mode('default') # -------------------------------- # Step 5: Developer and Plugin specific configuration # OPTIONAL # -------------------------------- # -------------------------------- # Step 6: Return Value # OBLIGATORY # Return True if the everything is alright! # False will lead to PaPI not starting this Plugin! # -------------------------------- return True
class UDP_Plugin(iop_base): def cb_get_plugin_configuration(self): config = { 'address': { 'value': '127.0.0.1', 'advanced': '1' }, 'source_port': { 'value': '20000', 'advanced': '1' }, 'out_port': { 'value': '20001', 'advanced': '1' }, 'Cfg_Path': { 'value': '/home/control/PycharmProjects/PaPI/data_sources/ORTD/DataSourceExample/ProtocollConfig.json', 'type': 'file', 'advanced': '0' }, 'SeparateSignals': { 'value': '0', 'advanced': '1' }, 'SendOnReceivePort': { 'value': '0', # NOTE: chnage back to 0 'advanced': '1', 'display_text': 'Use same port for send and receive' }, "UseSocketIO" : { 'value' : '0', # NOTE: change back to 0 !! 'advanced' : '1', 'tooltip' : 'Use socket.io connection to node.js target-server', 'type' : 'bool' }, 'socketio_port': { 'value': '8091', 'advanced': '1' }, "OnlyInitialConfig" : { 'value' :'0', 'tooltip' : 'Use only first configuration, ignore further configurations.', 'type' : 'bool' } } return config def cb_initialize_plugin(self): print('ORTD', self.__id__, ':process id', os.getpid()) self.config = self.pl_get_current_config_ref() # open UDP self.HOST = self.config['address']['value'] self.SOURCE_PORT = int(self.config['source_port']['value']) self.OUT_PORT = int(self.config['out_port']['value']) self.LOCALBIND_HOST = '' # config['source_address']['value'] #CK self.sendOnReceivePort = True if self.config['SendOnReceivePort']['value'] == '1' else False self.UseSocketIO = True if self.config['UseSocketIO']['value'] == '1' else False if self.UseSocketIO: self.SocketIOPort = int(self.config['socketio_port']['value']) #self.sendOnReceivePort = True # NOTE: remove this #self.UseSocketIO = True # NOTE: remove this print ("SendOnReceivePort = ", self.sendOnReceivePort) print ("UseSocketIO = ", self.UseSocketIO) self.PAPI_SIMULINK_BLOCK = False self.separate = int(self.config['SeparateSignals']['value']) self.onlyInitialConfig = self.config['OnlyInitialConfig']['value'] == '1' self.hasInitialConfig = False if (not self.sendOnReceivePort): # SOCK_DGRAM is the socket type to use for UDP sockets self.sock_parameter = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock_parameter.setblocking(1) self.ControlBlock = DBlock('ControllerSignals') self.ControlBlock.add_signal(DSignal('ControlSignalReset')) self.ControlBlock.add_signal(DSignal('ControlSignalCreate')) self.ControlBlock.add_signal(DSignal('ControlSignalSub')) self.ControlBlock.add_signal(DSignal('ControllerSignalParameter')) self.ControlBlock.add_signal(DSignal('ControllerSignalClose')) self.ControlBlock.add_signal(DSignal('ActiveTab')) self.pl_send_new_block_list([self.ControlBlock]) self.t = 0 self.pl_set_event_trigger_mode(True) self.sock_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if (not self.sendOnReceivePort): self.sock_recv.bind((self.LOCALBIND_HOST, self.SOURCE_PORT)) # CK print("UDP_Plugin-plugin listening on: ", self.LOCALBIND_HOST, ":", self.SOURCE_PORT) #CK else: print ("---- Using client UDP mode (not binding to a port) ----") self.sock_recv.settimeout(1) self.thread_goOn = True self.lock = threading.Lock() self.thread = threading.Thread(target=self.thread_execute) self.thread.start() if self.UseSocketIO: print ("Using socket.io connection on port", self.SocketIOPort) self.thread_socket_goOn = True self.thread_socketio = threading.Thread(target=self.thread_socketio_execute) self.blocks = {} self.Sources = {} self.parameters = {} self.signal_values = {} self.block_id = 0 self.config_complete = False self.config_buffer = {} self.timer = Timer(3,self.callback_timeout_timer) self.timer_active = False self.ConsoleBlock = DBlock('ConsoleSignals') self.ConsoleBlock.add_signal(DSignal('MainSignal')) self.pl_send_new_block_list([self.ConsoleBlock]) self.consoleIn = DParameter('consoleIn',default='') self.pl_send_new_parameter_list([self.consoleIn]) if self.UseSocketIO: self.thread_socketio.start() return True def SIO_callback_SCISTOUT(self, data): # Got a chunk of data from a console interface in the target server self.sio_count += 1 self.pl_send_new_data(self.ConsoleBlock.name, [self.sio_count], {'MainSignal':data['Data']}) def SIO_callback_PAPICONFIG(self, data): # Got a new PaPI plugin configuration in JSON-format via socket.io connection # currently the config is transmitted via ORTD packets that may also be encapsulated into socket.io # added 12.8.15, CK print ("Got a new config in JSON/socket.io format") print (data) self.check_and_process_cfg(data) # TODO: Test this def SIO_callback_ORTDPACKET(self, data): # Got an encapsulated packet from ORTD, not transfered via UDP but encapsulated within the socket.io connection #print ("Got data packet from ORTD via socket.io") #print (data) self.process_received_package(base64.b64decode(data)) # data must be a binary blob def thread_socketio_execute(self): #self.sio = SocketIO('localhost', 8091, LoggingNamespace) #self.sio.on('SCISTOUT',self.callback_SCISTOUT) while True: try: with SocketIO(self.HOST, self.SocketIOPort, LoggingNamespace) as self.sio: self.sio.on('SCISTOUT',self.SIO_callback_SCISTOUT) self.sio.on('PAPICONFIG',self.SIO_callback_PAPICONFIG) self.sio.on('ORTDPACKET',self.SIO_callback_ORTDPACKET) self.request_new_config_from_ORTD() self.sio_count = 0 while self.thread_socket_goOn: self.sio.wait(seconds=1) except: print("Something failed within socket.io") def cb_pause(self): self.lock.acquire() self.thread_goOn = False self.lock.release() self.thread.join() def cb_resume(self): self.thread_goOn = True self.thread = threading.Thread(target=self.thread_execute, args=(self.HOST, self.SOURCE_PORT)) self.thread.start() def thread_execute(self): time.sleep(2) # TODO: Grrr. do not use sleep for thread sync... #try: if not self.UseSocketIO: self.request_new_config_from_ORTD() goOn = True newData = False signal_values = {} while goOn: try: if not self.sendOnReceivePort: rev = self.sock_recv.recv(65507) # not feasible for network connection other than loopback else: #print ("---- Waiting for data ----") rev, server = self.sock_recv.recvfrom(65507) # not feasible for network connection other than loopback #print ("---- got ----") #print (rev) except socket.timeout: # print('timeout') newData = False except socket.error: print('ORTD got socket error') else: newData = True if newData: self.process_received_package(rev) # check if thread should go on self.lock.acquire() goOn = self.thread_goOn self.lock.release() # Thread ended self.sock_recv.close() def process_received_package(self, rev): SenderId, Counter, SourceId = struct.unpack_from('<iii', rev) if SourceId == -1 and len(self.blocks) > 0: # data stream finished self.process_finished_action(SourceId, rev) self.signal_values = {} if SourceId >= 0 and len(self.blocks) > 0: # got data stream self.process_data_stream(SourceId, rev) if SourceId == -2: # new config in ORTD available # send trigger to get new config self.request_new_config_from_ORTD() self.config_complete = False self.config_buffer = {} if SourceId == -100: self.PAPI_SIMULINK_BLOCK = True # got data stream from the PaPI-Simulink Block self.process_papi_data_stream(rev) if SourceId == -4: self.PAPI_SIMULINK_BLOCK = False # new configItem # print("Part of a new configuration"); # receive new config item and execute cfg in PaPI # unpack package i = 16 # Offset: 4 ints unp = '' while i < len(rev): unp = unp + str(struct.unpack_from('<s',rev,i)[0])[2] i += 1 if int(Counter) not in self.config_buffer: self.config_buffer[int(Counter)] = unp else: if self.config_buffer[int(Counter)] != unp: self.config_buffer = {} # Check counter key series for holes counters = list(self.config_buffer.keys()) counters.sort() i = 1 config_file = '' self.config_complete = True for c in counters: if i == c: config_file += self.config_buffer[c] i += 1 else: self.config_complete = False break if self.config_complete: if not self.check_and_process_cfg(config_file): self.start_timeout_timer() else: self.stop_timeout_timer() else: self.start_timeout_timer() def start_timeout_timer(self): if not self.timer_active: self.timer = Timer(3,self.callback_timeout_timer) self.timer.start() self.timer_active = True else: self.timer.cancel() self.timer = Timer(3,self.callback_timeout_timer) self.timer.start() def stop_timeout_timer(self): if self.timer_active: self.timer.cancel() self.timer_active = False #self.config_buffer = {} def callback_timeout_timer(self): print('ORTD_PLUGIN: Config timeout, requesting a new config') self.timer_active = False self.config_buffer = {} self.request_new_config_from_ORTD() def request_new_config_from_ORTD(self): Counter = 1 data = struct.pack('<iiid', 12, Counter, int(-3), float(0)) if self.UseSocketIO: print ("Requesting config via socket.io") self.sio.emit('ORTDPACKET', base64.b64encode(data).decode('ascii') ) # TODO test this else: if not self.sendOnReceivePort: self.sock_parameter.sendto(data, (self.HOST, self.OUT_PORT)) else: self.sock_recv.sendto(data, (self.HOST, self.SOURCE_PORT)) def check_and_process_cfg(self, config_file): try: # config completely received # extract new configuration cfg = json.loads(config_file) ORTDSources, ORTDParameters, plToCreate, \ plToClose, subscriptions, paraConnections, activeTab = self.extract_config_elements(cfg) if self.hasInitialConfig and self.onlyInitialConfig: return True self.hasInitialConfig = True self.update_block_list(ORTDSources) self.update_parameter_list(ORTDParameters) self.process_papi_configuration(plToCreate, plToClose, subscriptions, paraConnections, activeTab) return True except ValueError as e: return False def process_papi_configuration(self, toCreate, toClose, subs, paraConnections, activeTab): self.pl_send_new_data('ControllerSignals', [1], {'ControlSignalReset': 1, 'ControlSignalCreate':None, 'ControlSignalSub':None, 'ControllerSignalParameter':None, 'ControllerSignalClose':None, 'ActiveTab': None }) self.pl_send_new_data('ControllerSignals', [1], {'ControlSignalReset':0, 'ControlSignalCreate':toCreate, 'ControlSignalSub':subs, 'ControllerSignalParameter':paraConnections, 'ControllerSignalClose':toClose, 'ActiveTab': activeTab}) def parse_json_stream(self,stream): decoder = json.JSONDecoder() while stream: obj, idx = decoder.raw_decode(stream) yield obj stream = stream[idx:].lstrip() def update_parameter_list(self, ORTDParameter): newList ={} for para_id in ORTDParameter: para_name = ORTDParameter[para_id]['ParameterName'] if para_name in self.parameters: para_object = self.parameters.pop(para_name) else: val_count = int(ORTDParameter[para_id]['NValues']) opt_object = OptionalObject(para_id, val_count) if "initial_value" in ORTDParameter[para_id]: val = ORTDParameter[para_id]['initial_value'] if val_count > 1: val = val[1:-1] init_value = list(map(float,val.split(','))) else: init_value = float(val) else: init_value = 0 para_object = DParameter(para_name, default=str(init_value), OptionalObject=opt_object) self.pl_send_new_parameter_list([para_object]) newList[para_name] = para_object toDeleteDict = self.parameters self.parameters = newList for par in toDeleteDict: self.pl_send_delete_parameter(par) def update_block_list(self,ORTDSources): #self.block_id = self.block_id +1 #newBlock = DBlock('SourceGroup'+str(self.block_id)) #self.blocks['SourceGroup'+str(self.block_id)] = newBlock if 'SourceGroup0' in self.blocks: self.pl_send_delete_block('SourceGroup0') newBlock = DBlock('SourceGroup0') self.blocks['SourceGroup0'] = newBlock self.Sources = ORTDSources keys = list(self.Sources.keys()) for key in keys: Source = self.Sources[key] sig_name = Source['SourceName'] newBlock.add_signal(DSignal(sig_name)) self.pl_send_new_block_list([newBlock]) # Remove BLOCKS #if 'SourceGroup'+str(self.block_id-1) in self.blocks: #self.pl_send_delete_block(self.blocks.pop('SourceGroup'+str(self.block_id-1)).name) def process_papi_data_stream(self, rev): timestamp = None offset = 4*4 for i in range(len(self.Sources)): try: val = [] # offset += i*(4+4+4) # Get current signal ID: # signal_id,data = struct.unpack_from('<id', rev, offset) signal_id, data = struct.unpack_from('<id', rev, offset) # print('Offset=' + str(offset)) # # print('SignalID: ' + str(signal_id)) # print('Data: ' + str(data)) if str(signal_id) in self.Sources: Source = self.Sources[str(signal_id)] NValues = int(Source['NValues_send']) # print("NValues : " + str(NValues)) #print("Offset:" + str(offset)) offset += 4 for n in range(NValues): # print('#Value=' + str(n)) # print('Offset=' + str(offset)) try: data = struct.unpack_from('<d', rev, offset)[0] # print('Data=' + str(data)) val.append(data) except struct.error: # print(sys.exc_info()[0]) # print('!!!! except !!!!') val.append(0) offset += 8 # print('Data: ' + str(val)) # if NValues > 1: # signal_id,data = struct.unpack_from('<id%sd' %NValues, rev, offset) # offset += (NValues-1)*(4+4) if self.Sources[str(signal_id)]["SourceName"] == "time": timestamp = val[0] self.signal_values[signal_id] = val #print("Signal: " + str(signal_id) + " Data: " + str(data) ); except struct.error: print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno)) print(sys.exc_info()[1]) print("Can't unpack.") self.process_finished_action(-1,None, timestamp) def process_data_stream(self, SourceId, rev): # Received a data packet # Lookup the Source behind the given SourceId if str(SourceId) in self.Sources: Source = self.Sources[str(SourceId)] NValues = int(Source['NValues_send']) # Read NVales from the received packet val = [] for i in range(NValues): try: val.append(struct.unpack_from('<d', rev, 3 * 4 + i * 8)[0]) except: val.append(0) self.signal_values[SourceId] = val else: dp_info = self.pl_get_dplugin_info() print('ORTD_PLUGIN - '+dp_info.uname+': received data with an unknown id ('+str(SourceId)+')') def process_finished_action(self, SourceId, rev, timestamp=None): if SourceId == -1: # unpack group ID # GroupId = struct.unpack_from('<i', rev, 3 * 4)[0] self.t += 1.0 keys = list(self.signal_values.keys()) keys.sort() # REMARK: Die liste keys nur einmal sortieren; bei initialisierung signals_to_send = {} for key in keys: if str(key) in self.Sources: sig_name = self.Sources[str(key)]['SourceName'] signals_to_send[sig_name] = self.signal_values[key] if len( list(self.blocks.keys()) ) >0: block = list(self.blocks.keys())[0] if len(self.blocks[block].signals) == len(signals_to_send)+1: if timestamp is None: self.pl_send_new_data(block, [self.t], signals_to_send ) else: self.pl_send_new_data(block, [timestamp], signals_to_send ) def cb_execute(self, Data=None, block_name = None, plugin_uname = None): raise Exception('Should not be called!') def cb_set_parameter(self, name, value): if name in self.parameters: parameter = self.parameters[name] Pid = parameter.OptionalObject.ORTD_par_id Counter = 111 if value is not None: data = None # get values in float from string valueCast = ast.literal_eval(value) # check is it is a list, if not, cast to list if not isinstance(valueCast,list): valueCast = [valueCast] if self.PAPI_SIMULINK_BLOCK: data = struct.pack('<iii%sd' %len(valueCast), 12, Counter, int(Pid),*valueCast) else: data = struct.pack('<iii%sd' %len(valueCast), 12, Counter, int(Pid),*valueCast) #if isinstance(valueCast, list): #data += struct.pack('%sd' %len(valueCast),*valueCast) # for i in range(0,len(valueCast)): # data += struct.pack('<d',valueCast[i]) #else: # data += struct.pack('d',float(value)) if self.UseSocketIO: print ("Setting parameter via socket.io") self.sio.emit('ORTDPACKET', base64.b64encode(data).decode('ascii') ) # TODO test this else: if not self.sendOnReceivePort: self.sock_parameter.sendto(data, (self.HOST, self.OUT_PORT)) else: self.sock_recv.sendto(data, (self.HOST, self.SOURCE_PORT)) else: if name == 'consoleIn': self.sio.emit('ConsoleCommand', { 'ConsoleId' : '1' , 'Data' : value }) def cb_quit(self): self.lock.acquire() self.thread_goOn = False self.lock.release() self.thread.join() if not self.sendOnReceivePort: self.sock_parameter.close() print('ORTD-Plugin will quit') def cb_plugin_meta_updated(self): pass def plconf(self): cfg = {} subs = {} paras = {} close = {} if 'PaPIConfig' in self.ProtocolConfig: if 'ToCreate' in self.ProtocolConfig['PaPIConfig']: cfg = self.ProtocolConfig['PaPIConfig']['ToCreate'] if 'ToSub' in self.ProtocolConfig['PaPIConfig']: subs = self.ProtocolConfig['PaPIConfig']['ToSub'] if 'ToControl' in self.ProtocolConfig['PaPIConfig']: paras = self.ProtocolConfig['PaPIConfig']['ToControl'] if 'ToClose' in self.ProtocolConfig['PaPIConfig']: close = self.ProtocolConfig['PaPIConfig']['ToClose'] return cfg, subs, paras, close def extract_config_elements(self, configuration): plToCreate = {} subscriptions = {} paraConnections = {} plToClose = {} ORTDSources = {} ORTDParameters = {} activeTab = 'PaPI-Tab' if 'PaPIConfig' in configuration: if 'ToCreate' in configuration['PaPIConfig']: plToCreate = configuration['PaPIConfig']['ToCreate'] if 'ToSub' in configuration['PaPIConfig']: subscriptions = configuration['PaPIConfig']['ToSub'] if 'ToControl' in configuration['PaPIConfig']: paraConnections = configuration['PaPIConfig']['ToControl'] if 'ToClose' in configuration['PaPIConfig']: plToClose = configuration['PaPIConfig']['ToClose'] if 'ActiveTab' in configuration['PaPIConfig']: activeTab = configuration['PaPIConfig']['tab'] if 'SourcesConfig' in configuration: ORTDSources = configuration['SourcesConfig'] if 'ParametersConfig' in configuration: ORTDParameters = configuration['ParametersConfig'] return ORTDSources, ORTDParameters, plToCreate, plToClose, subscriptions, paraConnections, activeTab
def cb_initialize_plugin(self): print('ORTD', self.__id__, ':process id', os.getpid()) self.config = self.pl_get_current_config_ref() # open UDP self.HOST = self.config['address']['value'] self.SOURCE_PORT = int(self.config['source_port']['value']) self.OUT_PORT = int(self.config['out_port']['value']) self.LOCALBIND_HOST = '' # config['source_address']['value'] #CK self.sendOnReceivePort = True if self.config['SendOnReceivePort']['value'] == '1' else False self.UseSocketIO = True if self.config['UseSocketIO']['value'] == '1' else False if self.UseSocketIO: self.SocketIOPort = int(self.config['socketio_port']['value']) #self.sendOnReceivePort = True # NOTE: remove this #self.UseSocketIO = True # NOTE: remove this print ("SendOnReceivePort = ", self.sendOnReceivePort) print ("UseSocketIO = ", self.UseSocketIO) self.PAPI_SIMULINK_BLOCK = False self.separate = int(self.config['SeparateSignals']['value']) self.onlyInitialConfig = self.config['OnlyInitialConfig']['value'] == '1' self.hasInitialConfig = False if (not self.sendOnReceivePort): # SOCK_DGRAM is the socket type to use for UDP sockets self.sock_parameter = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock_parameter.setblocking(1) self.ControlBlock = DBlock('ControllerSignals') self.ControlBlock.add_signal(DSignal('ControlSignalReset')) self.ControlBlock.add_signal(DSignal('ControlSignalCreate')) self.ControlBlock.add_signal(DSignal('ControlSignalSub')) self.ControlBlock.add_signal(DSignal('ControllerSignalParameter')) self.ControlBlock.add_signal(DSignal('ControllerSignalClose')) self.ControlBlock.add_signal(DSignal('ActiveTab')) self.pl_send_new_block_list([self.ControlBlock]) self.t = 0 self.pl_set_event_trigger_mode(True) self.sock_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if (not self.sendOnReceivePort): self.sock_recv.bind((self.LOCALBIND_HOST, self.SOURCE_PORT)) # CK print("UDP_Plugin-plugin listening on: ", self.LOCALBIND_HOST, ":", self.SOURCE_PORT) #CK else: print ("---- Using client UDP mode (not binding to a port) ----") self.sock_recv.settimeout(1) self.thread_goOn = True self.lock = threading.Lock() self.thread = threading.Thread(target=self.thread_execute) self.thread.start() if self.UseSocketIO: print ("Using socket.io connection on port", self.SocketIOPort) self.thread_socket_goOn = True self.thread_socketio = threading.Thread(target=self.thread_socketio_execute) self.blocks = {} self.Sources = {} self.parameters = {} self.signal_values = {} self.block_id = 0 self.config_complete = False self.config_buffer = {} self.timer = Timer(3,self.callback_timeout_timer) self.timer_active = False self.ConsoleBlock = DBlock('ConsoleSignals') self.ConsoleBlock.add_signal(DSignal('MainSignal')) self.pl_send_new_block_list([self.ConsoleBlock]) self.consoleIn = DParameter('consoleIn',default='') self.pl_send_new_parameter_list([self.consoleIn]) if self.UseSocketIO: self.thread_socketio.start() return True