Exemple #1
0
int
canberra_play_system_sound(char *theme, char *event_id,
        char *device, char* driver)
{
	int curid = ++id;
	setlocale(LC_ALL, "");
	ca_context *ca = connect_canberra_context(device, driver);
	if (ca == NULL) {
		return -1;
	}

	int playret = ca_context_play(ca, curid,
	                      CA_PROP_CANBERRA_XDG_THEME_NAME, theme,
	                      CA_PROP_EVENT_ID, event_id, NULL);

	if (playret != CA_SUCCESS) {
		g_warning("play: id=%d %s\n", curid, ca_strerror(playret));
		ca_context_destroy(ca);
		return playret;
	}

	// wait for end
	int playing;
	do {
		g_usleep(500 * 1000); // sleep 0.5s
		int ret = ca_context_playing(ca, curid, &playing);
		if (ret != CA_SUCCESS) {
			g_warning("ca_context_playing id=%d %s\n", curid, ca_strerror(ret));
		}
	} while (playing > 0);

	ca_context_destroy(ca);
	return playret;
}
Exemple #2
0
static ca_context*
connect_canberra_context(char* device, char* driver)
{
	ca_context* ca = NULL;
	if (ca_context_create(&ca) != 0) {
		g_warning("Create canberra context failed");
		return NULL;
	}

	// set backend driver
	if (strlen(driver) > 0) {
		if (ca_context_set_driver(ca, driver) != 0 ) {
			g_warning("Set '%s' as backend driver failed", driver);
			ca_context_destroy(ca);
			return NULL;
		}
	}

	if (strlen(device) > 0) {
		if (ca_context_change_device(ca, device) != 0) {
			g_warning("Set '%s' as backend device failed", device);
			ca_context_destroy(ca);
			return NULL;
		}
	}

	if (ca_context_open(ca) != 0) {
		g_warning("Connect the context to sound system failed");
		ca_context_destroy(ca);
		return NULL;
	}

	return ca;
}
Exemple #3
0
int
canberra_play_sound_file(char *file, char *device, char* driver)
{
	int curid = ++id;
	setlocale(LC_ALL, "");
	ca_context *ca = connect_canberra_context(device, driver);
	if (ca == NULL) {
		return -1;
	}

	int playret = ca_context_play(ca, curid,
	                      CA_PROP_MEDIA_FILENAME, file, NULL);

	if (playret != CA_SUCCESS) {
		g_warning("play_sound_file filename:%s id=%d %s\n", file, curid, ca_strerror(playret));
		ca_context_destroy(ca);
		return playret;
	}

	// wait for end
	int playing;
	do {
		g_usleep(500 * 1000); // sleep 0.5s
		int ret = ca_context_playing(ca, curid, &playing);
		if (ret != CA_SUCCESS) {
			g_warning("ca_context_playing id=%d %s\n", curid, ca_strerror(ret));
		}
	} while (playing > 0);

	ca_context_destroy(ca);
	return playret;
}
Exemple #4
0
int main(int argc,char **argv)
{
	FILE	*fp=NULL, *ftmp=NULL;
	char	s[BUF_SIZE], filename[PATH_SIZE], restoreFileName[PATH_SIZE];
	char	*tempname;
	int		n;
	int		numDifferences;
	int		status;
	int		verbose=0, debug=0, write_restore_file=0;

	/* Parse args */
	if (argc == 1) {
		printUsage();
		exit(1);
	}
	if (*argv[1] == '-') {
		for (n=1; n<strlen(argv[1]); n++) {
			if (argv[1][n] == 'v') verbose = 1;
			if (argv[1][n] == 'r') write_restore_file = 1;
			if (argv[1][n] == 'd') printf("debug=%d\n", ++debug);
			if (argv[1][n] == 'h') {printUsage(); exit(1);}
		}
		strcpy(filename, argv[2]);
	} else {
		strcpy(filename, argv[1]);
	}

	status = ca_context_create(ca_disable_preemptive_callback);
	if (!(status & CA_M_SUCCESS)) {
		printf("Can't create CA context.  I quit.\n");
		return(-1);
	}

	/*
	 * Copy to temporary file.
	 * The .sav file is likely to be overwritten while we're using it.
	 */
	fp = fopen(filename,"r");
	if (fp == NULL) {printf("Can't open %s\n", filename); return(-1);}
	tempname = tmpnam(NULL);
	ftmp = fopen(tempname,"w");
	if (ftmp == NULL) {printf("Can't open temp file.\n"); return(-1);}
	while (!feof(fp) && (n=fread(s,1,BUF_SIZE,fp))) {
		fwrite(s,1,n,ftmp);
	}
	fclose(fp); fp = NULL;
	fclose(ftmp); ftmp = NULL;

	if (write_restore_file) {
		strcpy(restoreFileName, filename);
		strcat(restoreFileName, ".asVerify");
	} else {
		strcpy(restoreFileName, "");
	}
	numDifferences = asVerify(tempname, verbose, debug, write_restore_file, restoreFileName);

	remove(tempname);
	ca_context_destroy();
	return(numDifferences);
}
Exemple #5
0
static void
osk_audio_dealloc(OskAudio* audio)
{
    if (audio->ca)
        ca_context_destroy(audio->ca);

    OSK_FINISH_DEALLOC(audio);
}
Exemple #6
0
static void
gsound_context_finalize(GObject *obj)
{
    GSoundContext *self = GSOUND_CONTEXT(obj);

    ca_context_destroy(self->priv->ca);

    G_OBJECT_CLASS(gsound_context_parent_class)->finalize(obj);
}
Exemple #7
0
static void
_eventd_libcanberra_uninit(EventdPluginContext *context)
{
    g_hash_table_unref(context->events);

    ca_context_destroy(context->context);

    g_free(context);

    libeventd_regex_clean();
}
int ca_context_create(ca_context **_c) {
    ca_context *c;
    int ret;
    const char *d;

    ca_return_val_if_fail(!ca_detect_fork(), CA_ERROR_FORKED);
    ca_return_val_if_fail(_c, CA_ERROR_INVALID);

    if (!(c = ca_new0(ca_context, 1)))
        return CA_ERROR_OOM;

    if (!(c->mutex = ca_mutex_new())) {
        ca_context_destroy(c);
        return CA_ERROR_OOM;
    }

    if ((ret = ca_proplist_create(&c->props)) < 0) {
        ca_context_destroy(c);
        return ret;
    }

    if ((d = getenv("CANBERRA_DRIVER"))) {
        if ((ret = ca_context_set_driver(c, d)) < 0) {
            ca_context_destroy(c);
            return ret;
        }
    }

    if ((d = getenv("CANBERRA_DEVICE"))) {
        if ((ret = ca_context_change_device(c, d)) < 0) {
            ca_context_destroy(c);
            return ret;
        }
    }

    *_c = c;
    return CA_SUCCESS;
}
Exemple #9
0
void ChannelAccessThr::run()
{
	//printchannel();	//for Debug
    CHNODE	mynode[register_chacc.size()];
	unsigned int i = 0;
	//const char  SHM_KEY[]  = "0x50000000";
	//const key_t  SHM_KEY  = 0x50000000;
	//char *shmPtr = m_pattach->mCachedData.open (SHM_KEY, register_chacc.size()*sizeof(CachedData), CachedChannelAccess::RT_SHM_CREAT | CachedChannelAccess::RT_SHM_RDWR);
	mutex.lock();
	for ( reg_chacciter = register_chacc.begin(); reg_chacciter != register_chacc.end(); ++reg_chacciter, i++)
	{
		mynode[i].objname	= QString(reg_chacciter->objname.c_str());
		mynode[i].acacc		= m_pattach;
		mynode[i].pvname	= QString(reg_chacciter->pvname.c_str());
		mynode[i].dbrequest	= reg_chacciter->dbrequest;
		mynode[i].chindex	= reg_chacciter->chindex;
		ca_create_channel(reg_chacciter->pvname.c_str(), connectionCallback, &mynode[i], 10, (oldChannelNotify**)&mynode[i].ch_id);
	};
	ca_pend_event(1.0);
	for ( reg_chacciter = register_chacc.begin(), i=0; reg_chacciter != register_chacc.end(); ++reg_chacciter, i++)
	{
		if (mynode[i].onceConnected)
		{
			//qDebug("Conn PV:%s", mynode[i].pvname.toStdString().c_str() );
		}
		else if (mynode[i].onceConnected == 0)
		{
			//qDebug("NotConn PV:%s", mynode[i].pvname.toStdString().c_str() );
			m_pattach->ConnectionStatusObj(mynode[i].objname, -1);
		};
	}
	mutex.unlock();
#if 1
	//in vm image, ca_pend_event(0.0001) stop processing on running;
	while(true)
	{
		if(getStop() == true) break;
		ca_pend_event(0.0001);
	};
    ca_context_destroy();
	exit();
#else
	//in vm image, this code no problem why?? U know?
	ca_pend_event(0.0);
#endif
}
Exemple #10
0
static int canberra_connect ()
{
    int error;

    if (c_context)
        return TRUE;

    ca_context_create (&c_context);
    error = ca_context_open (c_context);
    if (error) {
        N_WARNING (LOG_CAT "can't connect to canberra! %s", ca_strerror (error));
        ca_context_destroy (c_context);
        c_context = 0;
        return FALSE;
    }

    return TRUE;
}
Exemple #11
0
void ChannelAccessThr::run()
{
	unsigned int i = 0;
	vecnode.reserve(register_chacc.size());
	mutex.lock();
	for ( reg_chacciter = register_chacc.begin(); reg_chacciter != register_chacc.end(); ++reg_chacciter, i++)
	{
		CHNODE node;
		node.objname   = QString(reg_chacciter->objname.c_str());
		node.acacc     = m_pattach;
		node.pvname    = QString(reg_chacciter->pvname.c_str());
		node.dbrequest = reg_chacciter->dbrequest;
		node.chindex   = reg_chacciter->chindex;
		node.pItem   = reg_chacciter->pItem;
		vecnode.push_back(node);
		ca_create_channel(reg_chacciter->pvname.c_str(), connectionCallback, (void*)&(vecnode.at(i)), 10, (oldChannelNotify**)&((vecnode.at(i)).ch_id));
	};
	ca_pend_event(1.0);
	for ( reg_chacciter = register_chacc.begin(), i=0; reg_chacciter != register_chacc.end(); ++reg_chacciter, i++)
	{
		CHNODE *pNode  = &vecnode.at(i); 
		if (pNode->onceConnected)
		{
		}
		else if (pNode->onceConnected == 0)
		{
			m_pattach->ConnectionStatusObj(pNode->objname, -1);
		};
	}
	mutex.unlock();

	while(true)
	{
		if(getStop() == true) break;
		ca_pend_event(0.0001);
	};
    ca_context_destroy();
	exit();
}
Exemple #12
0
static gboolean
gsound_context_real_init(GInitable *initable, GCancellable *cancellable, GError **error)
{
    GSoundContext *self = GSOUND_CONTEXT(initable);

    if (self->priv->ca)
        return TRUE;

    int success = ca_context_create(&self->priv->ca);
    
    if (!test_return(success, error))
        return FALSE;

    /* Set a couple of attributes here if we can */
    ca_proplist *pl;
    ca_proplist_create(&pl);

    ca_proplist_sets(pl, CA_PROP_APPLICATION_NAME, g_get_application_name());
    if (g_application_get_default())
    {
        GApplication *app = g_application_get_default ();
        ca_proplist_sets(pl, CA_PROP_APPLICATION_ID,
                         g_application_get_application_id(app));
    }

    success = ca_context_change_props_full(self->priv->ca, pl);

    ca_proplist_destroy(pl);

    if (!test_return(success, error))
    {
        ca_context_destroy(self->priv->ca);
        self->priv->ca = NULL;
    }

    return TRUE;
}
Exemple #13
0
int main (int argc, char *argv[]) {
	GError *error_parsearg = NULL;
	GOptionContext *context;
	GtkWidget *window, *vbox, *hbox2;
	GtkAdjustment *sadj, *madj, *hadj;

#ifdef ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	gtk_init (&argc, &argv);
	notify_init ("Gtimer");
	ca_context_create (&sound);

	context = g_option_context_new (_("- a simple countdown timer"));
	g_option_context_add_main_entries (context, entries, NULL);
#ifdef ENABLE_NLS
	g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
#endif
	if (!g_option_context_parse (context, &argc, &argv, &error_parsearg)) {
		g_fprintf (stderr, "%s\n", error_parsearg->message);
		exit(1);
	}

	vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
	hbox1 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
	hbox2 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);

	gtk_box_set_spacing (GTK_BOX (hbox2), 5);
	gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);

	timer_display = gtk_label_new (NULL);
	reset_display();
	
	sadj = gtk_adjustment_new (0, 0, 60, 1, 1, 0);
	madj = gtk_adjustment_new (0, 0, 60, 1, 1, 0);
	hadj = gtk_adjustment_new (0, 0, 24, 1, 1, 0);
	spin_seconds = gtk_spin_button_new (sadj, 1, 0);
	spin_minutes = gtk_spin_button_new (madj, 1, 0);
	spin_hours = gtk_spin_button_new (hadj, 1, 0);

	gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin_seconds), TRUE);
	gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_seconds), seconds);
	g_object_set (spin_seconds, "shadow-type", GTK_SHADOW_IN, NULL);
	gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin_minutes), TRUE);
	gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_minutes), minutes);
	g_object_set (spin_minutes, "shadow-type", GTK_SHADOW_IN, NULL);
	gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin_hours), TRUE);
	gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_hours), hours);
	g_object_set (spin_hours, "shadow-type", GTK_SHADOW_IN, NULL);

	entry = gtk_entry_new();
	gtk_entry_set_text (GTK_ENTRY (entry), entry_text);
	
	button_timer = gtk_button_new();
	gtk_button_set_label (GTK_BUTTON (button_timer), _("Start"));
	button_reset = gtk_button_new_with_label (_("Reset"));
	gtk_widget_set_sensitive (button_reset, FALSE);

	gtk_box_pack_start (GTK_BOX (hbox1), spin_hours, TRUE, FALSE, 5);
	gtk_box_pack_start (GTK_BOX (hbox1), spin_minutes, TRUE, FALSE, 5);
	gtk_box_pack_start (GTK_BOX (hbox1), spin_seconds, TRUE, FALSE, 5);
	gtk_box_pack_start (GTK_BOX (vbox), timer_display, FALSE, TRUE, 5);
	gtk_box_pack_start (GTK_BOX (hbox2), button_timer, TRUE, TRUE, 0);
	gtk_box_pack_start (GTK_BOX (hbox2), button_reset, TRUE, TRUE, 0);
	gtk_container_add (GTK_CONTAINER (vbox), hbox1);
	gtk_box_pack_start (GTK_BOX (vbox), entry, FALSE, TRUE, 5);
	gtk_container_add (GTK_CONTAINER (vbox), hbox2);

	window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title (GTK_WINDOW (window), "Gtimer");
	gtk_container_add (GTK_CONTAINER (window), vbox);
	gtk_widget_show_all (window);

	g_timeout_add_seconds (1, (GSourceFunc) timer_function, NULL);
	g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
	g_signal_connect (button_timer, "clicked", G_CALLBACK (on_timer_button_clicked), NULL);
	g_signal_connect (button_reset, "clicked", G_CALLBACK (on_reset_button_clicked), NULL);

	gtk_main();
	notify_uninit();
	ca_context_destroy (sound);
	g_option_context_free (context);
	return 0;
}
Exemple #14
0
int cagetFuZE(char *pvName, char *pvValue) {

  RequestT request = get;
  OutputT format = plain;
  chtype dbrType = -1;
  unsigned long reqElems = 0;
  int n, result;
  pv* pvs;
  int i;
  unsigned long nElems;
  

  result = ca_context_create(ca_disable_preemptive_callback);

  pvs = calloc(1, sizeof(pv));

  pvs[0].name = pvName;
  
  connect_pvs(pvs, 1);
  
  for (n = 0; n < 1; n++) {
    
    /* Set up pvs structure */
    /* -------------------- */

    /* Get natural type and array count */
    nElems         = ca_element_count(pvs[n].chid);
    pvs[n].dbfType = ca_field_type(pvs[n].chid);
    pvs[n].dbrType = dbrType;

    /* Set up value structures */
    if (format != specifiedDbr)
      {
	pvs[n].dbrType = dbf_type_to_DBR_TIME(pvs[n].dbfType); /* Use native type */
	if (dbr_type_is_ENUM(pvs[n].dbrType))                  /* Enums honour -n option */
	  {
	    if (enumAsNr) pvs[n].dbrType = DBR_TIME_INT;
	    else          pvs[n].dbrType = DBR_TIME_STRING;
	  }
	else if (floatAsString &&
		 (dbr_type_is_FLOAT(pvs[n].dbrType) || dbr_type_is_DOUBLE(pvs[n].dbrType)))
	  {
	    pvs[n].dbrType = DBR_TIME_STRING;
	  }
      }

    /* Issue CA request */
    /* ---------------- */

    if (ca_state(pvs[n].chid) == cs_conn)
      {
  	nConn++;
  	pvs[n].onceConnected = 1;
  	if (request == callback)
  	  {
  	    /* Event handler will allocate value and set nElems */
  	    pvs[n].reqElems = reqElems > nElems ? nElems : reqElems;
  	    result = ca_array_get_callback(pvs[n].dbrType,
  					   pvs[n].reqElems,
  					   pvs[n].chid,
  					   event_handler,
  					   (void*)&pvs[n]);
  	  } else {
  	  /* We allocate value structure and set nElems */
	  pvs[n].nElems = reqElems && reqElems < nElems ? reqElems : nElems;
  	  pvs[n].value = calloc(1, dbr_size_n(pvs[n].dbrType, pvs[n].nElems));
	  if (!pvs[n].value) {
  	    fprintf(stderr,"Memory allocation failed\n");
  	    return -1;
  	  }
  	  result = ca_array_get(pvs[n].dbrType,
  				pvs[n].nElems,
  				pvs[n].chid,
  				pvs[n].value);
  	}
  	pvs[n].status = result;
      } else {
      pvs[n].status = ECA_DISCONN;
    }
  }

  if (!nConn) return -1;              /* No connection? We're done. */

  /* Wait for completion */
  /* ------------------- */

  result = ca_pend_io(caTimeout);
  if (result == ECA_TIMEOUT) {
    fprintf(stderr, "Read operation timed out: some PV data was not read.\n");
    return -1;
  }

  if (request == callback)    /* Also wait for callbacks */
    {
      if (caTimeout != 0)
        {
	  double slice = caTimeout / PEND_EVENT_SLICES;
	  for (n = 0; n < PEND_EVENT_SLICES; n++)
            {
	      ca_pend_event(slice);
	      if (nRead >= nConn) break;
            }
	  if (nRead < nConn) {
	    fprintf(stderr, "Read operation timed out: some PV data was not read.\n");
	    return -1;
	  }
	} else {
	/* For 0 timeout keep waiting until all are done */
	    while (nRead < nConn) {
	      ca_pend_event(1.0);
	    }
      }
    }


  // Does this kill the connection??
  ca_context_destroy();
  
  sprintf(pvValue, "%s\n", val2str(pvs[0].value, pvs[0].dbrType, 0));

  return 1;

}
Exemple #15
0
int main (int argc, char *argv[])
{
    int returncode = 0;
    int n = 0;
    int result;                 /* CA result */

    int opt;                    /* getopt() current option */
    int digits = 0;             /* getopt() no. of float digits */

    int nPvs;                   /* Number of PVs */
    pv* pvs = 0;                /* Array of PV structures */

    setvbuf(stdout,NULL,_IOLBF,BUFSIZ);   /* Set stdout to line buffering */

    while ((opt = getopt(argc, argv, ":nhm:se:f:g:#:d:0:w:t:")) != -1) {
        switch (opt) {
        case 'h':               /* Print usage */
            usage();
            return 0;
        case 'n':               /* Print ENUM as index numbers */
            enumAsNr=1;
            break;
        case 't':               /* Select timestamp source(s) and type */
            tsSrcServer = 0;
            tsSrcClient = 0;
            {
                int i = 0;
                char c;
                while ((c = optarg[i++]))
                    switch (c) {
                    case 's': tsSrcServer = 1; break;
                    case 'c': tsSrcClient = 1; break;
                    case 'n': break;
                    case 'r': tsType = relative; break;
                    case 'i': tsType = incremental; break;
                    case 'I': tsType = incrementalByChan; break;
                    default :
                        fprintf(stderr, "Invalid argument '%c' "
                                "for option '-t' - ignored.\n", c);
                    }
            }
            break;
        case 'w':               /* Set CA timeout value */
            if(epicsScanDouble(optarg, &caTimeout) != 1)
            {
                fprintf(stderr, "'%s' is not a valid timeout value "
                        "- ignored. ('caget -h' for help.)\n", optarg);
                caTimeout = DEFAULT_TIMEOUT;
            }
            break;
        case '#':               /* Array count */
            if (sscanf(optarg,"%ld", &reqElems) != 1)
            {
                fprintf(stderr, "'%s' is not a valid array element count "
                        "- ignored. ('caget -h' for help.)\n", optarg);
                reqElems = 0;
            }
            break;
        case 'm':               /* Select CA event mask */
            eventMask = 0;
            {
                int i = 0;
                char c, err = 0;
                while ((c = optarg[i++]) && !err)
                    switch (c) {
                    case 'v': eventMask |= DBE_VALUE; break;
                    case 'a': eventMask |= DBE_ALARM; break;
                    case 'l': eventMask |= DBE_LOG; break;
                    default :
                        fprintf(stderr, "Invalid argument '%s' "
                                "for option '-m' - ignored.\n", optarg);
                        eventMask = DBE_VALUE | DBE_ALARM;
                        err = 1;
                    }
            }
            break;
        case 's':               /* Select string dbr for floating type data */
            floatAsString = 1;
            break;
        case 'e':               /* Select %e/%f/%g format, using <arg> digits */
        case 'f':
        case 'g':
            if (sscanf(optarg, "%d", &digits) != 1)
                fprintf(stderr, 
                        "Invalid precision argument '%s' "
                        "for option '-%c' - ignored.\n", optarg, opt);
            else
            {
                if (digits>=0 && digits<=VALID_DOUBLE_DIGITS)
                    sprintf(dblFormatStr, "%%-.%d%c", digits, opt);
                else
                    fprintf(stderr, "Precision %d for option '-%c' "
                            "out of range - ignored.\n", digits, opt);
            }
            break;
        case '0':               /* Select integer format */
            switch ((char) *optarg) {
            case 'x': outType = hex; break;    /* 0x print Hex */
            case 'b': outType = bin; break;    /* 0b print Binary */
            case 'o': outType = oct; break;    /* 0o print Octal */
            default :
                fprintf(stderr, "Invalid argument '%s' "
                        "for option '-0' - ignored.\n", optarg);
            }
            break;
        case '?':
            fprintf(stderr,
                    "Unrecognized option: '-%c'. ('caget -h' for help.)\n",
                    optopt);
            return 1;
        case ':':
            fprintf(stderr,
                    "Option '-%c' requires an argument. ('caget -h' for help.)\n",
                    optopt);
            return 1;
        default :
            usage();
            return 1;
        }
    }

    nPvs = argc - optind;       /* Remaining arg list are PV names */

    if (nPvs < 1)
    {
        fprintf(stderr, "No pv name specified. ('camonitor -h' for help.)\n");
        return 1;
    }
                                /* Start up Channel Access */

    result = ca_context_create(ca_disable_preemptive_callback);
    if (result != ECA_NORMAL) {
        fprintf(stderr, "CA error %s occurred while trying "
                "to start channel access '%s'.\n", ca_message(result), pvs[n].name);
        return 1;
    }
                                /* Allocate PV structure array */

    pvs = calloc (nPvs, sizeof(pv));
    if (!pvs)
    {
        fprintf(stderr, "Memory allocation for channel structures failed.\n");
        return 1;
    }
                                /* Connect channels */

                                      /* Copy PV names from command line */
    for (n = 0; optind < argc; n++, optind++)
    {
        pvs[n].name   = argv[optind];
    }
                                      /* Create CA connections */
    returncode = create_pvs(pvs, nPvs, connection_handler);
    if ( returncode ) {
        return returncode;
    }
                                      /* Check for channels that didn't connect */
    ca_pend_event(caTimeout);
    for (n = 0; n < nPvs; n++)
    {
        if (!pvs[n].onceConnected)
            print_time_val_sts(&pvs[n], pvs[n].reqElems);
    }

                                /* Read and print data forever */
    ca_pend_event(0);

                                /* Shut down Channel Access */
    ca_context_destroy();

    return result;
}
Exemple #16
0
// extern "C"
int epicsShareAPI ca_task_exit ()
{
    ca_context_destroy ();
    return ECA_NORMAL;
}
Exemple #17
0
 /// Destructor.
 ~Canberra() { ca_context_destroy(m_ctx) ;}
Exemple #18
0
int main (int argc, char *argv[])
{
    int i;
    int result;                 /* CA result */
    OutputT format = plain;     /* User specified format */
    RequestT request = get;     /* User specified request type */
    int isArray = 0;            /* Flag for array operation */
    int enumAsString = 0;       /* Force ENUM values to be strings */

    int count = 1;
    int opt;                    /* getopt() current option */
    chtype dbrType = DBR_STRING;
    char *pend;
    EpicsStr *sbuf;
    double *dbuf;
    char *cbuf = 0;
    char *ebuf = 0;
    void *pbuf;
    int len = 0;
    int waitStatus;
    struct dbr_gr_enum bufGrEnum;

    int nPvs;                   /* Number of PVs */
    pv* pvs;                /* Array of PV structures */

    LINE_BUFFER(stdout);        /* Configure stdout buffering */
    putenv("POSIXLY_CORRECT="); /* Behave correct on GNU getopt systems */

    while ((opt = getopt(argc, argv, ":cnlhatsS#:w:p:F:")) != -1) {
        switch (opt) {
        case 'h':               /* Print usage */
            usage();
            return 0;
        case 'n':               /* Force interpret ENUM as index number */
            enumAsNr = 1;
            enumAsString = 0;
            break;
        case 's':               /* Force interpret ENUM as menu string */
            enumAsString = 1;
            enumAsNr = 0;
            break;
        case 'S':               /* Treat char array as (long) string */
            charArrAsStr = 1;
            isArray = 0;
            break;
        case 't':               /* Select terse output format */
            format = terse;
            break;
        case 'l':               /* Select long output format */
            format = all;
            break;
        case 'a':               /* Select array mode */
            isArray = 1;
            charArrAsStr = 0;
            break;
        case 'c':               /* Select put_callback mode */
            request = callback;
            break;
        case 'w':               /* Set CA timeout value */
            if(epicsScanDouble(optarg, &caTimeout) != 1)
            {
                fprintf(stderr, "'%s' is not a valid timeout value "
                        "- ignored. ('caput -h' for help.)\n", optarg);
                caTimeout = DEFAULT_TIMEOUT;
            }
            break;
        case '#':               /* Array count */
            if (sscanf(optarg,"%d", &count) != 1)
            {
                fprintf(stderr, "'%s' is not a valid array element count "
                        "- ignored. ('caput -h' for help.)\n", optarg);
                count = 0;
            }
            break;
        case 'p':               /* CA priority */
            if (sscanf(optarg,"%u", &caPriority) != 1)
            {
                fprintf(stderr, "'%s' is not a valid CA priority "
                        "- ignored. ('caget -h' for help.)\n", optarg);
                caPriority = DEFAULT_CA_PRIORITY;
            }
            if (caPriority > CA_PRIORITY_MAX) caPriority = CA_PRIORITY_MAX;
            break;
        case 'F':               /* Store this for output and tool_lib formatting */
            fieldSeparator = (char) *optarg;
            break;
        case '?':
            fprintf(stderr,
                    "Unrecognized option: '-%c'. ('caput -h' for help.)\n",
                    optopt);
            return 1;
        case ':':
            fprintf(stderr,
                    "Option '-%c' requires an argument. ('caput -h' for help.)\n",
                    optopt);
            return 1;
        default :
            usage();
            return 1;
        }
    }

    nPvs = argc - optind;       /* Remaining arg list are PV names and values */

    if (nPvs < 1) {
        fprintf(stderr, "No pv name specified. ('caput -h' for help.)\n");
        return 1;
    }
    if (nPvs == 1) {
        fprintf(stderr, "No value specified. ('caput -h' for help.)\n");
        return 1;
    }

    nPvs = 1;                   /* One PV - the rest is value(s) */

    epId = epicsEventCreate(epicsEventEmpty);  /* Create empty EPICS event (semaphore) */

                                /* Start up Channel Access */

    result = ca_context_create(ca_enable_preemptive_callback);
    if (result != ECA_NORMAL) {
        fprintf(stderr, "CA error %s occurred while trying "
                "to start channel access.\n", ca_message(result));
        return 1;
    }
                                /* Allocate PV structure array */

    pvs = calloc (nPvs, sizeof(pv));
    if (!pvs) {
        fprintf(stderr, "Memory allocation for channel structure failed.\n");
        return 1;
    }
                                /* Connect channels */

    pvs[0].name = argv[optind] ;   /* Copy PV name from command line */

    result = connect_pvs(pvs, nPvs); /* If the connection fails, we're done */
    if (result) {
        ca_context_destroy();
        return result;
    }

                                /* Get values from command line */
    optind++;

    if (isArray) {
        optind++;               /* In case of array skip first value (nr
                                 * of elements) - actual number of values is used */
        count = argc - optind;

    } else {                    /* Concatenate the remaining line to one string
                                 * (sucks but is compatible to the former version) */
        for (i = optind; i < argc; i++) {
            len += strlen(argv[i]);
            len++;
        }
        cbuf = calloc(len, sizeof(char));
        if (!cbuf) {
            fprintf(stderr, "Memory allocation failed.\n");
            return 1;
        }
        strcpy(cbuf, argv[optind]);

        if (argc > optind+1) {
            for (i = optind + 1; i < argc; i++) {
                strcat(cbuf, " ");
                strcat(cbuf, argv[i]); 
            }
        }

        if ((argc - optind) >= 1)
            count = 1;
        argv[optind] = cbuf;
    }

    sbuf = calloc (count, sizeof(EpicsStr));
    dbuf = calloc (count, sizeof(double));
    if(!sbuf || !dbuf) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

                                /*  ENUM? Special treatment */

    if (ca_field_type(pvs[0].chid) == DBR_ENUM) {

                                /* Get the ENUM strings */

        result = ca_array_get (DBR_GR_ENUM, 1, pvs[0].chid, &bufGrEnum);
        result = ca_pend_io(caTimeout);
        if (result == ECA_TIMEOUT) {
            fprintf(stderr, "Read operation timed out: ENUM data was not read.\n");
            return 1;
        }

        if (enumAsNr) {         /* Interpret values as numbers */

            for (i = 0; i < count; ++i) {
                dbuf[i] = epicsStrtod(*(argv+optind+i), &pend);
                if (*(argv+optind+i) == pend) { /* Conversion didn't work */
                    fprintf(stderr, "Enum index value '%s' is not a number.\n",
                            *(argv+optind+i));
                    return 1;
                }
                if (dbuf[i] >= bufGrEnum.no_str) {
                    fprintf(stderr, "Warning: enum index value '%s' may be too large.\n",
                            *(argv+optind+i));
                }
            }
            dbrType = DBR_DOUBLE;

        } else {                /* Interpret values as strings */

            for (i = 0; i < count; ++i) {
                epicsStrnRawFromEscaped(sbuf[i], sizeof(EpicsStr), *(argv+optind+i), sizeof(EpicsStr));
                *( sbuf[i]+sizeof(EpicsStr)-1 ) = '\0';
                dbrType = DBR_STRING;

                                /* Compare to ENUM strings */
                for (len = 0; len < bufGrEnum.no_str; len++)
                    if (!strcmp(sbuf[i], bufGrEnum.strs[len]))
                        break;

                if (len >= bufGrEnum.no_str) {
                                         /* Not a string? Try as number */
                    dbuf[i] = epicsStrtod(sbuf[i], &pend);
                    if (sbuf[i] == pend || enumAsString) {
                        fprintf(stderr, "Enum string value '%s' invalid.\n", sbuf[i]);
                        return 1;
                    }
                    if (dbuf[i] >= bufGrEnum.no_str) {
                        fprintf(stderr, "Warning: enum index value '%s' may be too large.\n", sbuf[i]);
                    }
                    dbrType = DBR_DOUBLE;
                }
            }
        }

    } else {                    /* Not an ENUM */

        if (charArrAsStr) {
            dbrType = DBR_CHAR;
            ebuf = calloc(len, sizeof(char));
            if(!ebuf) {
                fprintf(stderr, "Memory allocation failed\n");
                return 1;
            }
            count = epicsStrnRawFromEscaped(ebuf, len, cbuf, len-1) + 1;
        } else {
            for (i = 0; i < count; ++i) {
                epicsStrnRawFromEscaped(sbuf[i], sizeof(EpicsStr), *(argv+optind+i), sizeof(EpicsStr));
                *( sbuf[i]+sizeof(EpicsStr)-1 ) = '\0';
            }
            dbrType = DBR_STRING;
        }
    }

                                /* Read and print old data */
    if (format != terse) {
        printf("Old : ");
        result = caget(pvs, nPvs, format, 0, 0);
    }

                                /* Write new data */
    if (dbrType == DBR_STRING) pbuf = sbuf;
    else if (dbrType == DBR_CHAR) pbuf = ebuf;
    else pbuf = dbuf;

    if (request == callback) {
        /* Use callback version of put */
        pvs[0].status = ECA_NORMAL;   /* All ok at the moment */
        result = ca_array_put_callback (
            dbrType, count, pvs[0].chid, pbuf, put_event_handler, (void *) pvs);
    } else {
        /* Use standard put with defined timeout */
        result = ca_array_put (dbrType, count, pvs[0].chid, pbuf);
    }
    result = ca_pend_io(caTimeout);
    if (result == ECA_TIMEOUT) {
        fprintf(stderr, "Write operation timed out: Data was not written.\n");
        return 1;
    }
    if (request == callback) {   /* Also wait for callbacks */
        waitStatus = epicsEventWaitWithTimeout( epId, caTimeout );
        if (waitStatus)
            fprintf(stderr, "Write callback operation timed out\n");

        /* retrieve status from callback */
        result = pvs[0].status;
    }

    if (result != ECA_NORMAL) {
        fprintf(stderr, "Error occured writing data.\n");
        return 1;
    }

                                /* Read and print new data */
    if (format != terse)
        printf("New : ");

    result = caget(pvs, nPvs, format, 0, 0);

                                /* Shut down Channel Access */
    ca_context_destroy();

    return result;
}
void SinglePlotThread::run()
{
#if 0
	// event gathering
	//printchannel();	//for Debug
	mutex.lock();
	mynode.plot	= m_plot;
	chid unit_chid;
	dbr_string_t units;
	QString unitch = m_pvname + ".EGU";
	ca_create_channel(unitch.toStdString().c_str(), 0, 0, 0, &unit_chid);
	ca_pend_io(0.1);
	ca_get(DBR_STRING, unit_chid, (void *)&units);
	ca_pend_io(0.1);
	m_plot->SetUnit(units);

	ca_create_channel(m_pvname.toStdString().c_str(), connectionCallback, &mynode, 0, (oldChannelNotify**)&mynode.mychid);
	ca_replace_access_rights_event(mynode.mychid, accessRightsCallback);
	ca_create_subscription (DBR_TIME_DOUBLE, 0, mynode.mychid, DBE_VALUE|DBE_ALARM, eventCallback, &mynode, &mynode.myevid);
	//ca_add_event(DBR_GR_DOUBLE, mynode.mychid, eventCallback, &mynode, &mynode.myevid);
	mutex.unlock();
	ca_pend_event(0.0);
#else
	//periodic gathering
	mutex.lock();
	chid unit_chid, val_chid;
	dbr_string_t units;

	QString unitch = m_pvname + ".EGU";
	ca_create_channel(unitch.toStdString().c_str(), 0, 0, 0, &unit_chid); ca_pend_io(0.2);
	ca_get(DBR_STRING, unit_chid, (void *)&units); ca_pend_io(0.2);
	m_plot->SetUnit(units);

	struct dbr_time_double data;
	ca_create_channel(m_pvname.toStdString().c_str(), 0, 0, 0, &val_chid);
	ca_pend_io(0.2);

	epicsTime  stamp;

	struct local_tm_nano_sec tm;
	int totsec = 0;
	//for periodic single plot local time
	int year, month, day, hour, min, sec;
	int factor = 1;
	switch(mperiodic)
	{
		case PointOne:
			factor *= 0.1;
			break;
		case PointFive:
			factor *= 0.5;
			break;
		case FiveSec:
			factor *= 5;
			break;
		case TenSec:
			factor *= 10;
			break;
		case OneSec:
		default:
			break;
	};
	while(getStop()==false)
	{
		ca_get(DBR_TIME_DOUBLE, val_chid, (void *)&data);
		ca_pend_io(0.2);
		//qDebug("%s : %f\n",ca_name(val_chid), data.value);
		Epoch2Datetime(year, month, day, hour, min, sec);
#if 0
		stamp = data.stamp;
		tm = (local_tm_nano_sec) stamp;
		totsec = tm.ansi_tm.tm_hour*3600+tm.ansi_tm.tm_min*60+tm.ansi_tm.tm_sec;
		m_plot->GetValue(data.value, totsec,tm.ansi_tm.tm_year,tm.ansi_tm.tm_mon, tm.ansi_tm.tm_mday );
#else
		totsec = hour*3600+min*60+sec;
		m_plot->GetValue(data.value, totsec, year, month, day);
#endif
		usleep(1000000*factor);
	};
	//ca_clear_channel(unit_chid);
	//ca_clear_channel(val_chid);
	ca_context_destroy();
	mutex.unlock();
	exit();
	qDebug("SinglePlot Exit");
#endif
}
Exemple #20
0
static int
canberra_sink_play (NSinkInterface *iface, NRequest *request)
{
    CanberraData *data = (CanberraData*) n_request_get_data (request, CANBERRA_KEY);
    (void) iface;

    N_DEBUG (LOG_CAT "sink play");

    g_assert (data != NULL);

    if (!data->sound_enabled)
        goto complete;

    if (canberra_connect () == FALSE)
        return FALSE;

    static GHashTable *cached_samples = NULL;
    if (!cached_samples) {
        cached_samples = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
    }

    NProplist *props = props = (NProplist*) n_request_get_properties (request);
    ca_proplist *ca_props = 0;
    int error;
    ca_proplist_create (&ca_props);

    /* TODO: don't hardcode */
    ca_proplist_sets (ca_props, CA_PROP_CANBERRA_XDG_THEME_NAME, "jolla-ambient");
    ca_proplist_sets (ca_props, CA_PROP_EVENT_ID, data->filename);

    /* convert all properties within the request that begin with
       "sound.stream." prefix. */
    n_proplist_foreach (props, proplist_to_structure_cb, ca_props);

    if (g_hash_table_lookup_extended (cached_samples, data->filename, NULL, NULL) == FALSE) {
        N_DEBUG (LOG_CAT "caching sample %s", data->filename);
        error = ca_context_cache_full (c_context, ca_props);
        if (error) {
            N_WARNING (LOG_CAT "canberra couldn't cache sample %s", data->filename);
            return FALSE;
        }

        g_hash_table_add (cached_samples, strdup(data->filename));
    } else {
        N_DEBUG (LOG_CAT "sample %s is cached", data->filename);
    }

    error = ca_context_play_full (c_context, 0, ca_props, NULL, NULL);
    ca_proplist_destroy (ca_props);

    if (error) {
        N_WARNING (LOG_CAT "sink play had a warning: %s", ca_strerror (error));

        if (error == CA_ERROR_NOTAVAILABLE ||
                error == CA_ERROR_DISCONNECTED ||
                error == CA_ERROR_STATE ||
                error == CA_ERROR_DESTROYED) {
            ca_context_destroy (c_context);
            c_context = 0;
        }

        return FALSE;
    }

complete:
    /* We do not know how long our samples play, but let's guess we
     * are done in 200ms. */
    data->complete_cb_id = g_timeout_add (200, canberra_complete_cb, data);

    return TRUE;
}
Exemple #21
0
static void dbCaTask(void *arg)
{
    taskwdInsert(0, NULL, NULL);
    SEVCHK(ca_context_create(ca_enable_preemptive_callback),
        "dbCaTask calling ca_context_create");
    dbCaClientContext = ca_current_context ();
    SEVCHK(ca_add_exception_event(exceptionCallback,NULL),
        "ca_add_exception_event");
    epicsEventSignal(startStopEvent);

    /* channel access event loop */
    while (TRUE){
        do {
            epicsEventMustWait(workListEvent);
        } while (dbCaCtl == ctlPause);
        while (TRUE) { /* process all requests in workList*/
            caLink *pca;
            short  link_action;
            int    status;

            epicsMutexMustLock(workListLock);
            if (!(pca = (caLink *)ellGet(&workList))){  /* Take off list head */
                epicsMutexUnlock(workListLock);
                if (dbCaCtl == ctlExit) goto shutdown;
                break; /* workList is empty */
            }
            link_action = pca->link_action;
            pca->link_action = 0;
            if (link_action & CA_CLEAR_CHANNEL) --removesOutstanding;
            epicsMutexUnlock(workListLock);         /* Give back immediately */
            if (link_action & CA_CLEAR_CHANNEL) {   /* This must be first */
                dbCaLinkFree(pca);
                /* No alarm is raised. Since link is changing so what? */
                continue; /* No other link_action makes sense */
            }
            if (link_action & CA_CONNECT) {
                status = ca_create_channel(
                      pca->pvname,connectionCallback,(void *)pca,
                      CA_PRIORITY_DB_LINKS, &(pca->chid));
                if (status != ECA_NORMAL) {
                    errlogPrintf("dbCaTask ca_create_channel %s\n",
                        ca_message(status));
                    printLinks(pca);
                    continue;
                }
                dbca_chan_count++;
                status = ca_replace_access_rights_event(pca->chid,
                    accessRightsCallback);
                if (status != ECA_NORMAL) {
                    errlogPrintf("dbCaTask replace_access_rights_event %s\n",
                        ca_message(status));
                    printLinks(pca);
                }
                continue; /*Other options must wait until connect*/
            }
            if (ca_state(pca->chid) != cs_conn) continue;
            if (link_action & CA_WRITE_NATIVE) {
                assert(pca->pputNative);
                if (pca->putType == CA_PUT) {
                    status = ca_array_put(
                        pca->dbrType, pca->nelements,
                        pca->chid, pca->pputNative);
                } else if (pca->putType==CA_PUT_CALLBACK) {
                    status = ca_array_put_callback(
                        pca->dbrType, pca->nelements,
                        pca->chid, pca->pputNative,
                        putCallback, pca);
                } else {
                    status = ECA_PUTFAIL;
                }
                if (status != ECA_NORMAL) {
                    errlogPrintf("dbCaTask ca_array_put %s\n",
                        ca_message(status));
                    printLinks(pca);
                }
                epicsMutexMustLock(pca->lock);
                if (status == ECA_NORMAL) pca->newOutNative = FALSE;
                epicsMutexUnlock(pca->lock);
            }
            if (link_action & CA_WRITE_STRING) {
                assert(pca->pputString);
                if (pca->putType == CA_PUT) {
                    status = ca_array_put(
                        DBR_STRING, 1,
                        pca->chid, pca->pputString);
                } else if (pca->putType==CA_PUT_CALLBACK) {
                    status = ca_array_put_callback(
                        DBR_STRING, 1,
                        pca->chid, pca->pputString,
                        putCallback, pca);
                } else {
                    status = ECA_PUTFAIL;
                }
                if (status != ECA_NORMAL) {
                    errlogPrintf("dbCaTask ca_array_put %s\n",
                        ca_message(status));
                    printLinks(pca);
                }
                epicsMutexMustLock(pca->lock);
                if (status == ECA_NORMAL) pca->newOutString = FALSE;
                epicsMutexUnlock(pca->lock);
            }
            /*CA_GET_ATTRIBUTES before CA_MONITOR so that attributes available
             * before the first monitor callback                              */
            if (link_action & CA_GET_ATTRIBUTES) {
                status = ca_get_callback(DBR_CTRL_DOUBLE,
                    pca->chid, getAttribEventCallback, pca);
                if (status != ECA_NORMAL) {
                    errlogPrintf("dbCaTask ca_get_callback %s\n",
                        ca_message(status));
                    printLinks(pca);
                }
            }
            if (link_action & CA_MONITOR_NATIVE) {
                size_t element_size;
    
                element_size = dbr_value_size[ca_field_type(pca->chid)];
                epicsMutexMustLock(pca->lock);
                pca->pgetNative = dbCalloc(pca->nelements, element_size);
                epicsMutexUnlock(pca->lock);
                status = ca_add_array_event(
                    ca_field_type(pca->chid)+DBR_TIME_STRING,
                    ca_element_count(pca->chid),
                    pca->chid, eventCallback, pca, 0.0, 0.0, 0.0, 0);
                if (status != ECA_NORMAL) {
                    errlogPrintf("dbCaTask ca_add_array_event %s\n",
                        ca_message(status));
                    printLinks(pca);
                }
            }
            if (link_action & CA_MONITOR_STRING) {
                epicsMutexMustLock(pca->lock);
                pca->pgetString = dbCalloc(1, MAX_STRING_SIZE);
                epicsMutexUnlock(pca->lock);
                status = ca_add_array_event(DBR_TIME_STRING, 1,
                    pca->chid, eventCallback, pca, 0.0, 0.0, 0.0, 0);
                if (status != ECA_NORMAL) {
                    errlogPrintf("dbCaTask ca_add_array_event %s\n",
                        ca_message(status));
                    printLinks(pca);
                }
            }
        }
        SEVCHK(ca_flush_io(), "dbCaTask");
    }
shutdown:
    taskwdRemove(0);
    if (dbca_chan_count == 0)
        ca_context_destroy();
    else
        fprintf(stderr, "dbCa: chan_count = %d at shutdown\n", dbca_chan_count);
    epicsEventSignal(startStopEvent);
}