Ejemplo n.º 1
0
def get_bluetooth_devices(request):
    '''
    Help to asynchronically show all available bluetooth devices
    This method is used by bluetooth.js
    '''
    response_dict = {}
    devices_list = []    
    
    try:
        devices = bluetooth.get_discovered_devices(request.META["REMOTE_ADDR"])
        for device in devices.items():
            device_dict = {}
            device_dict["name"] = device[1]
            device_dict["mac"] = device[0]
            devices_list.append(device_dict)
        response_dict["devices"] = devices_list
        
        logger.debug("Got Bluetooth Devices: %s"% str(devices_list))
        
        return HttpResponse(content = simplejson.dumps(response_dict),
                            content_type = "application/json")
    except Exception, e:
        logger.error("get_bluetooth_devices from %s failed: %s" %
                        (request.META["REMOTE_ADDR"], str(e)))
        return HttpResponse(status = 500)
Ejemplo n.º 2
0
def check_spool_files():
    """
        Check all queued spoolfiles if they have already been processed
        by the Asterisk telephony server;
        Set the corresponding status for the scheduled events
    """
    queued_events = get_all_queued_events()
    for event in queued_events:
        try:
            status = get_spoolfile_status(event.filename)
            if status == "Completed":
                logger.info("Completed sending %s" % unicode(event.sendable))
                event.state = "done"
            elif status == "Expired":
                # Handle what to do if asterisk gave up
                event.retry += 1
                if event.retry < settings.ASTERISK_RETRY:
                    logger.info("%s expired; rescheduling" % unicode(event.sendable))
                    event.send_time = datetime.now() + \
                        timedelta(minutes = settings.ASTERISK_RETRY_TIME)
                    event.state = "new"
                else:
                    event.state = "failed"
                    logger.error("Sending %s failed" % unicode(event.sendable))
            elif status == "Failed":
                # Something really, really went wrong
                event.state = "failed"
                logger.error("Sending %s failed" % unicode(event.sendable))
            event.save()
        except:
            # This means the file has not been found in the done folder
            # nothing has to be done here.
            pass
Ejemplo n.º 3
0
def run(run_only_one_time = False):
    """
        check every second, if an SMS or a Voicecall needs to be sent
        and send it if due
    """
    while True:
        check_spool_files()         
        due_events = get_all_due_events()
                         
        for event in due_events:
            event.state = 'pending'
            try:
                data = event.sendable.get_data_for_sending()
                logger.info("Trying to send: %s" % unicode(event.sendable))
            except Exception, e:
                logger.error("Failed to get data for " + unicode(event) + \
                             " exception " + unicode(e))
                
                event.state = "failed"
                event.save()
                continue
            
            # TODO error handling
            if len(get_all_queued_events()) > 0:
                break

            try:                
                logger.info("  sending: %s" % unicode(data))
                event.filename = data.send()
                #if not run_only_one_time:
                    #time.sleep(20)
            except Exception, e:
                logger.error("Failed to send: " + unicode(data) + \
                             " exception " + unicode(e))
                event.state = "failed"
                event.save()
                    
            event.state = 'queued'
            event.save()
            del data
Ejemplo n.º 4
0
def create_notification(request, notification_type_name = None):
    '''
        Display the form and creates a new notification, but does not
        save it yet. Redirect to authentication if switched on
    '''
    notification_type = NotificationType.objects. \
                              filter(name = notification_type_name)[0]
    nexturl = ""
    backurl = reverse('web_index')
    
    ways_of_communication = get_ways_of_communication(
                                    notification_type.notify_immediately)
    
    if request.method == "POST":
        data = deepcopy(request.POST)
        if notification_type.notify_immediately:
            data['date'] = date.today().strftime('%Y-%m-%d') + \
                            ' ' + DEFAULT_SEND_TIME
        else:
            data['date'] = data.get('date', '') + ' ' + DEFAULT_SEND_TIME
			
        form = NotificationValidationForm(data)

        woc = get_woc_by_id( request.POST['way_of_communication'] )
        if not woc.can_send_immediately:
		    form = NotificationValidationFormBluetooth(data)
		
        if form.is_valid():
            notification = Notification()
            patient = Patient()
            if woc.can_send_immediately:
                patient.phone_number = form.cleaned_data['phone_number']
            notification.date = form.cleaned_data['date']
            notification.notification_type = notification_type
            notification.hospital = Hospital.get_current_hospital()
            notification.way_of_communication = \
                                    form.cleaned_data['way_of_communication']
                                    
            request.session['notification'] = notification
            request.session['patient'] = patient            
            
            logger.info("Create notification via %s" %
                            notification.way_of_communication.verbose_name)
            if notification.way_of_communication == get_woc('bluetooth'):
                return HttpResponseRedirect(reverse("web_list_devices") + \
                                "?next=" + reverse("notifications_send"))
            elif notification.way_of_communication.name in ('sms', 'voice' ):
                return redirect_to_authentication_or(
                                reverse("notifications_save"))

            else:
                logger.error("Unknown way of communication selected.")
                raise Exception ("Unknown way of communication %s " \
                                 %notification.way_of_communication.\
                                 verbose_name + "(this is neither " + \
                                 "bluetooth nor sms or voice)") 
                                
        else:
        
            logger.info("create_notification: Invalid form.")
        
    return render_to_response('notifications/create.html',
                            locals(),
                            context_instance=RequestContext(request))