Exemplo n.º 1
0
    def make_ui(self):
        if self.status_icon != None:
            self.status_icon.set_visible(False)

        self.notification = notification.Notification()
        self.notification.connect("has-unread", self.has_unread)
        self.init_status_icon()
Exemplo n.º 2
0
    def start_app(self):
        i=0
        test=tester.Tester.hotels
        while i< len(test):
            new_hotel=hotel.Hotel(test[i][0],test[i][1],test[i][2],test[i][3],test[i][4])
            i+=1


        ################################
        #check if there is empty room in a hotels_list

        x=0
        test_reservation=tester.Tester.reservation
        while x< len(test_reservation):
            hotel_name=test_reservation[x][0]
            customer_name=test_reservation[x][1]
            mobile_number=test_reservation[x][2]
            if new_hotel.get_no_empty_rooms(hotel_name)>0:
                new_reservation=reservation.Reservation(hotel_name,customer_name,mobile_number)
                new_hotel.update_empty_rooms(hotel_name,new_hotel.get_no_empty_rooms(hotel_name)-1)

            #confirmation message
                message="thank you {}\n you reserve in {}\n date: {}".format(customer_name,hotel_name,datetime.datetime.now().strftime("%a, %d %B %Y %I:%M:%S"))
            #send confirmation message to customer
                new_notification=notification.Notification()
                new_notification.send_sms(mobile_number,message)
                # new_notification=notification.Notification(mobile_number,message)
            #add to customers list
                new_customer=customer.Customer(customer_name,mobile_number)


            else:
                print "no reservation available"
            x+=1
Exemplo n.º 3
0
    def onCachesUpdated(self):

        if ADDON.getSetting('notifications.enabled') == 'true':
            n = notification.Notification(self.database, ADDON.getAddonInfo('path'))
            n.scheduleNotifications()

        self.database.close(None)
Exemplo n.º 4
0
def display_notification(video_source, requested_target, remote_domain):
    """Show notification to the user"""

    notification_ui = notification.Notification()
    notification_ui.video_source = video_source
    notification_ui.requested_target = requested_target
    notification_ui.remote_domain = remote_domain
    notification_ui.show()
Exemplo n.º 5
0
Arquivo: main.py Projeto: jthop/pyping
def tester():
    """
    Simple endpoint to test notifications.  This is intended for
    debugging purposes only.
    """

    msg = notification.Notification('test sub', 'test body')
    msg.send()
    return '<html>test complete</html>'
Exemplo n.º 6
0
 def __init__(self, config, **kwargs):
     super(Timer, self).__init__(**kwargs)
     # init settings and timer
     self.init(config)
     self.alarm_sound = SoundLoader.load('data/gong.wav')
     self.start_sound = SoundLoader.load('data/ticktock.wav')
     self.running_down = False
     self.running_up = False
     # init notification wrapper
     self.notification_wrapper = notification.Notification()
     # display time string
     self.update_time_string()
Exemplo n.º 7
0
Arquivo: main.py Projeto: jthop/pyping
def cron():
    """
    The primary checker.  This is the endpoint run each
    time cron runs the checker.  We will check all services,
    and then send notifications if necessary, as well as
    insert details into Mongo.
    """

    p = Pinger.load()
    for s in p.services:
        s.check()
        alert = s.check_notifications()
        if alert.get('just_up'):
            m = models.Incident()
            m.insert(service.freeze)
            # send backup notifications
            body = f'{s.pretty_name} is BACK UP after {s.last_n} pings.'
            msg = notification.Notification(s.pretty_name, body)
            try:
                msg.send()
            except Exception as e:
                app.logger.error(e)

        if alert.get('just_down'):
            # write to mongo
            m = models.Incident()
            m.insert(service.freeze)
            # now send msg
            body = f'{s.pretty_name} just went down. {s.response}'
            msg = notification.Notification(s.pretty_name, body)
            try:
                msg.send()
            except Exception as e:
                app.logger.error(e)

    p.save()
    return '<html>cron complete</html>'
Exemplo n.º 8
0
 def onCachesUpdated(self):
     if ADDON.getSetting('notifications.enabled') == 'true':
         n = notification.Notification(self.database, ADDON.getAddonInfo('path'))
         n.scheduleNotifications()
     if ADDON.getSetting('autoplays.enabled') == 'true':
         n = autoplay.Autoplay(self.database, ADDON.getAddonInfo('path'))
         n.scheduleAutoplays()
     if ADDON.getSetting('autoplaywiths.enabled') == 'true':
         n = autoplaywith.Autoplaywith(self.database, ADDON.getAddonInfo('path'))
         n.scheduleAutoplaywiths()
     self.database.close(None)
     xbmc.log("[script.tvguide.fullscreen] Background Update Finished", xbmc.LOGNOTICE)
     if ADDON.getSetting('background.notify') == 'true':
         d = xbmcgui.Dialog()
         d.notification("TV Guide Fullscreen", "Finished Updating")
Exemplo n.º 9
0
 def onCachesUpdated(self):
     #BUG doesn't work on login (maybe always?)
     if ADDON.getSetting('notifications.enabled') == 'true':
         n = notification.Notification(self.database, ADDON.getAddonInfo('path'))
         #n.scheduleNotifications()
     if ADDON.getSetting('autoplays.enabled') == 'true':
         n = autoplay.Autoplay(self.database, ADDON.getAddonInfo('path'))
         #n.scheduleAutoplays()
     if ADDON.getSetting('autoplaywiths.enabled') == 'true':
         n = autoplaywith.Autoplaywith(self.database, ADDON.getAddonInfo('path'))
         #n.scheduleAutoplaywiths()
     self.database.close(None)
     xbmc.log("[script.baksy.guide] Background Update Finished", xbmc.LOGNOTICE)
     if ADDON.getSetting('background.notify') == 'true':
         d = xbmcgui.Dialog()
         d.notification("Baksy IPTV Guide", "Finished Updating")
Exemplo n.º 10
0
def show_notification(folder):
	# Get status icon position
	icon_geometry=status_icon.get_geometry()
	icon_x=icon_geometry[1].x+12
	icon_y=icon_geometry[1].y+15
	# Set notification contents
	notif_list.append(notification.Notification())
	notif_list[-1].setAppName("Correo")
	notif_list[-1].setSummary("You have new mail!")
	notif_list[-1].setBody("New mail has been received in folder:" \
							"<b>" + folder + "</b>")
	# Set icon from stock
	notif_list[-1].setIcon("stock_mail")
	# Set notification position
	notif_list[-1].setXY(icon_x, icon_y)
	# Set timeout time while notification will be shown
	notif_list[-1].setTimeout(10)
	# Show notification!
	notif_list[-1].notify()
	# return False to Destroy gobject.timeout_add interval
	return False
Exemplo n.º 11
0

cust_operations()


def find_reservation(res_list, customer, hotel):

    for res in res_list:
        if (res[0] == customer):
            if (res[1] == hotel):
                return 'reservation with this customer in this hotel found'
    return 'no reservation for this customer exist'


print ' test reservation class '
print find_reservation(reservation.Reservation.reservations_list, hassan,
                       rotana_hotel)
print find_reservation(reservation.Reservation.reservations_list, ahmed,
                       rotana_hotel)
print find_reservation(reservation.Reservation.reservations_list, hassan,
                       ramsis_hotel)

#send message to client
notification.Notification('rotana', 'hassan')

# should change it to class method
##print 'test '
##
##for res in reservation.Reservation.reservations_list:
##    print res[0],res[1]
Exemplo n.º 12
0
def do_notify(summary, body, icon_file=None):
    global notifier
    if (notifier == None):
        import notification
        notifier = notification.Notification()
    notifier.show(summary, body, icon_file)
Exemplo n.º 13
0
#!/usr/bin/env python3

from pystalkd.Beanstalkd import Connection
import notification
import pickle
import base64

setup = {
    'connection': ('localhost', 11300),
    'tubes': {
        'use': 'python',
        'ignore': ['default'],
    }
}

c = Connection(*setup['connection'])

c.use(setup['tubes']['use'])
print("Using tube {}".format(c.using()))

notifications = []
notifications.append(notification.Notification("*****@*****.**", "Hello"))

for notification in notifications:
    thing = pickle.dumps(notification)
    # beanstalk jobs only allows str objects
    body = base64.b64encode(thing)
    c.put(body.decode('ascii'))
Exemplo n.º 14
0
 def __init__(self, monitors):
     monitors = np.asarray(monitors)
     self.notification = notification.Notification()
     self.monitors = monitors
     self.code = self.monitors[..., 0].tolist()
Exemplo n.º 15
0
class ICan:
    """
    Main class of the iCan application that packages the high level logic of the device.

    Public Methods:
        checkOrientation()
    """

    # SENSORS
    lidSensor = lid.Lid()
    cameraSensor = camera.Camera('/tmp/trash.jpg')

    # ACTUATORS/OUTPUT
    lightOutput = light.Light(21)
    trapdoorOutput = trapdoor.Trapdoor()

    # CLOUD SERVICES AND APIs
    storageService = s3.S3()
    databaseService = database.ICanItems()
    weatherService = local_weather.LocalWeather()
    recognitionService = image_recognition.ImageRecognition()
    predictionService = prediction.Prediction()
    notificationService = notification.Notification()

    # How long to wait to be in "steady" state (seconds)
    WAIT_TIME = 3
    
    # How often readings are taken from the accelerometer (seconds)
    READING_INTERVAL = 0.2

    recentOpenStates = None

    # Take a photo only after the can was just opened and closed (and in steady state)
    photoRecentlyTaken = True

    def __init__(self):
        # Store recent history of states in tuples (horizontal, vertical)
        initialState = (False, False)
        maxLength = int(self.WAIT_TIME / self.READING_INTERVAL)
        self.recentOpenStates = deque(maxLength * [initialState], maxLength)

    def checkOrientation(self):
        """
        Checks the current orientation of the lid, take a photo and process it.
        :return:
        """
        horizontal = self.lidSensor.isHorizontal()
        vertical = self.lidSensor.isVertical()
        print 'H: ', horizontal
        print 'V: ', vertical

        self.recentOpenStates.append((horizontal, vertical))

        if self.isReadyToTakePhoto() and not self.photoRecentlyTaken:
            print 'Taking photo now . . . '
            fileName = self.getFileName()
            self.cameraSensor.setImagePath(fileName)
            self.cameraSensor.takePhoto()
            link = self.uploadPhoto(fileName)

            identifiers = self.recognitionService.getImageIdentifiers(fileName)
            targetPrediction = self.predictionService.getTrashPrediction(identifiers)
            print identifiers
            print targetPrediction

            # Fallback in case nothing is recognized in the image by recognition service
            if len(identifiers) == 0:
                identifiers = ['trash']
                targetPrediction = 'trash'

            self.saveToDatabase(identifiers, targetPrediction, link)
            self.respondToPrediction(identifiers, targetPrediction)
            self.photoRecentlyTaken = True

        if vertical and not horizontal:
            # Lid is open
            self.lightOutput.turnOn()
            self.photoRecentlyTaken = False
        else:
            self.lightOutput.turnOff()

    def saveToDatabase(self, identifiers, targetPrediction, link):
        """
        Save the record of identification to the database.
        :param identifiers: List of identifier strings from the image recognition service
        :param targetPrediction: String prediction from the prediction service
        :param link: Public URL to the image
        :return: Response to save request from the database
        """
        return self.databaseService.addRecord({
            'item_name': ", ".join(identifiers),
            'recyclable': (targetPrediction == 'recyclable'),
            'compostable': (targetPrediction == 'compostable'),
            'timestamp': int(time()),
            'temperature': self.weatherService.getCurrentTemperature(),
            'image': link,
            'user_feedback': False,
        })

    def getFileName(self):
        """
        Return the pseudo unique filename of the next photo to be taken.
        :return: Absolute path to the file as a string
        """
        timestamp = time()
        name = 'trash_' + str(timestamp) + '.jpg'
        path = '/tmp/'
        return path + name

    def isReadyToTakePhoto(self):
        """
        Return if the iCan is ready to take a photo based on current state and previous states.

        If the lid as been closed for the entire duration of the waiting period, then it is
        time to take a photo.

        :return: Boolean on whether the iCan is ready to take a photo
        """
        # Check if the queue of states shows it has been closed
        # for the entire waiting period
        closedState = (True, False)
        return self.recentOpenStates.count(closedState) == self.recentOpenStates.maxlen

    def uploadPhoto(self, fileName):
        """
        Upload given file to cloud storage, write the link to a file and return it
        :param fileName: Absolute path to file
        :return: URL to the file on cloud storage
        """

        # Write the public link to a local file
        link = self.storageService.uploadData(fileName)
        with open('/tmp/photos.txt', 'a') as photosFile:
            photosFile.write(link + "\n")
        print 'URL: ' + link
        return link

    def respondToPrediction(self, identifiers, targetPrediction):
        """
        React to the prediction by either opening the trapdoor or sending a notification.
        :param identifiers: List of string identifiers from Image Recognition Service
        :param targetPrediction: Prediction of 'trash', 'compostable', 'recyclable', etc. from the ML model
        :type targetPrediction: str
        """
        if targetPrediction == 'trash':
            print 'Down the hatch!'
            self.trapdoorOutput.open()
            print 'Waiting . . . '
            sleep(2)
            self.trapdoorOutput.close()
        else:
            print 'Sending Notification'
            identifiersList = ', '.join(identifiers[:3])
            message = 'iCan has detected an item that is: ' + identifiersList
            message = message + "\nCategory " + targetPrediction.upper()
            self.notificationService.sendNotification(message)

    def cleanUp(self):
        """
        Clean up any used I/O pins and close any connections if needed.
        :return: None
        """
        self.trapdoorOutput.cleanUp()
        self.lightOutput.cleanUp()
Exemplo n.º 16
0
    if apppath.checkDependancies() != None:
        logging.error(apppath.checkDependancies())
        sys.exit(1)

    if loggingLevel == "debug":
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s %(message)s')
        logging.debug('Verbose logging enabled')
    elif loggingLevel == "info":
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(message)s')

    #load config
    config = inireader.loadFile(
        os.path.join(os.path.dirname(__file__), 'config.ini'))
    notify = notification.Notification(config['notification'])

    if argType == 'disc' or argType == 'dir' or argType == 'image':
        logging.info('Rip begin -------')

        #load ripper, scraper and notification
        ripper = ripper.Ripper(config['ripper'], argPath, argType)

        rippedTracks = ripContent(config, notify, ripper, argType, argPath)

        uncatalogedFilePaths = []
        for track in rippedTracks:
            uncatalogedFilePaths.append(track.filepath)

        if len(rippedTracks) == 0:
            logging.warn("Didn't extract any video tracks from " + argPath)
Exemplo n.º 17
0
#  This Program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this Program; see the file LICENSE.txt.  If not, write to
#  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#  http://www.gnu.org/copyleft/gpl.html
#
import xbmcaddon
import notification
import xbmc
import source as src

try:
    ADDON = xbmcaddon.Addon(id='script.tvguide')
    source = src.instantiateSource(ADDON)
    if ADDON.getSetting('cache.data.on.xbmc.startup') == 'true':
        channelList = None
        if source._isChannelListCacheExpired():
            channelList = source.updateChannelAndProgramListCaches()

    if ADDON.getSetting('notifications.enabled') == 'true':
        n = notification.Notification(source, ADDON.getAddonInfo('path'))
        n.scheduleNotifications()

except Exception, ex:
    xbmc.log('[script.tvguide] Uncaugt exception in service.py: %s' % str(ex),
             xbmc.LOGDEBUG)