Aes encryption code

Dependencies:   Crypto USBDevice mbed

Fork of larada by MZJ

Revision:
3:cff2f80f0a42
Parent:
2:35e620097381
Child:
4:11520c01d65f
--- a/main.cpp	Wed Mar 02 08:52:50 2016 +0000
+++ b/main.cpp	Tue Mar 08 20:38:38 2016 +0000
@@ -2,7 +2,9 @@
 #include "USBSerial.h"
 #include "IAP.h"
 
-// #define SERIAL //comment for USB operation, uncomment for serial
+#define FAKE_HW
+
+#define SERIAL //comment for USB operation, uncomment for serial
 #define CALIBRATE 0
 #define FUNCTION_CHECK 0
 
@@ -36,6 +38,10 @@
 //#define TEMP_LIMIT_UPPER 485 // No burning allowed (Alphas)
 #define DEFAULT_TEMP_LIMIT_UPPER 65 // No burning allowed (Betas)
 
+#define CRYPT_BUFF_SZ 16
+#define BYTES_PER_100_MS 8 // the number of bytes to send per 100 ms
+#define TIP_UPDATE_INTERVAL_S 3 // Update the tip remaining time every x seconds
+
 float filter = DEFAULT_FILTER;
 uint8_t initial_duty = DEFAULT_INITIAL_DUTY;
 uint8_t nominal_duty = DEFAULT_NOMINAL_DUTY;
@@ -48,9 +54,11 @@
 enum State {
     IDLE,
     WAIT_FOR_TIP,
+    GET_TIP_CONFIG,
     INITIAL_RAMP,
     ACTIVE,
     DONE,
+    PAUSED,
     ERROR,
 };
 
@@ -67,6 +75,19 @@
     DUTY_TOO_LARGE,
 };
 
+enum 
+{
+    READ_TIME_REMAINING=1,
+    WRITE_TIME_REMAINING,
+    RESET_BUFFER // This is a local command, resets the rx buffer
+}tip_command;
+
+struct tip_message
+{
+    int command __attribute__((packed));
+    long value  __attribute__((packed)); 
+};
+
 // Heater control pins
 DigitalOut fan(P0_22);
 DigitalOut heater_pin(P1_27);
@@ -81,8 +102,13 @@
 DigitalOut tip_light(P1_14);
 
 // Other pins
+#ifdef FAKE_HW
+bool tip_sensor = false;
+bool on_off = false;
+#else
 DigitalIn tip_sensor(P0_14);
 DigitalIn on_off(P1_28);
+#endif
 
 #define ON_TIME_S 2700L // The device is active for 45 minutes
 //#define ON_TIME_S 150L
@@ -110,6 +136,9 @@
 volatile float temperature = 0.0;
 unsigned long start_time = 0L;
 unsigned long current_time = 0L;
+uint32_t tip_start_value_s = 0L; // The number of seconds remaing on the tip at the start of the cycle
+uint32_t current_cycle_on_time_s = 0; // The number of seconds this cycle has been operational
+uint32_t last_serial_send = 0;
 bool connected = false;
 volatile uint32_t millis = 0;
 
@@ -118,6 +147,10 @@
 void interpret(char parameter, int value);
 void spin_lights(bool first);
 
+void do_get_tip_config(bool first);
+bool get_message_from_tip(struct tip_message *tm);
+
+
 //INTERRUPT - increment this every ms since the normal mbed timer returns an int and we need an unsigned type
 void tick(void) {millis++;}
 
@@ -146,7 +179,169 @@
   __disable_irq();
   float temperature_copy = temperature;
   __enable_irq();
+  
+  #ifdef FAKE_HW
+  return setpoint;
+  #else
   return temperature_copy;
+  #endif
+}
+
+/**
+ * Packs the message into a string whic can be sent.
+ *
+ * @param *buff - buffer to populate
+ * @param buff_sz - the size of the output buffer
+ * @param *tm - the message to convert into a string
+ */
+bool pack_message(char *buff, int buff_sz, struct tip_message *tm)
+{
+    memset(buff, 0x00, buff_sz);
+    
+    if (buff_sz != CRYPT_BUFF_SZ)
+    {
+        return false; 
+    } 
+    
+    snprintf(buff, buff_sz, "%d:%ld\r\n", tm->command, tm->value);
+    
+    return true;
+}
+
+/**
+ * Waits 100ms from the last send.
+ *
+ * @param last_send - time of last 8 byte send
+ */
+void wait_until_can_send_tip_message(uint32_t last_send)
+{
+    uint32_t counter = 0;
+    
+    while (get_time() - last_send < 100)
+    {
+        wait_ms(1);
+        ++counter;
+    }
+}
+
+/**
+ * Sends a message to the tip. This accounts for the
+ * max number of bytes which can be sent per 100ms.
+ *
+ * @param *tm - the message to send
+ * @returns true if sent successfully
+ */
+bool send_message_to_tip(struct tip_message *tm)
+{
+    static char buff[CRYPT_BUFF_SZ] = {0};
+    static char send_buff[BYTES_PER_100_MS + 1] = {0};
+    static uint32_t last_send = 0;
+    
+    int bytes_sent = 0;
+    
+    pack_message(buff, sizeof(buff), tm);
+    
+    bytes_sent = 0;
+    
+    wait_until_can_send_tip_message(last_send);
+    
+    if (tm->command == RESET_BUFFER)
+    {
+        pc.printf("\r\n"); 
+        return true;   
+    }
+    
+    if (strlen(buff) > BYTES_PER_100_MS)
+    {
+        memcpy(send_buff, buff, BYTES_PER_100_MS);
+        
+        pc.printf("!%s", send_buff); 
+        bytes_sent = BYTES_PER_100_MS;
+        last_send = get_time();
+        
+        while (bytes_sent < strlen(buff))
+        {
+            wait_until_can_send_tip_message(last_send);
+            
+            memcpy(send_buff, buff+bytes_sent, BYTES_PER_100_MS);
+            pc.printf("%s", send_buff); 
+            bytes_sent = BYTES_PER_100_MS;
+            last_send = get_time(); 
+        }
+    }
+    else
+    {
+        pc.printf("!%s", buff); 
+        last_send = get_time(); 
+    }
+    
+    last_serial_send = get_time();
+    
+    return true;
+}
+
+/**
+ * Reads a message from the tip and populates the 
+ * struct given.
+ *
+ * @param *tm - storage for message
+ * @returns true when message read, else false
+ */
+bool get_message_from_tip(struct tip_message *tm)
+{
+    static char buff[CRYPT_BUFF_SZ] = {0};
+    static int pos = 0;
+    bool rval = false;
+    
+    if (tm->command == RESET_BUFFER)
+    { 
+        memset(buff, 0x00, sizeof(buff));
+        pos = 0;
+        
+        return false;    
+    }
+    
+    while (pc.readable())
+    {
+        char t = pc.getc();
+        
+        if (get_time() - last_serial_send < 100)
+        {
+            continue; // Ignore for 100ms
+        }
+        
+        if (t == '\r' || t == '\n')
+        {
+            if (pos >= 4 && buff[0] == '!')
+            {
+                tm->command = (int)(buff[1]-'0');
+                tm->value   = atol(buff+3);  
+                rval = true;
+                
+                break;
+            }
+            
+            pos = 0;
+            memset(buff, 0x00, sizeof(buff));
+        }
+        else
+        {
+            if (pos > sizeof(buff))
+            {
+                pos = 0;    
+            }
+            
+            buff[pos++] = t;    
+        } 
+    }
+    
+    if (rval)
+    {   
+        pos = 0;
+        memset(buff, 0x00, sizeof(buff));
+    }
+    
+    return rval;
 }
 
 //pull the settings saved to flash into memory
@@ -224,7 +419,7 @@
         buffer[i-1] = 0;
         value = atoi(buffer);
       }
-      pc.printf("%c, %d", parameter, value);
+      
       //Serial.println("not _");
       interpret(parameter, value);
       parameter = '_';
@@ -372,7 +567,10 @@
     write_settings();
     pc.printf("Wrote the current control parameters to memory.\r\n");
     break;
-
+  case 'x':
+    tip_sensor = !tip_sensor;
+    pc.printf("tip_sensor = %d\r\n", tip_sensor);
+    break;
 
   default:
     usage();    
@@ -527,7 +725,7 @@
 
 void init(void){
 #ifdef SERIAL
-  pc.baud(115200);
+  pc.baud(4800);
   connected = true;
 #else
   pc.connect();
@@ -541,9 +739,9 @@
   temperature_interrupt.attach(&get_temp, 0.004);
   if(!CALIBRATE)check_limits_interrupt.attach(&check_limits, 0.5);
 
-  read_settings();
-  set_duty(initial_duty);
-  all_off();
+  //read_settings();
+  //set_duty(initial_duty);
+  //all_off();
 }
 
 void check_on_off(void){
@@ -564,6 +762,12 @@
     if(!on_off) state = WAIT_FOR_TIP;
 }
 
+void do_paused(bool first)
+{
+    all_off(); 
+    state = WAIT_FOR_TIP;
+}
+
 // tip neeeds to be present before we can start the cycle
 // later we should also abort the cycle if the tip is removed
 void do_wait_for_tip(bool first){
@@ -584,7 +788,7 @@
       fuel_gage_4.output();
       fuel_gage_4 = 0;
       empty_led.input();
-      state = INITIAL_RAMP;
+      state = GET_TIP_CONFIG;
       if(connected)pc.printf("Found the tip\r\n");
       return;
     }
@@ -613,6 +817,97 @@
     }
 }
 
+/**
+ * Get the configuration data from the tip. Currently just 
+ * reads the time remaining parameter.
+ *
+ * @param first - true when state just changed, else false
+ */
+void do_get_tip_config(bool first)
+{
+    static int _state = 1;
+    static uint32_t last_print = 0;
+    static uint32_t sent_time = 0;
+
+    if (first)
+    {
+        _state = 1;    
+        sent_time = 0;
+        last_print = get_time();
+    }
+    
+    if (connected && get_time() - last_print > 5000)
+    {
+        pc.printf("tip_config: %d\r\n", _state);  
+        last_print = get_time();  
+    }
+    
+    switch (_state)
+    {
+        case 1:
+        {
+            tip_message tm;
+        
+            tm.command = READ_TIME_REMAINING;
+            tm.value   = 10L;
+            
+            if (send_message_to_tip(&tm))
+            {
+                _state = 2;
+                sent_time = get_time();
+            }
+            else
+            {
+                _state = -1;    
+            }
+            break;
+        }
+        case 2:
+        {
+            tip_message tm;
+            tm.command = 0;
+            
+            if (get_message_from_tip(&tm))
+            {
+                tip_start_value_s = tm.value;
+                
+                if (connected)
+                {
+                    pc.printf("TIP_START_VAL: %ld\r\n", tip_start_value_s);
+                }
+                
+                if (tip_start_value_s <= 0)
+                {
+                    if (connected)
+                    {
+                        pc.printf("TIP HAS ZERO VAL\r\n");    
+                    }
+                    
+                    state = PAUSED;
+                }
+                else
+                {
+                    state = INITIAL_RAMP;
+                }
+            }
+            else if (get_time() - sent_time > 3000) // Wait 3s for reply
+            {
+                // Try again
+                tm.command = RESET_BUFFER;
+                get_message_from_tip(&tm);
+                
+                if (connected)
+                {
+                    pc.printf("TIP TIMEOUT\r\n");
+                }
+                
+                _state = 1;
+            }
+            break;
+        }
+    }
+}
+
 //This should quickly take us up from ambient to the setpoint.
 void do_initial_ramp(bool first){
   // set duty to initial_duty and wait to reach the setpoint to break out
@@ -649,18 +944,31 @@
 void do_treatment_cycle(bool first){
   static uint32_t start_time = 0;
   static uint32_t control_timer = 0;
+  static uint32_t last_tip_update = 0;
   uint8_t duty_copy;
   float temperature_copy;
   
   if(first){
     start_time = get_time();
     control_timer = start_time;
+    last_tip_update = 0;
   }
   
   uint32_t current_time = get_time() - start_time;
   
+  // Check if we should update the tip time remaining
+  if (current_time - last_tip_update > TIP_UPDATE_INTERVAL_S * 1000L)
+  {
+    struct tip_message tm;
+    tm.command = WRITE_TIME_REMAINING;
+    tm.value   = tip_start_value_s - (current_time / 1000);
+    
+    send_message_to_tip(&tm);
+    last_tip_update = current_time;
+  }
+  
   // check if we're done
-  if(current_time >= ON_TIME_S * 1000L){
+  if((current_time / 1000L) + current_cycle_on_time_s >= ON_TIME_S){
     if(connected)pc.printf("Done!\r\n");
     //abort(false);
     set_duty(0);
@@ -668,8 +976,26 @@
     state = DONE;
   }
   
-  //if(!tip->in_place())abort(false);
-   
+  if (tip_sensor || current_time > tip_start_value_s * 1000L) 
+  {
+      struct tip_message tm;
+      tm.command = WRITE_TIME_REMAINING;
+      tm.value   = tip_start_value_s - (current_time / 1000);
+    
+      send_message_to_tip(&tm);
+      
+      // The tip has been removed or is out of juice
+      current_cycle_on_time_s += current_time / 1000L;
+      
+      if (connected)
+      {
+        pc.printf("ACTIVE -> PAUSED: %d %ld %ld %ld\r\n", tip_sensor, current_time, current_cycle_on_time_s, tip_start_value_s);
+      }
+      
+      state = PAUSED;
+      return;
+  }
+  
   if(current_time - control_timer > 5000){ // run the control loop every 5 seconds
     control_timer = current_time;
     duty_copy = get_duty();
@@ -702,6 +1028,8 @@
     empty_led.output();
     empty_led = 0;  
   }
+  
+  current_cycle_on_time_s = 0;
 }
 
 void print_state(void){
@@ -726,21 +1054,33 @@
         case ERROR:
           printf("ERROR\r\n");
           break;
+        case PAUSED:
+          printf("PAUSED\r\n");
+          break;
+        case GET_TIP_CONFIG:
+            printf("GET_TIP_CONFIG\r\n");
+            break;
         default: break;
     }
 }
 
 int main(){
+  wait_ms(8000);
+  
   static State last_state = IDLE;
+  
   init();
+  #if 0
   if(FUNCTION_CHECK) functional_check();
   if(CALIBRATE){
       calibrate(true);
       while(1)calibrate(false);
   }
+  #endif
   
   while(1){
-    getInput();
+    
+    //getInput();
     
     check_on_off();
     
@@ -750,7 +1090,7 @@
         last_state = state;
         print_state();
     }
-      
+    
    switch(state){
       case IDLE:
         do_idle(state_change);
@@ -758,6 +1098,9 @@
       case WAIT_FOR_TIP:
         do_wait_for_tip(state_change);
         break;
+      case GET_TIP_CONFIG:
+        do_get_tip_config(state_change);
+        break;
       case INITIAL_RAMP:
         do_initial_ramp(state_change);
         spin_lights(state_change);
@@ -772,9 +1115,13 @@
       case ERROR:
         abort(true);
         break;
+      case PAUSED:
+        do_paused(state_change);
       default: break;
-    }   
+    }  
+    
   }
+  
 }
 
 void spin_lights(bool first){