def SetBrightness( self, brightness ): value = self._percentToValue( brightness ) if self.current != value: writeToFile( "%s/brightness" % self.node, str( value ) ) if self.current == 0: # previously, we were off self._setFbPower( True ) elif value == 0: self._setFbPower( False ) self.current = value
def SetBrightness( self, brightness ): writeToFile( "%s/trigger" % self.node, "none" ) if brightness >= 100: value = 255 elif brightness <= 0: value = 0 else: value = int( round( brightness / 100.0 * 255 ) ) writeToFile( "%s/brightness" % self.node, str( value ) )
def __init__(self, bus, channel): # Kernel specific paths global DEVICE_POWER_PATH_NEW kernel_release = os.uname()[2] if kernel_release >= "2.6.39": DEVICE_POWER_PATH_NEW = "/sys/bus/platform/drivers/gta02-pm-gps/gta02-pm-gps.0/power_on" logger.info("Kernel >= 2.6.39, gps sysfs updated") elif kernel_release >= "2.6.32": DEVICE_POWER_PATH_NEW = "/sys/bus/platform/devices/gta02-pm-gps.0/power_on" logger.info("Kernel >= 2.6.32, gps sysfs updated") # Make sure the GPS is off helpers.writeToFile(DEVICE_POWER_PATH_OLD, "1") helpers.writeToFile(DEVICE_POWER_PATH_NEW, "1") time.sleep(0.5) helpers.writeToFile(DEVICE_POWER_PATH_OLD, "0") helpers.writeToFile(DEVICE_POWER_PATH_NEW, "0") self.aidingData = persist.get("ogpsd", "aidingdata") if self.aidingData is None: self.aidingData = { "almanac": {}, "ephemeris": {}, "position": {}, "hui": {} } self.huiTimeout = None super(GTA02Device, self).__init__(bus, channel)
def StartConnectionSharingWithInterface( self, interface, dbus_ok, dbus_error ): """ This should be roughly equivalent to: #!/bin/sh iptables -I INPUT 1 -s 192.168.0.200 -j ACCEPT iptables -I OUTPUT 1 -s 192.168.0.202 -j ACCEPT iptables -A POSTROUTING -t nat -j MASQUERADE -s 192.168.0.0/24 echo 1 > /proc/sys/net/ipv4/ip_forward <prepare udhcpd configuration> <launch udhcpd> """ try: iface = theNetwork[ str(interface) ] except KeyError: dbus_error( NoInterface( "%s is not a valid interface. Known interfaces are %s" % ( interface, theNetwork.keys() ) ) ) return source_address = iface.ipAddress4() if not isValidAddress( address ): dbus_error( NoAddress( "%s is not a valid IPv4 address." % address ) ) return target_address = address # FIXME use dhcp daemon commands = [] commands.append( "iptables -I INPUT 1 -s 192.168.0.0/24 -j ACCEPT" ) commands.append( "iptables -I OUTPUT 1 -s %s -j ACCEPT" % source_address ) commands.append( "iptables -A POSTROUTING -t nat -j MASQUERADE -s 192.168.0.0/24" ) for command in commands: logging.debug( "issuing command '%s'" % command ) result = subprocess.call( command.split( ' ' ) ) logging.debug( "command result = %d" % result ) if result != 0: dbus_error( InternalError( "%s gave returncode %d" % ( command, result ) ) ) return writeToFile( "/proc/sys/net/ipv4/ip_forward", "1" ) dhcp.prepareDaemonConfigurationForInterface( iface ) dhcp.launchDaemon() dbus_ok()
def prepareDaemonConfigurationForInterface( iface ): #============================================================================# name = iface.name() address = iface.ipAddress4() nameservers = "" resolv_conf = readFromFile( ETC_RESOLV_CONF ).split( '\n' ) for line in resolv.conf: if line.startswith( "nameserver" ): nameservers += ( line.strip().split( ' ' ) ) nameservers += " " conf_file = daemon_conf_file_template % ( name, nameservers, address ) writeToFile( ETC_RESOLV_CONF, conf_file )
def StartConnectionSharingWithInterface(self, interface, dbus_ok, dbus_error): """ This should be roughly equivalent to: #!/bin/sh iptables -I INPUT 1 -s 192.168.0.200 -j ACCEPT iptables -I OUTPUT 1 -s 192.168.0.202 -j ACCEPT iptables -A POSTROUTING -t nat -j MASQUERADE -s 192.168.0.0/24 echo 1 > /proc/sys/net/ipv4/ip_forward <prepare udhcpd configuration> <launch udhcpd> """ try: iface = theNetwork[str(interface)] except KeyError: dbus_error( NoInterface( "%s is not a valid interface. Known interfaces are %s" % (interface, theNetwork.keys()))) return source_address = iface.ipAddress4() commands = [] commands.append("iptables -I INPUT 1 -s 192.168.0.0/24 -j ACCEPT") commands.append("iptables -I OUTPUT 1 -s %s -j ACCEPT" % source_address) commands.append( "iptables -A POSTROUTING -t nat -j MASQUERADE -s 192.168.0.0/24") for command in commands: logger.debug("issuing command '%s'" % command) result = subprocess.call(command.split(' ')) logger.debug("command result = %d" % result) if result != 0: dbus_error( InternalError("%s gave returncode %d" % (command, result))) return writeToFile("/proc/sys/net/ipv4/ip_forward", "1") dhcp.prepareDaemonConfigurationForInterface(iface) dhcp.launchDaemon() dbus_ok()
def prepareDaemonConfigurationForInterface(iface): #============================================================================# name = iface.name() address = iface.ipAddress4() nameservers = "" resolv_conf = readFromFile(ETC_RESOLV_CONF).split('\n') for line in resolv_conf: if line.startswith("nameserver"): nameserver = line.strip().split(' ')[1] nameservers += nameserver nameservers += " " conf_file = daemon_conf_file_template % (name, nameservers, address) writeToFile(ETC_UDHCPD_CONF, conf_file)
def initializeDevice(self): helpers.writeToFile(DEVICE_POWER_PATH_OLD, "1") helpers.writeToFile(DEVICE_POWER_PATH_NEW, "1") # Wait for the device to be powered up time.sleep(0.5) # Reset the device #self.send("CFG-RST", 4, {"nav_bbr" : 0xffff, "Reset" : 0x01}) super(GTA02Device, self).initializeDevice() # Load aiding data and only if that succeeds have the GPS chip ask for it if self.aidingData["almanac"] or self.aidingData[ "ephemeris"] or self.aidingData["position"]: self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["AID-REQ"][0], "MsgID": CLIDPAIR["AID-REQ"][1], "Rate": 1 }) # Enable NAV-POSECEF, AID-REQ (AID-DATA), AID-ALM, AID-EPH messages self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["NAV-POSECEF"][0], "MsgID": CLIDPAIR["NAV-POSECEF"][1], "Rate": 8 }) self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["AID-ALM"][0], "MsgID": CLIDPAIR["AID-ALM"][1], "Rate": 1 }) self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["AID-EPH"][0], "MsgID": CLIDPAIR["AID-EPH"][1], "Rate": 1 }) self.huiTimeout = gobject.timeout_add_seconds(300, self.requestHuiTimer)
def setPower(self, power): ResourceAwarePowerControl.setPower(self, power) # Neo1973 Bluetooth needs special reset handling after touching power if power: writeToFile(self.resetnode, "1") writeToFile(self.resetnode, "0") else: writeToFile(self.resetnode, "1")
def shutdownDevice(self): # Disable NAV-POSECEF, AID-REQ (AID-DATA), AID-ALM, AID-EPH messages self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["NAV-POSECEF"][0], "MsgID": CLIDPAIR["NAV-POSECEF"][1], "Rate": 0 }) self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["AID-REQ"][0], "MsgID": CLIDPAIR["AID-REQ"][1], "Rate": 0 }) self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["AID-ALM"][0], "MsgID": CLIDPAIR["AID-ALM"][1], "Rate": 0 }) self.send( "CFG-MSG", 3, { "Class": CLIDPAIR["AID-EPH"][0], "MsgID": CLIDPAIR["AID-EPH"][1], "Rate": 0 }) if self.huiTimeout is not None: gobject.source_remove(self.huiTimeout) self.huiTimeout = None super(GTA02Device, self).shutdownDevice() helpers.writeToFile(DEVICE_POWER_PATH_OLD, "0") helpers.writeToFile(DEVICE_POWER_PATH_NEW, "0") # Save collected aiding data persist.set("ogpsd", "aidingdata", self.aidingData) persist.sync("ogpsd")
def SetBlinking( self, delay_on, delay_off ): # validate parameters if "timer" not in self.triggers: raise UnsupportedTrigger( "Timer trigger not available. Available triggers are %s" % self.triggers ) # do it else: writeToFile( "%s/trigger" % self.node, "timer" ) writeToFile( "%s/delay_on" % self.node, str( abs( delay_on ) ) ) writeToFile( "%s/delay_off" % self.node, str( abs( delay_off ) ) )
def SetNetworking( self, interface, mode ): # validate parameters if "netdev" not in self.triggers: raise UnsupportedTrigger( "Netdev trigger not available. Available triggers are %s" % self.triggers ) interfaces = os.listdir( "/sys/class/net" ) if interface not in interfaces: raise InvalidParameter( "Interface %s not known. Available interfaces are %s" % ( interface, interfaces ) ) modes = mode.strip().split() for m in modes: if m not in "link rx tx".split(): raise InvalidParameter( "Mode element %s not known. Available elements are 'link rx tx'" % m ) # do it writeToFile( "%s/trigger" % self.node, "netdev" ) writeToFile( "%s/device_name" % self.node, str( interface.strip() ) ) writeToFile( "%s/mode" % self.node, str( mode.strip() ) )
def shutdownDevice(self): NMEADevice.shutdownDevice(self) helpers.writeToFile(DEVICE_POWER_PATH, "0")
def __init__(self, bus, channel): # Make sure the GPS is off helpers.writeToFile(DEVICE_POWER_PATH, "0") NMEADevice.__init__(self, bus, channel)
def SetBacklightPower( self, power ): value = 0 if power else 1 writeToFile( "%s/bl_power" % self.node, str( value ) )
def setPower(self, power): if power: writeToFile(self.modenode, "host") else: writeToFile(self.modenode, "device") GenericPowerControl.setPower(self, power)
def serve(): import tweepy from tweepy.error import RateLimitError from helpers import parseCliArgs, api, writeToFile from config import fetch_handles from time import sleep from sys import argv, exit opt = parseCliArgs() if not opt['user_id'] and not opt['screen_name']: try: stdin = input('Please enter a screen name or a user Id:\n') except NameError: stdin = raw_input('Please enter a screen name or a user Id:\n') except: pass if stdin and stdin.isdigit(): opt['user_id'] = stdin elif stdin: opt['screen_name'] = stdin if not opt['user_id'] and not opt['screen_name']: print('No user_id or screen_name argument supplied. Exitting..') exit(1) uid_key = 'user_id' if opt['user_id'] else 'screen_name' print('Processing data for %s' % opt[uid_key]) if not opt['save-to']: from datetime import datetime from helpers import checkWritable opt['save-to'] = './timeline-RT-%s-%s.txt' % (opt[uid_key], str(datetime.now())) checkWritable(opt['save-to']) api = api() ids = [] total = 0 try: try: steps = xrange(0, opt['max-page']) except NameError: steps = range(0, opt['max-page']) max_id = opt['max_id'] for i in steps: args = { uid_key: opt[uid_key], 'count': opt['count'] if opt['count'] and opt['count'] <= 200 else 200 } if max_id: args['max_id'] = max_id tweets = api.user_timeline(**args) if tweets: for status in tweets: try: if 'retweeted_status' in dir(status): rt = getattr(status, 'retweeted_status') uid = getattr( getattr(rt, 'author'), 'screen_name' if fetch_handles else 'id') if uid and uid not in ids: ids.append(uid) max_id = getattr(status, 'id') except: pass total += 1 else: break if not 'max-page' in opt or opt['max-page'] <= i + 1: break if int(opt['sleep']) > 0: print('ZzZ.. (page %d)' % int(i + 1)) sleep(int(opt['sleep'])) except RateLimitError: print('Rate limit exceeded! Halt..') except Exception as e: print('Exception raised, err: %s' % e) if ids: if writeToFile(opt['save-to'], '\n'.join([str(i) for i in ids])): print('Successfully saved %d/%d items to %s.' % (len(ids), total, opt['save-to'])) exit(0) else: print('Writing to %s ended with an error.' % opt['save-to']) exit(1) else: print('No IDs retrieved. Exitting..') exit(1)
def setPower(self, power): powernode = "bind" if power else "unbind" writeToFile("%s/%s" % (self.node, powernode), "s3c2440-sdi")
def serve(friends=False): import tweepy from tweepy.error import RateLimitError from helpers import parseCliArgs, api, writeToFile from config import fetch_handles from time import sleep from sys import argv, exit opt = parseCliArgs() if not opt['user_id'] and not opt['screen_name']: try: stdin = input('Please enter a screen name or a user Id:\n') except NameError: stdin = raw_input('Please enter a screen name or a user Id:\n') except: pass if stdin and stdin.isdigit(): opt['user_id'] = stdin elif stdin: opt['screen_name'] = stdin if not opt['user_id'] and not opt['screen_name']: print ( 'No user_id or screen_name argument supplied. Exitting..' ) exit(1) uid_key = 'user_id' if opt['user_id'] else 'screen_name' print ( 'Processing data for %s' % opt[uid_key] ) if not opt['save-to']: from datetime import datetime from helpers import checkWritable opt['save-to'] = './%s-%s-%s.txt' % ( opt[uid_key], 'friends' if friends else 'followers', str(datetime.now()) ) checkWritable( opt['save-to'] ) api = api() ids = [] screen_names = {} try: i=0 for uids in tweepy.Cursor(api.friends_ids if friends else api.followers_ids, **{uid_key: opt[uid_key], 'count': opt['count']}).pages(): ids.extend(uids) if fetch_handles: last = float(len(uids))/float(100) last += 1 if last != int(last) else 0 try: chunks = xrange(0, int(last)) except NameError: chunks = range(0, int(last)) for x in chunks: chunk = uids[x*100:x*100 +100] if not chunk or len(chunk) <= 0: break handles = api._lookup_users(user_id=','.join([str(i) for i in chunk])) if handles: for user in handles: try: screen_names[getattr(user, 'id')] = getattr(user, 'screen_name') except: pass else: raise Exception('Unable to retrieve handles for set of IDs, stop right here.') break if 'id2handle_sleep' in opt and int(opt['id2handle_sleep']) > 0: print( 'ZzZ..' ) sleep(int(opt['id2handle_sleep'])) i+=1 if not 'max-page' in opt or opt['max-page'] <= i: break if int(opt['sleep']) > 0: print( 'ZzZ.. (page %d)' % i ) sleep(int(opt['sleep'])) except RateLimitError: print( 'Rate limit exceeded! Halt..' ) except Exception as e: print ( 'Exception raised, err: %s' % e ) if ids: def stringifyId(i): return str(i) if not i in screen_names else screen_names[i] if writeToFile( opt['save-to'], '\n'.join([stringifyId(i) for i in ids])): print ( 'Successfully saved %d items to %s.' % ( len(ids), opt['save-to'] ) ) exit(0) else: print ( 'Writing to %s ended with an error.' % opt['save-to'] ) exit(1) else: print ( 'No IDs retrieved. Exitting..' ) exit(1)
def initializeDevice(self): helpers.writeToFile(DEVICE_POWER_PATH, "1") NMEADevice.initializeDevice(self)
def serve(): import tweepy from tweepy.error import RateLimitError from helpers import parseCliArgs, api, writeToFile from config import fetch_handles from time import sleep from sys import argv, exit opt = parseCliArgs() hashtags = opt['hashtag'] if not hashtags: try: stdin = input('Please enter a hashtag or a set of hashtags separated by spaces:\n') except NameError: stdin = raw_input('Please enter a hashtag or a set of hashtags separated by spaces:\n') except: pass if stdin: hashtags = stdin if str(hashtags): def remhash(s): return s.replace(r'#', '').strip() hashtags = [remhash(i) for i in str(hashtags).split(' ')] hashtags = [x for x in hashtags if x] if not hashtags: print ( 'No hashtag supplied. Exitting..' ) exit(1) if not opt['save-to']: from datetime import datetime from helpers import checkWritable opt['save-to'] = './hashtag-%s-%s.txt' % ( ','.join([str(i) for i in hashtags]), str(datetime.now()) ) checkWritable( opt['save-to'] ) print ( 'Processing data for #%s' % ', #'.join(hashtags) ) qs = '#' + '+OR+#'.join(hashtags) api = api() ids = [] total=0 try: try: steps = xrange(0,opt['max-page']) except NameError: steps = range(0,opt['max-page']) max_id=opt['max_id'] for i in steps: args = {'q':qs, 'count': opt['count'] if opt['count'] and opt['count'] <= 100 else 100} if max_id > 0: args['max_id'] = max_id tweets = api.search(**args) if tweets: for status in tweets: try: uid = getattr( getattr(status, 'author'), 'screen_name' if fetch_handles else 'id' ) if uid and uid not in ids: ids.append( uid ) max_id = getattr(status, 'id') except: pass total+=1 else: break if not 'max-page' in opt or opt['max-page'] <= i+1: break if int(opt['sleep']) > 0: print( 'ZzZ.. (page %d)' % int(i+1) ) sleep(int(opt['sleep'])) except RateLimitError: print( 'Rate limit exceeded! Halt..' ) except Exception as e: print ( 'Exception raised, err: %s' % e ) if ids: if writeToFile( opt['save-to'], '\n'.join([str(i) for i in ids])): print ( 'Successfully saved %d/%d items to %s.' % ( len(ids), total, opt['save-to'] ) ) exit(0) else: print ( 'Writing to %s ended with an error.' % opt['save-to'] ) exit(1) else: print ( 'No IDs retrieved. Exitting..' ) exit(1)
def reset(self): writeToFile(self.resetnode, "1")
def setPower(self, power): value = self.onValue if power else self.offValue writeToFile(self.powernode, value)