def register(self, on_step=None): """Tasklet that registers on the network :Parameters: on_step : callback function | None a callback function that take a string argument that will be called at every step of the registration procedure """ def default_on_step(msg): pass on_step = on_step or default_on_step try: LOGGER.info("Request the GSM resource") on_step("Request the GSM resource") yield WaitDBus(self.ousage.RequestResource, 'GSM') yield self._turn_on(on_step) on_step("Register on the network") LOGGER.info("register on the network") yield WaitDBus(self.gsm_network.Register) yield tichy.Wait(self, 'provider-modified') except Exception, ex: LOGGER.error("Error : %s", ex) raise
def init(self): logger.info("bt loading") yield tichy.Service.get('ConfigService').wait_initialized() try: yield tichy.tasklet.WaitDBusName('org.bluez',time_out=120) self.usage_service = tichy.Service.get('Usage') yield self.usage_service.request_resource('Bluetooth') self.bus = dbus.SystemBus(mainloop=tichy.mainloop.dbus_loop) manager_obj = self.bus.get_object('org.bluez', "/") self.Manager = dbus.Interface(manager_obj, 'org.bluez.Manager') raise try: default_adapter = yield WaitDBus(self.Manager.DefaultAdapter) adapter = yield WaitDBus(self.Manager.FindAdapter, default_adapter) adapter_obj = self.bus.get_object('org.bluez', adapter) except: adapter_list = yield WaitDBus(self.Manager.ListAdapters) if len(adapter_list) == 0: logger.info("adapter list empty.. waiting") yield WaitDBusSignal(self.Manager, "AdapterAdded") adapter_list = yield WaitDBus(self.Manager.ListAdapters) adapter_obj = self.bus.get_object('org.bluez', adapter_list[0]) self.Adapter = dbus.Interface(adapter_obj, 'org.bluez.Adapter') self.config_service = tichy.Service.get("ConfigService") #setting up agent agent_path = "/test/agent" self.Agent = Agent(self.bus, agent_path) logger.debug("bluez Agent registered") self.Adapter.RegisterAgent(self.Agent, "DisplayYesNo") #listen for signals #on bt obj self.Adapter.connect_to_signal('DeviceFound',self.DeviceAppeared) self.Adapter.connect_to_signal('DeviceDisappeared',self.DeviceDisappeared) self.Adapter.connect_to_signal('DeviceRemoved',self.DeviceRemoved) print self.Adapter.GetProperties() #on service instance self.connect("close", self.close) self.scanning = False self.DeviceList = tichy.List() self.ListLabel = [('title','name'),('subtitle','addr')] self.scan_setting = tichy.settings.ListSetting('Bluetooth', 'List', tichy.Text, value="scan", setter=self.StartScanning, options=['scan'], model=self.DeviceList, ListLabel=self.ListLabel) status = tichy.settings.ToggleSetting('', 'status', tichy.Text, value=self.get_status(), setter=self.set_status, options=['active','inactive']) #password = tichy.settings.StringSetting('gprs', 'password', tichy.Text, value=self.get_password(), setter=self.set_password) #user = tichy.settings.StringSetting('gprs', 'user', tichy.Text, value=self.get_user(), setter=self.set_user) #apn = tichy.settings.StringSetting('gprs', 'apn', tichy.Text, value=self.get_apn(), setter=self.set_apn) #self.iface.connect_to_signal("NetworkStatus", self.status_change) #self.iface.connect_to_signal("ContextStatus", self.context_status_change) except Exception, e: logger.warning("can't use bt service : %s", e) raise
def SetRegStatus(self, val): if self.GetRegStatus() != 'not registered': yield WaitDBus(self.gsm_network.Unregister) ret = "not registered" else: yield WaitDBus(self.gsm_network.Register) ret = "registered" yield ret
def power(self, status): logger.info("setting power of wifi device") if self.power_iface.GetPower() == True: yield WaitDBus(self.power_iface.SetPower, False) ret = "inactive" else: yield WaitDBus(self.power_iface.SetPower, True) ret = "active" logger.info("new status %s", str(ret)) yield ret
def update(self): logger.info("update sms inbox") status = yield WaitDBus(self.sim_iface.GetSimReady) status = yield WaitDBus(self.sim_iface.GetAuthStatus) messages = yield WaitDBus(self.sim_iface.RetrieveMessagebook, "all") logger.info("found %s messages into sim", len(messages)) messages_service = tichy.Service('Messages') for msg in messages: id, status, number, text = msg sms = self.create(str(number), unicode(text), 'in') messages_service.add_to_messages(sms)
def send(self, sms): logger.info("Storing message to %s", sms.peer) message_id = yield WaitDBus(self.sim_iface.StoreMessage, str(sms.peer), unicode(sms.text), {}) logger.info("Done, id : %s", message_id) logger.info("Sending message") yield WaitDBus(self.sim_iface.SendStoredMessage, message_id) logger.info("Done") # We store a copy cause we don't want to modify the stored sms. logger.info("Store message into messages") #sms = SMS(sms.peer, sms.text, 'out') tichy.Service('Messages').add_to_messages(sms)
def run_scan(self, *args, **kargs): if self.get_power() == 'active': logger.info("power active") if hasattr(self, 'device'): try: yield WaitDBus(self.device.ProposeScan) logger.debug(" wifi Scan proposed") except: logger.debug("proposing wifi scan failed") yield WaitDBus(self.device.SetProperty, "Scanning", True) yield "scan" else: self.status_setting.rotate() yield "scan"
def retry_on_sim_busy(method, *args): """Attempt a dbus call the the framework and retry if we get a sim busy error Every time we get a SIM busy error, we wait for the ReadyStatus signal, or 5 seconds, and we try again. If it fails 5 times, we give up and raise an Exception. """ def is_busy_error(ex): """Check if an exception is due to a SIM busy error""" # There is a little hack to handle cases when the framework # fails to send the SIM.NotReady error. name = ex.get_dbus_name() msg = ex.get_dbus_message() return name == 'org.freesmartphone.GSM.SIM.NotReady' or \ msg.endswith('SIM busy') bus = dbus.SystemBus(mainloop=tichy.mainloop.dbus_loop) gsm = bus.get_object('org.freesmartphone.ogsmd', '/org/freesmartphone/GSM/Device', follow_name_owner_changes=True) gsm_sim = dbus.Interface(gsm, 'org.freesmartphone.GSM.SIM') for i in range(5): try: ret = yield WaitDBus(method, *args) yield ret except dbus.exceptions.DBusException, ex: if not is_busy_error(ex): # This is an other error raise logger.info("sim busy, retry in 5 seconds") yield WaitFirst(Sleep(5), WaitDBusSignal(gsm_sim, 'ReadyStatus')) continue
def get_contacts(self): """Return the list of all the contacts in the SIM The framework may fail, so we try at least 5 times before we give up. We need to remove this if the framework correct this problem. """ logger.info("Retrieve Phonebook") ready = yield WaitDBus(self.gsm_sim.GetSimReady) if ready == False: logger.info("ready false") while 1: status = yield WaitDBusSignal(self.gsm_sim, 'ReadyStatus') if status == True: logger.debug("ready now true breaking") break else: logger.debug("ready still flase not breaking") continue entries = yield retry_on_sim_busy(self.gsm_sim.RetrievePhonebook, 'contacts') logger.info("Got %d contacts" % len(entries)) #logger.debug('get contacts : %s', entries) ret = [] for entry in entries: index = int(entry[0]) name = unicode(entry[1]) tel = str(entry[2]) contact = SIMContact(name=name, tel=tel, sim_index=index) self.indexes[index] = contact ret.append(contact) yield ret
def _on_incoming_message(self, index): # XXX: It would be better to use a PhoneMessage here, and # never store messages on the SIM. logger.info("Incoming message %d", index) message = yield WaitDBus(self.sim_iface.RetrieveMessage, index) status = str(message[0]) peer = str(message[1]) text = unicode(message[2]) messages_service = tichy.Service.get('Messages') message = messages_service.create(peer, text, 'in') yield messages_service.add(message) tichy.Service.get('Sounds').Message() # We delete the message from the SIM logger.info("deleting %d", index) yield WaitDBus(self.sim_iface.DeleteMessage, index) logger.info("deleted %d", index)
def release_resource(self, resource): if hasattr(self, "iface"): if resource in self.iface.ListResources(): logger.debug("requesting resource %s state", str(resource)) state = yield WaitDBus(self.iface.GetResourceState, resource) if state == True and self.flags[resource] == True: try: logger.debug("releasing resource %s", str(resource)) yield WaitDBus(self.iface.ReleaseResource, resource) logger.debug("released resource %s", str(resource)) self.flags[resource] = False except Ex, e: logger.info("%s %s", str(Ex), str(e)) else: logger.debug( "not releasing resource %s as it has been already released", str(resource))
def add_contact(self, name, number): #logger.info("add %s : %s into the sim" % (name, number)) index = self._get_free_index() contact = SIMContact(name=name, tel=number, sim_index=index) self.indexes[index] = contact yield WaitDBus(self.gsm_sim.StoreEntry, 'contacts', index, unicode(name), str(number)) yield contact
def _turn_on(self, on_step): LOGGER.info("Check antenna power") power = yield WaitDBus(self.gsm_device.GetAntennaPower) LOGGER.info("antenna power is %d", power) if power: yield None LOGGER.info("turn on antenna power") on_step("Turn on antenna power") for i in range(3): try: yield WaitDBus(self.gsm_device.SetAntennaPower, True) except dbus.exceptions.DBusException, ex: if ex.get_dbus_name() != \ 'org.freesmartphone.GSM.SIM.AuthFailed': raise # We ask for the PIN yield self._ask_pin()
def release_resource(self, resource): if hasattr(self, "iface"): if resource in self.iface.ListResources(): logger.debug("requesting resource %s state", resource) state = yield WaitDBus(self.iface.GetResourceState, resource) if state and self.flags[resource]: try: logger.debug("releasing resource %s", resource) yield WaitDBus(self.iface.ReleaseResource, resource) logger.debug("released resource %s", resource) self.flags[resource] = False except Exception, e: logger.exception("release_resource %s", e) else: logger.debug( "not releasing resource %s as it has been already released", resource)
def _turn_on(self): """turn on the antenna We need to check if the SIM PIN is required and if so start the PIN input application. """ logger.info("Check antenna power") power = yield WaitDBus(self.gsm_device.GetAntennaPower) logger.info("antenna power is %d", power) if power: yield None logger.info("turn on antenna power") try: yield WaitDBus(self.gsm_device.SetAntennaPower, True) except dbus.exceptions.DBusException, ex: if ex.get_dbus_name() != 'org.freesmartphone.GSM.SIM.AuthFailed': raise yield self._ask_pin()
def set_alarm(self, ttime, func, *args): try: self.slot.set_action(func, *args) print func print args yield WaitDBus(self.alarm.SetAlarm, 'org.tichy.notification', int(ttime.value)) except Exception, ex: logger.error("Exception : %s", ex) raise
def send_pin(self, pin): logger.info("sending pin") try: yield WaitDBus(self.gsm_sim.SendAuthCode, pin) except dbus.exceptions.DBusException, ex: if ex.get_dbus_name() not in [ 'org.freesmartphone.GSM.SIM.AuthFailed', 'org.freesmartphone.GSM.SIM.InvalidIndex' ]: raise raise PINError(pin)
def set_status(self, val): status = self.get_status() ret = status logger.info("status is: %s", status) if status == "unregistered": self.pdp_id = yield WaitDBus(self.iface.ActivateContext, self.get_apn(), self.get_user(), self.get_password()) ret = "active" elif status in ["home","roaming","busy"]: if self.pdp_id != None: logger.info("trying to disconnect PDP") yield WaitDBus(self.iface.DeactivateContext) logger.info("disconnected PDP") self.pdp_id = None ret = "unregistered" else: yield tichy.tasklet.WaitDBus(self.iface.DeactivateContext) logger.info("no pdp_id found not disconnecting") else: ret = "unregistering" yield Wait(self,"gprs-status") yield ret
def ToggleForwarding(self, *args): reason = self.ForwardingGetReason() if self.GetForwardingStatus(reason) == 'inactive': channel = self.ForwardingGet('status') number = self.ForwardingGet('number') timeout = self.ForwardingGet('timeout') try: if reason == "no reply": yield WaitDBus( self.gsm_network.EnableCallForwarding( reason, channel, number, int(timeout))) else: yield WaitDBus( self.gsm_network.EnableCallForwarding( reason, channel, number, int(timeout))) except Exception, e: yield tichy.Service.get('Dialog').dialog( "window", 'Error', str(e)) print e print Exception
def send(self, sms): logger.info("Sending message to %s", sms.peer) if self.GetDeliveryReport() == 'on': properties = {'type':'sms-submit','alphabet': 'gsm_default','status-report-request':True} else: logger.info("no delivery report value is %s", self.GetDeliveryReport()) properties = dict(type='sms-submit', alphabet='gsm_default') try: index, timestamp = yield WaitDBus(self.sms_iface.SendMessage, str(sms.peer), unicode(sms.text), properties) except Exception, e: logger.info ("%s %s", str(Exception), str(e))
def run_scan(self, val): if self.scanning == False: self.scanning = True self.NetworkList.clear() providers = yield WaitDBus(self.gsm_network.ListProviders) for i in providers: if i[1] != 'forbidden': obj = Provider(i, self.RegisterWithProvider_pre) self.NetworkList.append(obj) self.scanning = False yield "scan"
def set_alarm(self, ttime, func, *args): try: self.slot.set_action(func, *args) logger.debug( 'set_action %s %s', func, args, ) yield WaitDBus(self.alarm.SetAlarm, 'org.tichy.notification', int(ttime.value)) except Exception, ex: logger.exception("Exception : %s", ex) raise
def set_current_time(self, ttime): """ Set time, but not date here. ttime argument is GMT time """ if not isinstance(ttime, tichy.ttime.Time): raise TypeError try: localtime = ttime.local_repr().split() timeSetCmd = 'date -s ' + localtime[3] #XXX: here seems a dirty quick way (os.system). os.system(timeSetCmd) yield WaitDBus(self.rtc.SetCurrentTime, int(ttime.value)) except Exception, ex: logger.error("Exception : %s", ex) raise
def _initiate(self, call): """Initiate a given call """ if not self.gsm_call: raise Exception("No connectivity") number = str(call.number) logger.info("initiate call to %s", number) call_id = yield WaitDBus(self.gsm_call.Initiate, number, "voice") call_id = int(call_id) logger.info("call id : %d", call_id) self.lines[call_id] = call # TODO: mabe not good idea to store this in the call itself, # beside, it makes pylint upset. call.__id = call_id
def get_messages(self): """Return the list of all the messages in the SIM The framework may fail, so we try at least 5 times before we give up. We need to remove this if the framework correct this problem. """ for i in range(5): try: logger.info("Retrieve Messages") entries = yield WaitDBus(self.gsm_sim.RetrieveMessagebook, 'all') logger.info("Got %d messages" % len(entries)) logger.debug('get messages : %s', entries) break except Exception, e: logger.error("can't retrieve message book : %s" % e) logger.info("retrying in 10 seconds") yield tichy.tasklet.Sleep(10) continue
def init(self): """Tasklet that registers on the network """ try: yield self._connect_dbus() logger.info("Request the GSM resource") yield WaitFSOResource('GSM', time_out=30) yield WaitDBus(self.ousage.RequestResource, 'GSM') yield self._turn_on() logger.info("register on the network") register = yield self._register() #if register: #provider = yield tichy.Wait(self, 'provider-modified') self._keep_alive().start() ##network selection end except Exception, ex: logger.error("Error : %s", ex) raise
def _register(self): try: #if self.reg_counter != 0: #logger.info("about to wait") yield WaitDBus(self.gsm_network.Register) ret = True #else: #logger.info("elsed") #raise TypeError except: ret = False logger.info("ret is %s", str(ret)) #self.reg_counter += 1 if not ret: t = Timer(30, self._register_jumper) t.start() #logger.info("timer obj: %s", str(t)) yield ret
def remove_message(self, message): logger.info("remove message %s from sim", message.sim_index) yield WaitDBus(self.gsm_sim.DeleteMessage, int(message.sim_index))
def remove_contact(self, contact): logger.info("remove contact %s from sim", contact.name) yield WaitDBus(self.gsm_sim.DeleteEntry, 'contacts', contact.sim_index)
setter=self.SetAuthRequired, options=["on", "off"]) self.ChangePinSetting = tichy.settings.ToggleSetting( 'SIM', 'Change PIN', tichy.Text, value="", setter=self.ChangeAuthCode) ##pin setting stop except Exception, ex: logger.error("Error : %s", ex) raise #logger.info("message center is %s", str(msg_center)) self.sim_info = yield WaitDBus(self.gsm_sim.GetSimInfo) yield None @tichy.tasklet.tasklet def SetServiceCenterNumber(self, value): self.gsm_sim.SetServiceCenterNumber(value) yield None def get_contacts(self): """Return the list of all the contacts in the SIM The framework may fail, so we try at least 5 times before we give up. We need to remove this if the framework correct this problem. """ logger.info("Retrieve Phonebook")