mercoledì 3 dicembre 2014

Remote Spark per Windows Phone

Remote Spark per Windows Phone è un progetto per gestire in remoto lo Spark device descritto nel mio precedente post.
Questa app, di cui i sorgenti sono pubblicati su codeplex, permette di accendere e spegnere due led e leggere la temperatura dal tuo Spark device.




Come usarlo
1. Costruisci il seguente circuito, usando lo Spark maker kit. Questo circuito è la fusione degli esempi proposti sul sito, blink an led, control leds over the net e measuring temperature:


2. Esegui il flash del seguente firmware sul tuo Spark device da https://www.spark.io/build :

// Define the pins we're going to call pinMode on
int led1 = D0;  // You'll need to wire an LED to this one to see it blink.
int led2 = D1; // This one is the built-in tiny one to the right of the USB jack
int temperature = 0;
double voltage;
// This routine runs only once upon reset
void setup() 
{
  Spark.function("led", ledControl);
  Spark.variable("temperature", &temperature, INT);
  // Initialize D0 + D7 pin as output
  // It's important you do this here, inside the setup() function rather than outside it or in the loop function.
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  // Connect the temperature sensor to A7 and configure it
  // to be an input
  pinMode(A7, INPUT);
}

void loop() 
{
  temperature = analogRead(A7);
  voltage = (temperature * 3.3)/4095;
  temperature = (voltage - 0.5) * 100;
}

int ledControl(String command)
{
    int state = 0;
    int pinNumber = (command.charAt(1) - '0') -1;
    if(pinNumber <0 || pinNumber >1)
      return pinNumber;
      
    if (command.substring(3,7) == "HIGH") 
      state = 1;
    else if(command.substring(3,6) == "LOW") 
      state = 0;
    else    
      return -1;
    digitalWrite(pinNumber, state);
    return 1;
}

3. Scarica il mio progetto da codeplex e imposta il tuo DeviceId e Token nella classe Spark.cs.
4. Esegui il deploy dell'applicazione sul tuo Windows Phone.

Cambiando lo stato dei toggle per accendere/spegnere i led, RemoteSpark invia una richiesta POST a spark cloud:

internal async static Task<LedResponse> Set(string p1, string p2)
        {
            LedResponse result = null;

            using (var request = new HttpClient())
            {
                string postData = string.Format("params={0},{1}", p1, p2);
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                var stringContent = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
                request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                var response = await request.PostAsync(string.Format("https://api.spark.io/v1/devices/{0}/led", DeviceId), stringContent);
                var json = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<LedResponse>(json);
                result.PlainJson = json;
                if (result.return_value == "1")
                    result.ok = true;
            }
            return result;
        }

Premendo il pulsante Get temperature, RemoteSpark invia questa richiesta GET:

 internal async static Task<TemperatureResponse> GetTemperature()
        {
            TemperatureResponse result = null;
            using (var request = new HttpClient())
            {
                request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                request.DefaultRequestHeaders.IfModifiedSince = DateTime.Now;
                var response = await request.GetAsync(string.Format("https://api.spark.io/v1/devices/{0}/temperature", DeviceId));
                var json = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<TemperatureResponse>(json);
            }
            return result;
        }
Il progetto è disponibile per il download e modifiche per i vostri progetti!