Next: , Up: The Grand Finale: Bridging Code and Logic   [Contents]


4.4.1 The Living Service: first-service-v3.c

#include <starter/mdns.h>
#include <starter/server.h>
#include <starter/input.h>
#include <starter/output.h>

static GPtrArray *inputs = NULL;
static GPtrArray *outputs = NULL;
static STVersion version = { 0, 3, 0 };

// Simulation: Incrementing our virtual sensor every second
static gboolean update_input (gpointer data) {
    STInput *input = ST_INPUT(data);
    gdouble val = st_input_get_val(input);
    
    val = (val < 100) ? val + 1 : 0;
    
    /* queues notify::val on the affinity context */
    st_input_set_val(input, val, NULL);
    return G_SOURCE_CONTINUE;
}

// Callback: Core wrote our output (GObject property notify)
static void on_output_changed(GObject *obj, GParamSpec *pspec,
                              gpointer data) {
    (void) pspec;
    (void) data;
    g_print("Action Triggered! Core set output to: %lf\n",
            st_output_get_val(ST_OUTPUT(obj)));
}

int main(int argc, char *argv[]) {
    GMainLoop *gloop = g_main_loop_new(NULL, FALSE);
    STServer *server;
    STMDNS *mdns;

    inputs = g_ptr_array_new_full(0, g_object_unref);
    g_ptr_array_add(inputs,
        st_input_new("myFirstInput", "Virtual Sensor",
            ST_UNIT_NULL, 0, 100, 1, 0,
            ST_IO_FLAG_NULL, NULL));

    outputs = g_ptr_array_new_full(0, g_object_unref);
    g_ptr_array_add(outputs,
        st_output_new("myFirstOutput", "Actuator",
            ST_UNIT_NULL, 0, 1, 1, 0,
            ST_IO_FLAG_NULL, NULL));

    // CONNECTING THE SIGNAL: GObject notify for "val"
    g_signal_connect(outputs->pdata[0], "notify::val",
                     G_CALLBACK(on_output_changed), NULL);
    
    server = st_server_new("ST:MyFirstService", &version,
                           inputs, outputs);
    st_server_start(server, 0, NULL);
    mdns = st_mdns_new();
    st_mdns_publish_service(mdns, st_server_get_name(server),
        "_dbus._tcp", st_server_get_port(server));

    // Start the heartbeat: Update the input every 1 second
    g_timeout_add_seconds(1, update_input, inputs->pdata[0]);
    
    g_main_loop_run(gloop);
    return EXIT_SUCCESS;
}