How to use _NewSection method in autotest

Best Python code snippet using autotest_python

CoovaChilliLib.py.in

Source:CoovaChilliLib.py.in Github

copy

Full Screen

1#!/usr/bin/python2"""3 CoovaChilli Python Library4 Copyright (C) 2009 David Bird <david@coova.com>5 This program is free software; you can redistribute it and/or modify6 it under the terms of the GNU General Public License as published by7 the Free Software Foundation; either version 2 of the License, or8 (at your option) any later version.9 This program is distributed in the hope that it will be useful,10 but WITHOUT ANY WARRANTY; without even the implied warranty of11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 GNU General Public License for more details.13 You should have received a copy of the GNU General Public License14 along with this program; if not, write to the Free Software15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA16"""17import pygtk18pygtk.require('2.0')19import os20import gtk21import time22import string23import socket24import fcntl25import struct26import array27import gobject28import ConfigParser29import subprocess30class EntryDialog(gtk.Dialog):31 def __init__(self, message="", default_text='', modal=True):32 gtk.Dialog.__init__(self)33 self.connect("destroy", self.quit)34 self.connect("delete_event", self.quit)35 if modal:36 self.set_modal(gtk.TRUE)37 box = gtk.VBox(spacing=10)38 box.set_border_width(10)39 self.vbox.pack_start(box)40 box.show()41 if message:42 label = gtk.Label(message)43 box.pack_start(label)44 label.show()45 self.entry = gtk.Entry()46 self.entry.set_text(default_text)47 box.pack_start(self.entry)48 self.entry.show()49 self.entry.grab_focus()50 button = gtk.Button("OK")51 button.connect("clicked", self.click)52 button.set_flags(gtk.CAN_DEFAULT)53 self.action_area.pack_start(button)54 button.show()55 button.grab_default()56 button = gtk.Button("Cancel")57 button.connect("clicked", self.quit)58 button.set_flags(gtk.CAN_DEFAULT)59 self.action_area.pack_start(button)60 button.show()61 self.ret = None62 def quit(self, w=None, event=None):63 self.hide()64 self.destroy()65 gtk.main_quit()66 def click(self, button):67 self.ret = self.entry.get_text()68 self.quit()69class CoovaChilli:70 About = "<b>About:</b>\nCoovaChilli is an open-source access\ncontroller server. After assigning each\ndevice with an IP address using DHCP,\nchilli will redirect unauthenticated\nusers to a captive portal.\n\n<b>Created by:</b>\n(c) 2009 David Bird\nhttp://coova.org/\nReleased under GPL"71 Query = '@SBINDIR@/chilli_query'72 Socket = '@VARRUN@/chilli.sock'73 Init = '@SYSCONFDIR@/init.d/chilli'74 DefIni = '@ETCCHILLI@/gui-config-default.ini'75 Ini = '@ETCCHILLI@/gui-config.ini'76 Conf = '@ETCCHILLI@/config'77 Section = '/tmp/hotspot-section'78 Settings = [ 'HS_SSID',79 'HS_NETWORK',80 'HS_NETMASK',81 'HS_UAMPORT',82 'HS_UAMLISTEN',83 'HS_UAMSERVER', 84 'HS_UAMFORMAT', 85 'HS_UAMSERVICE', 86 'HS_UAMSECRET',87 'HS_RADIUS', 88 'HS_RADIUS2', 89 'HS_RADSECRET',90 'HS_UAMALLOW',91 'HS_UAMDOMAINS',92 'HS_USELOCALUSERS',93 'HS_ADMUSR',94 'HS_ADMPWD',95 'HS_LOC_NAME' ]96 Labels = { 'HS_SSID' : gtk.Label( "Hotspot SSID:" ),97 'HS_NETWORK' : gtk.Label( "Network:" ),98 'HS_NETMASK' : gtk.Label( "Netmask:" ),99 'HS_UAMLISTEN' : gtk.Label( "UAM IP Address:" ),100 'HS_UAMSERVER' : gtk.Label( "UAM Server:" ),101 'HS_UAMFORMAT' : gtk.Label( "UAM Redirect URL:" ),102 'HS_UAMSERVICE' : gtk.Label( "UAM Service URL:" ),103 'HS_UAMSECRET' : gtk.Label( "UAM Secret:" ),104 'HS_RADIUS' : gtk.Label( "RADIUS Server 1:" ),105 'HS_RADIUS2' : gtk.Label( "RADIUS Server 2:" ),106 'HS_RADSECRET' : gtk.Label( "Shared Secret:" ),107 'HS_UAMALLOW' : gtk.Label( "UAM Allowed:" ),108 'HS_UAMDOMAINS' : gtk.Label( "UAM Domains:" ),109 'HS_ADMUSR' : gtk.Label( "Admin-User:" ),110 'HS_ADMPWD' : gtk.Label( "Admin-Password:" ) }111 112 Entries = { 'HS_SSID' : gtk.Entry(),113 'HS_NETWORK' : gtk.Entry(),114 'HS_NETMASK' : gtk.Entry(),115 'HS_UAMLISTEN' : gtk.Entry(),116 'HS_UAMSERVER' : gtk.Entry(),117 'HS_UAMFORMAT' : gtk.Entry(),118 'HS_UAMSERVICE' : gtk.Entry(),119 'HS_UAMSECRET' : gtk.Entry(),120 'HS_RADIUS' : gtk.Entry(),121 'HS_RADIUS2' : gtk.Entry(),122 'HS_RADSECRET' : gtk.Entry(),123 'HS_UAMALLOW' : gtk.Entry(),124 'HS_UAMDOMAINS' : gtk.Entry(),125 'HS_ADMUSR' : gtk.Entry(),126 'HS_ADMPWD' : gtk.Entry() }127 128 def saveChilliConfig( self, data=None ):129 configfile = open(self.Conf, 'wb')130 for setting in self.Settings:131 configfile.write(setting+"="+self.conf(setting)+"\n")132 return True133 def clone(self, section):134 for setting in self.Settings:135 self.config.set(section, setting, self.conf(setting))136 return137 def saveConfig( self, data=None ):138 print "Storing configuration changes"139 for setting in self.Settings:140 if self.Entries.get(setting):141 self.config.set(self.section, setting, self.Entries.get(setting).get_text())142 configfile = open(self.Ini, 'wb')143 self.config.write(configfile)144 configfile.close()145 self.saveChilliConfig()146 return True147 def _chilliQuery( self, mac=None ):148 self.sessionsStore.clear()149 if mac != None:150 self.selectedMac = mac151 if self.selectedMac == None:152 self.selectedSession = 0153 self.sesAuth.set_sensitive( False )154 self.sesRelease.set_sensitive( False )155 self.sesBlock.set_sensitive( False )156 self.sessionView.set_markup( '' )157 p = subprocess.Popen([self.Query, self.Socket, "list"], stdout=subprocess.PIPE, close_fds=True)158 i=0159 macNotFound = True160 selectPath = -1161 for line in p.stdout.readlines():162 print line163 s = line.split()164 self.sessionsStore.append([ s[0], s[1] ])165 if self.selectedMac == s[0]:166 macNotFound = False167 selectPath = i168 self.selectedSessionId = s[3]169 color = 'orange'170 if s[2] == 'pass':171 color = 'green'172 if s[2] == 'drop':173 color = 'red'174 markUp = "<b>MAC:</b>: <span color='"+color+"'>"+s[0]+"</span> <b>IP</b>: <span color='"+color+"'>"+s[1]+"</span>\n"175 markUp = markUp + ( "<b>Session Id</b>: <span color='"+color+"'>"+s[3]+"</span> <b>State</b>: <span color='"+color+"'>"+s[2]+"</span>\n" )176 markUp = markUp + ( "<b>Username</b>: <span color='"+color+"'>%s</span>\n" % s[5] )177 markUp = markUp + ( "<b>Time: Duration/Max</b>: <span color='"+color+"'>"+self.formatTime(s[6])+"</span> <b>Idle/Max</b>: <span color='"+color+"'>"+self.formatTime(s[7])+"</span>\n" )178 markUp = markUp + ( "<b>Octets: Input/Max</b>: <span color='"+color+"'>"+self.formatOctets(s[8])+"</span> <b>Output/Max</b>:<span color='"+color+"'>"+self.formatOctets(s[9])+"</span> <b>Total-Max</b>: <span color='"+color+"'>"+self.formatOctets(s[10])+"</span>\n" )179 markUp = markUp + ( "<b>Bandwidth: %/Max-Up</b>: <span color='"+color+"'>"+self.formatBw(s[12])+"</span> <b>%/Max-Down</b>: <span color='"+color+"'>"+self.formatBw(s[13])+"</span>\n" )180 markUp = markUp + ( "<b>Original URL:</b>: <span color='"+color+"'>"+self.formatURL(s[14])+"</span>\n" )181 self.sessionView.set_markup(markUp)182 i = i + 1183 if macNotFound:184 self.selectedMac = None185 self.sesAuth.set_sensitive( False )186 self.sesRelease.set_sensitive( False )187 self.sesBlock.set_sensitive( False )188 self.sessionView.set_markup('')189 else:190 if selectPath > -1:191 self.sessionsView.get_selection().select_path(selectPath)192 def chilliQuery( self, widget=None ):193 self._chilliQuery()194 return True195 def sessionRelease( self, widget ):196 print 'Releasing '+self.selectedMac197 p = subprocess.Popen([self.Query, self.Socket, "dhcp-release", self.selectedMac]).communicate()198 self.chilliQuery()199 return200 def sessionBlock( self, widget ):201 print 'Blocking access from '+self.selectedMac202 p = subprocess.Popen([self.Query, self.Socket, "block", self.selectedMac]).communicate()203 self.chilliQuery()204 return205 def sessionAuthorize( self, widget ):206 if self.selectedSessionId:207 print 'Authorizing '+self.selectedSessionId208 p = subprocess.Popen([self.Query, self.Socket, "authorize", "sessionid", self.selectedSessionId]).communicate()209 self.chilliQuery()210 return211 def startCoovaChilli( self, widget, data = None ):212 self.saveConfig()213 p = subprocess.Popen(self.Init + ' start', shell=True)214 sts = os.waitpid(p.pid, 0)215 configfile = open(self.Section, 'wb')216 configfile.write(self.section)217 configfile.close()218 return True219 def stopCoovaChilli( self, widget, data = None ):220 p = subprocess.Popen(self.Init + ' stop', shell=True)221 sts = os.waitpid(p.pid, 0)222 configfile = open(self.Section, 'wb')223 configfile.write('')224 configfile.close()225 return True226 def conf( self, name ):227 try:228 result = self.config.get(self.section, name);229 except:230 result = ''231 return result232 def _newSection( self ):233 win = EntryDialog('New config name', '', modal=True)234 win.set_title('Clone config')235 win.show()236 gtk.main()237 return win.ret238 def deleteSection( self, data=None ):239 if self.section != 'default':240 self.config.remove_section(self.section)241 self.sectionStore.clear()242 for s in self.config.sections():243 self.sectionStore.append([ s ])244 self._changeSection('default')245 return246 def newSection( self, data=None ):247 section = self._newSection()248 if section != None:249 if section != '':250 self.config.add_section(section)251 self.clone(section)252 self.sectionStore.clear()253 for s in self.config.sections():254 self.sectionStore.append([ s ])255 self._changeSection(section)256 return257 def _setComboxBox(self, box, val):258 model = box.get_model()259 index = box.get_active()260 i = 0261 for m in model:262 if m[0] == val:263 if i != index:264 box.set_active(i)265 return266 i = i + 1267 return268 def _changeSection(self, section):269 print 'change to '+section270 self.section = section271 272 for setting in self.Settings:273 if self.Entries.get(setting):274 self.Entries.get(setting).set_text( self.conf( setting ) )275 276 self._setComboxBox(self.sectionBox, section)277 self._setComboxBox(self.sectionBox2, section)278 return279 def changeSection(self, combobox):280 model = combobox.get_model()281 index = combobox.get_active()282 self._changeSection( model[index][0] )283 return284 def changeSection2(self, combobox):285 model = combobox.get_model()286 index = combobox.get_active()287 self._changeSection( model[index][0] )288 return289 def row3(self, treeview, iter, path, action):290 print action291 def row1(self, treeview, action):292 if action == 'cursor-changed':293 selection = self.sessionsView.get_selection()294 model, iter = selection.get_selected()295 if iter:296 mac = self.sessionsStore.get_value(iter, 0)297 print 'Selected: '+mac298 self.sesAuth.set_sensitive( True )299 self.sesRelease.set_sensitive( True )300 self.sesBlock.set_sensitive( True )301 self._chilliQuery( mac )302 print action303 def formatOctets(self, o):304 return o305 def formatTime(self, o):306 return o307 def formatBw(self, o):308 return o309 def formatURL(self, o):310 idx = string.find(o, "?")311 if idx > -1:312 o = o[:idx]313 return o314 def makeConfigTable( self ):315 self.configTable = gtk.Table(8, 2, True)316 self.lblSection = gtk.Label( "Configuration:" )317 self.btnSave = gtk.Button( "Save" )318 self.btnNewCfg = gtk.Button( "Clone" )319 self.btnDelCfg = gtk.Button( "Delete" )320 row = 0321 self.configTable.attach(self.lblSection, 0, 1, row, row+1)322 self.configTable.attach(self.sectionBox2, 1, 2, row, row+1)323 for setting in self.Settings:324 if self.Entries.get(setting):325 row = row + 1326 self.configTable.attach(self.Labels.get(setting), 0, 1, row, row+1)327 self.configTable.attach(self.Entries.get(setting), 1, 2, row, row+1)328 row = row + 1329 configBtnBox = gtk.HBox()330 configBtnBox.pack_start( self.btnSave )331 configBtnBox.pack_start( self.btnNewCfg )332 configBtnBox.pack_start( self.btnDelCfg )333 self.configTable.attach(configBtnBox, 0, 2, row, row+1)334 self.btnSave.connect( "clicked", self.saveConfig )335 self.btnNewCfg.connect( "clicked", self.newSection )336 self.btnDelCfg.connect( "clicked", self.deleteSection )337 self.lblSection.show()338 self.sectionBox.show()339 self.sectionBox2.show()340 for setting in self.Settings:341 if self.Entries.get(setting):342 self.Labels.get(setting).show()343 self.Entries.get(setting).show()344 self.btnSave.show()345 self.btnNewCfg.show()346 self.btnDelCfg.show()347 configBtnBox.show()348 def __init__( self, data=None, more=None ):349 # Load configuration file350 try:351 configfile = open(self.Section, 'r')352 self.section = configfile.readline()353 configfile.close()354 except:355 self.section = ''356 if self.section == '':357 self.section = 'default'358 # Initialize parameters359 self.selectedMac = None360 self.selectedSessionId = None361 self.config = ConfigParser.RawConfigParser()362 if os.path.exists(self.Ini):363 self.config.read(self.Ini)364 else:365 self.config.read(self.DefIni)366 # Setup the sections store and selection boxes367 self.sectionStore = gtk.ListStore(gobject.TYPE_STRING)368 self.sectionBox = gtk.ComboBox(self.sectionStore)369 self.sectionBox2 = gtk.ComboBox(self.sectionStore)370 cell = gtk.CellRendererText()371 self.sectionBox.pack_start(cell, True)372 self.sectionBox.add_attribute(cell, 'text', 0)373 self.sectionBox2.pack_start(cell, True)374 self.sectionBox2.add_attribute(cell, 'text', 0)375 for section in self.config.sections():376 self.sectionStore.append([ section ])377 self.sessionsStore = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)378 self.sessionsView = gtk.TreeView(self.sessionsStore)379 cell = gtk.CellRendererText()380 col = gtk.TreeViewColumn("MAC", cell, text=0)381 self.sessionsView.append_column(col)382 cell = gtk.CellRendererText()383 col = gtk.TreeViewColumn("IP", cell, text=1)384 self.sessionsView.append_column(col)385 self.sessionsView.connect( "cursor-changed", self.row1, "cursor-changed" )386 self.vboxSessions = gtk.VBox( )387 self.vboxSessionBtns = gtk.HBox( homogeneous = True )388 self.sesRefresh = gtk.Button( "Refresh" )389 self.sesAuth = gtk.Button( "Auth" )390 self.sesRelease = gtk.Button( "Release" )391 self.sesBlock = gtk.Button( "Block" )392 self.sesAuth.set_sensitive( False )393 self.sesRelease.set_sensitive( False )394 self.sesBlock.set_sensitive( False )395 self.sessionView = gtk.Label("");396 self.vboxSessions.pack_start( self.sessionsView )397 self.vboxSessions.pack_start( self.sessionView, False )398 self.vboxSessionBtns.pack_start( self.sesRefresh )399 self.vboxSessionBtns.pack_start( self.sesAuth )400 self.vboxSessionBtns.pack_start( self.sesRelease )401 self.vboxSessionBtns.pack_start( self.sesBlock )402 self.vboxSessions.pack_start( self.vboxSessionBtns, False )403 self.sesRefresh.connect( "clicked", self.chilliQuery )404 self.sesRelease.connect( "clicked", self.sessionRelease )405 self.sesBlock.connect( "clicked", self.sessionBlock )406 self.sesAuth.connect( "clicked", self.sessionAuthorize )407 self.vboxSessions.show()408 self.sesRefresh.show()409 self.sesAuth.show()410 self.sesRelease.show()411 self.sesBlock.show()412 self.sessionView.show()413 self.sessionsView.show()414 self.vboxSessionBtns.show()415 416 self.btnStart = gtk.Button( "Start" )417 self.btnStop = gtk.Button( "Stop" )418 self.btnStart.set_sensitive( False )419 self.btnStop.set_sensitive( False )420 421 self.btnStart.connect( "clicked", self.startCoovaChilli )422 self.btnStop.connect( "clicked", self.stopCoovaChilli )423 def main( self ):424 print 'hello'425if __name__ == "__main__":426 COOVACHILLI = CoovaChilli()...

Full Screen

Full Screen

osc-bridge.py

Source:osc-bridge.py Github

copy

Full Screen

1from web3 import Web32from pythonosc import osc_message_builder3from pythonosc import udp_client4import socket5import time6import sys7w3 = Web3(Web3.HTTPProvider('https://api.avax-test.network/ext/bc/C/rpc'))8address = '0x956cb3c3Db5b3cB13B4Dc7bFE22d1c7f32C71d5C'9abi = '[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"musicFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"startTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"}],"name":"musicStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_parameterId","type":"uint256"},{"indexed":false,"internalType":"address","name":"_sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_time","type":"uint256"}],"name":"paramChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_newSection","type":"uint256"},{"indexed":false,"internalType":"address","name":"_sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_numOfParams","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_time","type":"uint256"}],"name":"sectionChanged","type":"event"},{"inputs":[],"name":"_section","outputs":[{"internalType":"uint256","name":"currentSection","type":"uint256"},{"internalType":"uint256","name":"lastCue","type":"uint256"},{"internalType":"uint256","name":"numParams","type":"uint256"},{"internalType":"address","name":"lastAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_parameter","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"changeParameter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct THISSMARTCONTRACTLOVESOSC.ParamChange[]","name":"_input","type":"tuple[]"}],"name":"changeParameterMulti","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"endTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eventRunning","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"finishMusic","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"finishMusicAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAllParamStruct","outputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"minVal","type":"uint256"},{"internalType":"uint256","name":"maxVal","type":"uint256"},{"internalType":"address","name":"lastAddress","type":"address"},{"internalType":"uint256","name":"lastChange","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct THISSMARTCONTRACTLOVESOSC.Param[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"musicDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"musicTimeLeft","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"params","outputs":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"minVal","type":"uint256"},{"internalType":"uint256","name":"maxVal","type":"uint256"},{"internalType":"address","name":"lastAddress","type":"address"},{"internalType":"uint256","name":"lastChange","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"showTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"startEvent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"startTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]'10contract_instance = w3.eth.contract(address=address, abi=abi)11calls = [12 {13 "address": address,14 "name": "getAllParamStruct",15 "params": []16 },17 {18 "address": address,19 "name": "showRotationList",20 "params": []21 },22 {23 "address": address,24 "name": "showIdToCanvasLocationList",25 "params": []26 }27]28address_multicall = '0x7991E191193bD3cfCBACA17e16a01F52daab823F'29abi_multicall = '[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"musicFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"startTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"}],"name":"musicStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_parameterId","type":"uint256"},{"indexed":false,"internalType":"address","name":"_sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_time","type":"uint256"}],"name":"paramChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_newSection","type":"uint256"},{"indexed":false,"internalType":"address","name":"_sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_numOfParams","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_time","type":"uint256"}],"name":"sectionChanged","type":"event"},{"inputs":[],"name":"_section","outputs":[{"internalType":"uint256","name":"currentSection","type":"uint256"},{"internalType":"uint256","name":"lastCue","type":"uint256"},{"internalType":"uint256","name":"numParams","type":"uint256"},{"internalType":"address","name":"lastAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_parameter","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"changeParameter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct THISSMARTCONTRACTLOVESOSC.ParamChange[]","name":"_input","type":"tuple[]"}],"name":"changeParameterMulti","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"endTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eventRunning","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"finishMusic","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"finishMusicAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAllParamStruct","outputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"minVal","type":"uint256"},{"internalType":"uint256","name":"maxVal","type":"uint256"},{"internalType":"address","name":"lastAddress","type":"address"},{"internalType":"uint256","name":"lastChange","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct THISSMARTCONTRACTLOVESOSC.Param[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"musicDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"musicTimeLeft","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"params","outputs":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"minVal","type":"uint256"},{"internalType":"uint256","name":"maxVal","type":"uint256"},{"internalType":"address","name":"lastAddress","type":"address"},{"internalType":"uint256","name":"lastChange","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"showTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"startEvent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"startTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]'30multicall_contract_instance = w3.eth.contract(address=address_multicall, abi=abi_multicall)31def main():32 while True:33 paramvalues = contract_instance.functions.getAllParamStruct().call()34 # timePassed = contract_instance.functions.showTime().call()35 # section = contract_instance.functions._section().call()36 # client.send_message("/time", timePassed) 37 # client.send_message("/section", [section[0],section[2],section[1],section[3]]) 38 # print("Broadcasted:", "/time", timePassed)39 # print("section", section)40 print(paramvalues)41 for param in paramvalues:42 # # OSC PARSING: "/paramname" , "id" , "value" , "lastAddress", "time"43 client.send_message("/param", [ param[0] , param[1], param[6] , param[4], param[5]]) 44 print("Broadcasted:", "/param", [ param[0] , param[1], param[6] , param[4], param[5]])45 time.sleep(3)46if __name__ == '__main__':47 client = udp_client.SimpleUDPClient('127.0.0.1', 4545)48 # client = udp_client.SimpleUDPClient('192.168.0.255', 4545)49 client._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)...

Full Screen

Full Screen

render.py

Source:render.py Github

copy

Full Screen

1# Software License Agreement (Apache 2.0 License)2#3# Copyright (c) 2021, The Ohio State University4# Center for Design and Manufacturing Excellence (CDME)5# The Artificially Intelligent Manufacturing Systems Lab (AIMS)6# All rights reserved.7#8# Author: Adam Exley9import numpy as np10import cv211import PySimpleGUI as sg12from .data import Dataset13from .simulation import DatasetRenderer14class Aligner():15 """16 Used to manually find the position of camera relative to robot.17 W/S - Move forward/backward18 A/D - Move left/right19 Z/X - Move down/up20 Q/E - Roll21 R/F - Tilt down/up22 G/H - Pan left/right23 +/- - Increase/Decrease Step size24 """25 def __init__(self, dataset, start_idx = None, end_idx = None):26 # Load dataset27 self.ds = Dataset(dataset, permissions='a')28 self.renderer = DatasetRenderer(dataset, None, mode='seg_full')29 if start_idx is not None:30 self.start_idx = start_idx31 else:32 self.start_idx = 033 self.idx = self.start_idx34 if end_idx is not None:35 self.end_idx = end_idx36 else:37 self.end_idx = self.ds.length - 138 self.inc = int((self.end_idx - self.start_idx + 1)/20)39 if self.inc > 10:40 self.inc = 1041 if self.inc < 1:42 self.inc = 143 self.c_pose = self.ds.camera_pose[self.start_idx]44 # Movement steps45 self.xyz_steps = [.001,.005,.01,.05,.1,.25,.5]46 self.ang_steps = [.0005,.001,.005,.01,.025,.05,.1]47 self.step_loc = len(self.xyz_steps) - 448 self._findSections()49 self.section_idx = 050 print("Copying Image Array...")51 self.real_arr = np.copy(self.ds.og_img)52 self.gui = AlignerGUI()53 def run(self):54 ret = True55 move = True56 while ret:57 event, values = self.gui.update(self.section_starts, self.section_idx)58 if event == 'quit':59 print("Quit by user.")60 ret = False61 continue62 elif event == 'new_section':63 self._newSection(values)64 elif event == 'goto':65 if 0 <= self.idx and self.idx < self.ds.length:66 self.idx = values67 move = True68 self._getSection()69 self.readCameraPose()70 if move:71 real = self.real_arr[self.idx]72 self.renderer.setPosesFromDS(self.idx)73 render, depth = self.renderer.render()74 image = self.combineImages(real, render)75 move = False76 image = self.addOverlay(image)77 cv2.imshow("Aligner", image)78 inp = cv2.waitKey(1)79 ret, move = self.moveCamera(inp)80 self.gui.close()81 cv2.destroyAllWindows()82 def moveCamera(self,inp):83 xyz_step = self.xyz_steps[self.step_loc]84 ang_step = self.ang_steps[self.step_loc]85 if inp == ord('0'):86 return False, False87 elif inp == ord('='):88 self.step_loc += 189 if self.step_loc >= len(self.xyz_steps):90 self.step_loc = len(self.xyz_steps) - 191 return True, False92 elif inp == ord('-'):93 self.step_loc -= 194 if self.step_loc < 0:95 self.step_loc = 096 return True, False97 elif inp == ord('k'):98 self.increment(-self.inc)99 return True, True100 elif inp == ord('l'):101 self.increment(self.inc)102 return True, True103 if inp == ord('d'):104 self.c_pose[0] -= xyz_step105 elif inp == ord('a'):106 self.c_pose[0] += xyz_step107 elif inp == ord('w'):108 self.c_pose[1] -= xyz_step109 elif inp == ord('s'):110 self.c_pose[1] += xyz_step111 elif inp == ord('z'):112 self.c_pose[2] += xyz_step113 elif inp == ord('x'):114 self.c_pose[2] -= xyz_step115 elif inp == ord('q'):116 self.c_pose[3] -= ang_step117 elif inp == ord('e'):118 self.c_pose[3] += ang_step119 elif inp == ord('r'):120 self.c_pose[4] -= ang_step121 elif inp == ord('f'):122 self.c_pose[4] += ang_step123 elif inp == ord('g'):124 self.c_pose[5] += ang_step125 elif inp == ord('h'):126 self.c_pose[5] -= ang_step127 self.saveCameraPose()128 return True, True129 def addOverlay(self, image):130 pose_str = "["131 for num in self.c_pose:132 pose_str += f"{num:.3f}, "133 pose_str +="]"134 image = cv2.putText(image, pose_str,(10,50), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)135 image = cv2.putText(image, str(self.xyz_steps[self.step_loc]),(10,100), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)136 image = cv2.putText(image, str(self.ang_steps[self.step_loc]),(10,150), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)137 image = cv2.putText(image, str(self.idx),(10,200), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)138 return image139 def combineImages(self,image_a, image_b, weight = .5):140 return np.array(image_a * weight + image_b *(1-weight), dtype=np.uint8)141 def increment(self, step):142 if (self.idx + step >= 0) and (self.idx + step < self.ds.length):143 self.idx += step144 def saveCameraPose(self):145 for idx in range(self.start_idx, self.end_idx + 1):146 self.ds.camera_pose[idx,:] = self.c_pose147 def readCameraPose(self):148 self.c_pose = self.ds.camera_pose[self.idx,:]149 def _findSections(self):150 self.section_starts = []151 p = [0,0,0,0,0,0]152 for idx in range(self.ds.length):153 if not np.array_equal(self.ds.camera_pose[idx], p):154 self.section_starts.append(idx)155 p = self.ds.camera_pose[idx,:]156 self.section_starts.append(self.ds.length)157 self.section_starts158 def _newSection(self, idx):159 self.section_starts.append(idx)160 self.section_starts.sort()161 def _getSection(self):162 section_start = max([x for x in self.section_starts if x <= self.idx])163 self.section_idx = self.section_starts.index(section_start)164 self.start_idx = section_start165 self.end_idx = self.section_starts[self.section_idx + 1] - 1166class AlignerGUI():167 def __init__(self):168 control_str = "W/S - Move forward/backward\n"+\169 "A/D - Move left/right\nZ/X - Move up/down\nQ/E - Roll\n"+\170 "R/F - Tilt down/up\nG/H - Pan left/right\n+/- - Increase/Decrease Step size\nK/L - Last/Next image"171 self.layout = [[sg.Text("Currently Editing:"), sg.Text(size=(40,1), key='editing')],172 [sg.Input(size=(5,1),key='num_input'),sg.Button('Go To',key='num_goto'), sg.Button('New Section',key='new_section')],173 [sg.Text("",key='warn',text_color="red", size=(22,1))],174 [sg.Table([[["Sections:"]],[[1,1]]], key='sections'),sg.Text(control_str)],175 [sg.Button('Quit',key='quit')]]176 self.window = sg.Window('Aligner Controls', self.layout, return_keyboard_events = True, use_default_focus=False)177 def update(self, section_starts, section_idx):178 event, values = self.window.read(timeout=1, timeout_key='tm')179 section_table = []180 for idx in range(len(section_starts)-1):181 section_table.append([[f"{section_starts[idx]} - {section_starts[idx+1]-1}"]])182 self.window['editing'].update(f"{section_starts[section_idx]} - {section_starts[section_idx+1]-1}")183 self.window['sections'].update(section_table)184 try:185 if event == 'new_section':186 return ['new_section',int(values['num_input'])]187 elif event == 'num_goto':188 return ['goto',int(values['num_input'])]189 if len(values['num_input']) > 0:190 if int(values['num_input']) is not None:191 self.window['warn'].update("")192 except ValueError:193 self.window['warn'].update("Please input a number.")194 if event == 'quit':195 self.close()196 return ['quit',None]197 return [None,None]198 def close(self):...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful