Versão atual 13-12-2013.
Dependencies: EthernetInterface mbed-rtos mbed
Revision 0:65c41a68b49a, committed 2013-12-13
- Comitter:
- rebonatto
- Date:
- Fri Dec 13 11:42:59 2013 +0000
- Child:
- 1:238ac24e46dd
- Commit message:
- Versao atual 13-12-2013.
Changed in this revision
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/Capture.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,85 @@
+/*
+ * Capture.h
+ *
+ * Created on:
+ * Author:
+ */
+#include "Capture.h"
+
+Semaphore Capture::m_CaptureSemaphore(1); //used to alert the capture thread about a ready capture
+int Capture::m_BufferIndex;
+dmaLinkedListNode Capture::m_Nodes[2] __attribute__((section("AHBSRAM0"))); //this list holds the buffer configuration for the DMA peripheral
+unsigned short int Capture::m_AdcBuffers[2][NUMBER_OF_SAMPLES][NUMBER_OF_CHANNELS] __attribute__((section("AHBSRAM0")));
+
+//This function prepares the capture buffers and starts the DMA peripheral
+void Capture::Start()
+{
+ m_Nodes[0].destAddr = (unsigned int)m_AdcBuffers[0];// HERE GOES THE BUFFER ADDRESS(unsigned int)adval;
+ m_Nodes[0].sourceAddr = (unsigned int)&LPC_ADC->ADGDR;
+ m_Nodes[0].dmaControl = (NUMBER_OF_SAMPLES*NUMBER_OF_CHANNELS)| DMA_DST_WIDTH_HALFWORD | DMA_SRC_WIDTH_HALFWORD | DMA_DST_INCREMENT | DMA_TC_INT;
+ m_Nodes[0].nextNode = (unsigned int)&m_Nodes[1];
+
+ m_Nodes[1].destAddr = (unsigned int)m_AdcBuffers[1];// HERE GOES THE BUFFER ADDRESS(unsigned int)adval2;
+ m_Nodes[1].sourceAddr = (unsigned int)&LPC_ADC->ADGDR;
+ m_Nodes[1].dmaControl = (NUMBER_OF_SAMPLES*NUMBER_OF_CHANNELS)| DMA_DST_WIDTH_HALFWORD | DMA_SRC_WIDTH_HALFWORD | DMA_DST_INCREMENT | DMA_TC_INT;
+ m_Nodes[1].nextNode = (unsigned int)&m_Nodes[0];
+
+ m_BufferIndex=0;
+
+ while(!(LPC_ADC->ADDR0&(1U<<31))); //waits the completion of the ADC Channel 0 capture - for synchronization purposes
+ while(!(LPC_ADC->ADDR0&(1U<<31))); //waits the completion of the ADC Channel 0 capture - for synchronization purposes
+
+ setup_channel(&m_Nodes[0],0,DMA_PERIPHERAL_ADC,DMA_MEMORY);
+}
+
+//This function initializes the ADC and DMA peripherals
+void Capture::Initialize()
+{
+ init_adc(Settings::get_FreqBase()*NUMBER_OF_SAMPLES*NUMBER_OF_CHANNELS);
+ select_channels(ADC_CH_0|ADC_CH_1|ADC_CH_2|ADC_CH_3|ADC_CH_4|ADC_CH_5);
+ LPC_ADC->ADCR |= ADC_MODE_BURST;
+
+ init_dma();
+
+ Start();
+
+ m_CaptureSemaphore.wait();
+}
+
+void Capture::Stop()
+{
+ m_CaptureSemaphore.release(); //release semaphore
+ stop_channel();
+}
+
+void Capture::Wait()
+{
+ m_CaptureSemaphore.wait(osWaitForever);
+}
+
+unsigned short int Capture::GetValue(int nsamples, int nchannel)
+{
+ return ADC_CONVERT(m_AdcBuffers[m_BufferIndex][nsamples][nchannel]);
+}
+
+void Capture::CopyBuffer(int channel, unsigned short int *dest)
+{
+ for(int i=0;i<Settings::get_Samples();i++)
+ {
+ dest[i] = GetValue(i,channel);
+ }
+}
+
+//DMA ISR signals the capture thread about the end of capture event
+extern "C" void DMA_IRQHandler(void)
+{
+ Capture::ISRHandler();
+}
+
+void Capture::ISRHandler()
+{
+ Capture::m_BufferIndex = (~Capture::m_BufferIndex)&1;
+
+ Capture::m_CaptureSemaphore.release();
+ LPC_GPDMA->DMACIntTCClear = 0xFF;
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/CommTCP.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,111 @@
+/*
+ * CommTCP.cpp
+ *
+ * Created on: 07/07/2013
+ * Author: Rebonatto
+ */
+#include "CommTCP.h"
+#include "EventDetector.h"
+
+void CommTCP::CommTCP_Thread(void const *arg)
+{
+ char buffer[5];
+ int ret,i, r;
+ int cont = 0;
+ TCPSocketServer ServerSocket;
+
+ ServerSocket.bind(Settings::get_PortTCP());
+ ServerSocket.listen();
+ printf("TCP Thread starting...\r\n");
+// printf("ServerSocket %s:%d\n", get_address(), get_port());
+
+ while(1){
+ TCPSocketConnection sock;
+ for(i=0; i < Settings::get_MaxTries(); i++){
+ printf("Aguarda Conexao\n");
+ r = ServerSocket.accept(sock);
+ if (r == 0) //Accept Ok
+ break;
+ else{
+ printf("Error in Acceppt\n");
+ wait_ms(Settings::get_DelayTry());
+ }
+ }
+ //sock.set_blocking(true, 1500);
+
+ //printf("Conected %d at %s\n", r, sock.get_address());
+ for(i=0; i < Settings::get_MaxTries(); i++){
+ r = sock.receive(buffer, sizeof(buffer));
+ if (r != -1) // Receive Ok
+ break;
+ else{
+ printf("Erro na recepcao do Socket TCP\n");
+ wait_ms(Settings::get_DelayTry());
+ }
+ buffer[ret] = '\0';
+ }
+ if (cont % 60 == 0)
+ printf("Recebida conexao %d msg TCP: %d chars: *%s*\n", cont++, ret, buffer);
+
+ //printf("Received %d chars:\n*%s*\n", ret, buffer);
+ sock.close();
+ SendAcom(0,0);
+
+ }
+}
+
+void CommTCP::RequestAcom(){
+ // Metodo para solicitar os acompanhamentos
+ char msg[] = "3;-1";
+ TCPSocketConnection s[NEIGHBORS];
+ int escritos, i;
+ //TCPSocketConnection s[NEIGHBORS];
+
+ /*
+ Formato das mensagens de requisicao
+ Tipo ; Tomada
+ Tipos: 1 Solicitacao de fase
+ 2 Solicitacao de diferencial
+ 3 Acompanhamento (manda fase e diferencial)
+ Tomada: Numero da tomada
+ -1 (zero) quando de todas as tomadas
+ */
+ /*Timer t;
+ //t.start();
+
+ for(i=0;i<Settings::get_NumNeighbors();i++){
+ s[i].connect(Settings::get_Neighbor(i), Settings::get_PortTCP());
+ }
+ //t.stop();
+ //printf("The time taken in connection was %d useconds\n", t.read_us());
+ */
+ for(i=0; i< Settings::get_NumNeighbors(); i++){
+ //talvez verificar se o socket est conectado. Se no estiver, destruir objeto e conectar
+ TCPSocketConnection sock;
+ sock.connect(Settings::get_Neighbor(i), Settings::get_PortTCP());
+ //escritos = Settings::get_Socket(i).send_all(msg, sizeof(msg)-1);
+ //printf("Socket %d\n",s[i].is_connected());
+ //Timer t1;
+ //t1.start();
+ escritos = sock.send_all(msg, strlen(msg));
+ wait_ms(100);
+ if(escritos != strlen(msg)){
+ printf("Erro ao enviar mensagem para vizinho\n");
+ break;
+ }
+ //t1.stop();
+ //printf("The time taken in send was %d useconds\n", t1.read_us());
+
+ sock.close();
+
+ }
+}
+
+void CommTCP::SendAcom(int tipo,int tomada){
+ // Aqui chama a funço para enviar um acompanhamento
+ for(int i=0;i<Settings::get_MaxChannels();i++)
+ {
+ EventDetector::get_Detector(i).ExternalTrigger();
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/EventDetector.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,244 @@
+/*
+ * EventDetector.cpp
+ *
+ * Created on:
+ * Author:
+ */
+
+ #include "EventDetector.h"
+ #include "CommTCP.h"
+
+ #define MARCA 10
+
+CaptureMailbox EventDetector::m_EventMailbox;
+EventDetector EventDetector::m_Detector[NUMBER_OF_CHANNELS] = {0,1,2,3,4,5};
+static int cont=0;
+
+CaptureEvent::CaptureEvent()
+{
+}
+
+void CaptureEvent::Setup(char* rfid,int type,int outlet,float mv,float rms,float gain, int offset,float* sin, float* cos)
+{
+ memcpy(m_RFID,rfid,9);
+ m_Type = type;
+ m_OutletNumber = outlet;
+ m_MeanValue = mv;
+ m_RMSValue = rms;
+ m_Gain = gain;
+ m_Offset = offset;
+ memcpy(m_Sin,sin,Settings::get_MaxHarmonics()*sizeof(float));
+ memcpy(m_Cos,cos,Settings::get_MaxHarmonics()*sizeof(float));
+}
+
+EventDetector::EventDetector(int ch)
+{
+ m_Channel = ch;
+ m_OutletTriggered = false;
+ m_EventCounter = 0;
+}
+
+
+void EventDetector::ProcessEvent(float rmsvalue, int t)
+{
+ int gerafuga = 0;
+
+ //wait_ms(500);//TimeDelay(t));
+ //printf("%d time delay\n", TimeDelay(t));
+ if (gerafuga && (t % 2 == 0) ){
+ if (cont % MARCA == 0)
+ printf("Envia Fuga %d %d\n", cont, TimeDelay(t));
+ cont++;
+ // Fuga
+ m_OutletTriggered = true;
+ Capture::Stop();
+ //printf("Passou Stop\n");
+ //CommTCP::RequestAcom();
+ OnTrigger(rmsvalue); //TODO: must change the parameter of this function call
+ //printf("Passou OnTriger\n");
+ Capture::Start();
+ //printf("Passou Start\n");
+ m_EventCounter = 0;
+
+ wait_ms(2);
+ // Termino
+ if (cont % MARCA == 0)
+ printf("Envia Termino\n");
+ m_OutletTriggered = false;
+ Capture::Stop();
+ //printf("Passou Stop\n");
+ OnTrigger(rmsvalue);//TODO: must change the parameter of this function call
+ //printf("Passou onTrigger\n");
+ Capture::Start();
+ //printf("Passou Start\n");
+ m_EventCounter = 0;
+
+ wait_ms(2);
+ }
+ else{
+
+ if(rmsvalue > Settings::get_Limit(m_Channel))
+ {
+ if(!m_OutletTriggered)
+ {
+ if(m_EventCounter < Settings::get_EventLimit())
+ {
+ m_EventCounter++;
+ }
+ else
+ {
+ //printf("Deu Fuga\n");
+ m_OutletTriggered = true;
+ Capture::Stop();
+ OnTrigger(rmsvalue); //TODO: must change the parameter of this function call
+ //CommTCP::RequestAcom();
+ Capture::Start();
+ m_EventCounter = 0;
+ }
+ }
+ else
+ m_EventCounter = 0;
+ }
+ else
+ {
+ if(m_OutletTriggered)
+ {
+ if(m_EventCounter < Settings::get_EventLimit())
+ m_EventCounter++;
+ else
+ {
+ m_OutletTriggered = false;
+ Capture::Stop();
+ OnTrigger(rmsvalue);//TODO: must change the parameter of this function call
+ Capture::Start();
+ m_EventCounter = 0;
+ }
+ }
+ else
+ m_EventCounter = 0;
+ }
+ } // Final gerafuga
+}
+
+void EventDetector::ShowValues(CaptureEvent* e)
+{
+ printf("RFID: %s\n", e->get_RFID());
+ printf("type: %d\n", e->get_Type());
+ printf("OutletNr: %d\n", e->get_OutletNumber());
+ printf("MeanValue: %f\n", e->get_MeanValue());
+ printf("RMSValue: %f\n", e->get_RMSValue());
+ printf("Gain: %f\n", e->get_Gain());
+ printf("Offset: %d\n", e->get_Offset());
+
+ int i;
+ for(i=0;i<12;i++)
+ {
+ printf("Harm %d Sen %f Cos %f\n ", i, e->get_SineValue(i), e->get_CossineValue(i));
+ }
+}
+
+void EventDetector::OnTrigger(float rmsvalue)
+{
+ SendMessage(0,rmsvalue);
+ //printf("Ontrigger::Enviou mensagem\n");
+ /*
+ if(m_OutletTriggered)
+ {
+ for(int i=0;i<Settings::get_MaxChannels();i++)
+ {
+ //wait_ms(300);
+ if(i != m_Channel){
+ //printf("Ontrigger::Enviou acompanhamento %d\n", i);
+ get_Detector(i).ExternalTrigger();
+ }
+ }
+ //printf("Ontrigger::Enviou acompanhamentos %d\n");
+ }
+ */
+}
+
+void EventDetector::ExternalTrigger()
+{
+ SendMessage(1,0);
+}
+
+void EventDetector::SendMessage(int ext,float rmsvalue)
+{
+
+ //Here we must alloc a CaptureEvent object from mailbox pool,
+ CaptureEvent* event = GetMailbox().alloc();
+ //printf("Capturou evento\n");
+ //then initialize the object properly
+
+ unsigned short int buf[NUMBER_OF_SAMPLES];
+ Capture::CopyBuffer(m_Channel,buf);
+
+ if(ext)
+ {
+ rmsvalue = 0;//SignalProcessor::CalculateRMS(buf,m_Channel);
+ }
+
+ float seno[NUMBER_OF_HARMONICS],coss[NUMBER_OF_HARMONICS],mv;
+ //SignalProcessor::CalculateFFT(buf,sen,cos,&mv,1);
+
+ int type=0,outlet_number=0;
+ outlet_number = Settings::get_OutletNumber(m_Channel);
+ outlet_number = Settings::get_Outlet(outlet_number);
+ //Temporario
+ char rfid[9] = "1234560";
+ rfid[7] = (char)outlet_number + '0';
+
+ if(Settings::get_Purpose(m_Channel) == 'p') // phase channel
+ {
+ if(ext!=0)
+ type = 3;
+ else
+ {
+ if(m_OutletTriggered)
+ type = 4; // power on event
+ else
+ type = 5; // power off event
+ }
+ }
+ if(Settings::get_Purpose(m_Channel) == 'd') // diferential channel (leakage)
+ {
+ if(ext!=0)
+ type = 2;
+ else
+ {
+ if(m_OutletTriggered)
+ type = 1; // start leakage event
+ else
+ type = 6; // stop leakage event
+ }
+ }
+
+ if (type == 1 || type == 2 || type == 4) // Calula FFT s nos eventos de fuga, acompanhamento de fuga (diferencial) e liga
+ SignalProcessor::CalculateFFT(buf,seno,coss,&mv,1);
+ /*
+ for(int y=0; y < 12; y++)
+ printf("[%d] sen %f cos %f\n", y, seno[y], coss[y]);
+ */
+ else
+ for(int i=0; i < Settings::get_MaxHarmonics(); i++)
+ seno[i] = coss[i] = 0;
+
+ event->Setup(rfid,type,outlet_number,mv,rmsvalue,Settings::get_Gain(m_Channel),Settings::get_Offset(m_Channel),seno,coss);
+
+ //ShowValues(event);
+
+ //and finally place the object in the mailbox queue.
+ GetMailbox().put(event);
+ //printf("Deu put no evento no mailBox\n");
+}
+
+int EventDetector::TimeDelay(int t){
+ switch (t){
+ case 0: return 300;
+ case 1: return 250;
+ case 2: return 200;
+ case 3: return 250;
+ case 4: return 200;
+ default: return 150;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/Http_post.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,217 @@
+/*
+ * Http_post.cpp
+ *
+ * Created on:
+ * Author:
+ */
+#include "Http_post.h"
+
+extern "C" void mbed_reset();
+
+void HttpPost::HttpPost_Thread(void const *arg)
+{
+ printf("HTTP POST Thread starting...\r\n");
+
+ //inicializar socket
+ // TCPSocketConnection sock;
+
+ CaptureMailbox& mbox = EventDetector::GetMailbox();
+
+ osEvent evt;
+ //printf("aqui\n");
+ while(1)
+ {
+ TCPSocketConnection sock;
+ //printf("Esperando Evento\n");
+ evt = mbox.get();
+
+ if(evt.status == osEventMail)
+ {
+ //printf("Recebido osEventMail...\n ");
+ CaptureEvent* cap = (CaptureEvent*)evt.value.p;
+ DoPost(sock,Settings::get_ServerUrl(),cap);
+ mbox.free(cap);
+ //printf("Enviado e Liberado Mbox ...\n ");
+ //sock.reset_address();
+ }
+ //Thread::yield();
+ }
+}
+
+
+
+void HttpPost::DoPost(TCPSocketConnection sock, char *host, CaptureEvent* dados){
+ char http_cmd[500];
+ int escritos, r=-1, i;
+ FILE *f;
+
+ //Timer t;
+ //t.start();
+
+ //printf("HTTP Socket %s:%d\n", host, sock.get_port());
+ //printf("Antes Connect\n");
+ //rs= sock.connect(host, 80);
+ //printf("%d\n", rs);
+ //printf("Depois Connect ");
+
+ //t.stop();
+ //printf("HHTP: The time taken in connection was %d useconds\n", t.read_us());
+
+ //http_cmd = (char *) malloc(500);
+ memset(http_cmd, 0, 500);
+ PreparePost( dados,http_cmd );
+ //printf("Fuga\n");
+ //printf("%d\n", strlen(http_cmd));
+
+ //http_cmd = prepare_POST( dados );
+
+ //printf("Tamanho comando %d\n", strlen(http_cmd));
+ //printf("Request %d\n [%s]\n", Settings::get_MaxTries(), http_cmd);
+
+
+ for(i=0; i < Settings::get_MaxTries(); i++){
+ r = sock.connect(host, 80);
+ if (r < 0) {
+ printf("Error: Unable to connect to (%s) on port (%d) Try %d\n", host, 80, i);
+ Thread::wait(Settings::get_DelayTry());
+ }
+ else
+ break;
+ }
+ if (r == 0){
+ for(i=0; i < Settings::get_MaxTries(); i++){
+ escritos = sock.send_all(http_cmd, strlen(http_cmd));
+ if(escritos != strlen(http_cmd)){
+ printf("Erro ao gravar no socket HTTP!! Escritos %d\t Tam %d Try %d\n", escritos, strlen(http_cmd), i);
+ Thread::wait(Settings::get_DelayTry());
+ }
+ else
+ break;
+ }
+ if (i != Settings::get_MaxTries() )
+ Thread::wait(Settings::get_DelaySend());
+ else{
+ //printf("Reset\n");
+ f = fopen(FILENAMERESET, "a");
+ if (f == NULL)
+ f = fopen(FILENAMERESET, "w");
+ fprintf(f, "Reset - Connect\n");
+ fclose(f);
+
+ mbed_reset();
+ }
+
+ //Codigo para buscar o retorno do servidor HTTP
+ /*
+ printf("Vai pegar retorno\n");
+
+ char buffer[300];
+ int ret;
+ while (true) {
+ ret = sock.receive(buffer, sizeof(buffer)-1);
+ if (ret <= 0)
+ break;
+ buffer[ret] = '\0';
+ printf("Received %d chars from server:\n%s\n", ret, buffer);
+ }
+ */
+ }
+ else{
+ printf("Reset\n");
+ f = fopen(FILENAMERESET, "a");
+ if (f == NULL)
+ f = fopen(FILENAMERESET, "w");
+ fprintf(f, "Reset - Send\n");
+ fclose(f);
+
+ mbed_reset();
+ }
+
+ sock.close();
+}
+
+void HttpPost::PreparePost(CaptureEvent* dados,char *strfinal){
+ char str[400];
+ char aux[NUMBER_OF_HARMONICS];
+ int i;
+
+ const char *header1 = "POST /capture.php HTTP/1.1\r\n";
+ //"Host: 192.168.1.26\r\n"
+ //"Content-Length: "
+
+ const char *header2 = "\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "\r\n";
+
+ //str = (char *) malloc(450);
+ //strfinal = (char *) malloc(450);
+ memset(str,0,400);
+ memset(strfinal,0,500);
+
+ strcat(strfinal, header1);
+ strcat(strfinal, "Host: ");
+ strcat(strfinal, Settings::get_ServerUrl() );
+ strcat(strfinal, "\r\n");
+
+ sprintf(aux,"TYPE=0%d",dados->get_Type());
+ strcat(str, aux);
+
+ sprintf(aux,"&OUTLET=%02d",dados->get_OutletNumber());
+ strcat(str, aux);
+
+ sprintf(aux,"&RFID=%s", dados->get_RFID());
+ strcat(str,aux);
+
+ sprintf(aux,"&OFFSET=%04d",dados->get_Offset());
+ strcat(str,aux);
+
+ float f = dados->get_Gain();
+ sprintf(aux,"&GAIN=%08X", *(unsigned int*)&f);
+ strcat(str,aux);
+
+ f = dados->get_RMSValue();
+ sprintf(aux,"&RMS=%08X",*(unsigned int*)&f);
+ strcat(str,aux);
+
+ f = dados->get_MeanValue();
+ sprintf(aux,"&MV=%08X",*(unsigned int*)&f);
+ strcat(str,aux);
+
+ strcat(str,"&SIN=");
+ for(i=0;i<Settings::get_MaxHarmonics();i++)
+ {
+ char s[10];
+ //According to RFC1738,RFC3986 the semicolon is a reserved character and must be encoded
+ f = dados->get_SineValue(i);
+ sprintf(s,"%08X",*(unsigned int*)&f);
+ strcat(str,s);
+ if (i < (Settings::get_MaxHarmonics() - 1))
+ strcat(str, "%3B");
+ }
+
+ strcat(str,"&COS=");
+ for(i=0;i<Settings::get_MaxHarmonics();i++)
+ {
+ char c[10];
+ //According to RFC1738,RFC3986 the semicolon is a reserved character and must be encoded
+ f = dados->get_CossineValue(i);
+ sprintf(c,"%08X",*(unsigned int*)&f);
+ strcat(str,c);
+ if (i < (Settings::get_MaxHarmonics()-1))
+ strcat(str, "%3B");
+ }
+ strcat(str,"\r\n");
+
+ char len[5];
+ sprintf(len,"%d",strlen(str));
+
+ strcat(strfinal, "Content-Length: ");
+ strcat(strfinal, len);
+ strcat(strfinal, header2);
+ strcat(strfinal, str);
+ strcat(strfinal, "\r\n");
+
+ //printf("Request=[%s]\n",strfinal);
+ //printf("Tamanho STR %d\n", strlen(str));
+ //printf("Tamanho STRFINAL %d\n", strlen(strfinal));
+ }
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/Settings.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,366 @@
+/*
+ * Settings.cpp
+ *
+ * Created on:
+ * Author:
+ */
+
+#include "Settings.h"
+
+LocalFileSystem local("local");
+
+char* Settings::m_ipaddress = NULL;
+char* Settings::m_netmask = NULL;
+char* Settings::m_gateway = NULL;
+char* Settings::m_serverurl = NULL;
+int Settings::m_dhcp = 0;
+int Settings::m_module_number = 0;
+int Settings::m_MaxChannels = 0;
+int Settings::m_MaxOutlets = 0;
+int Settings::m_FreqBase = 0;
+int Settings::m_MaxHarmonics = 0;
+int Settings::m_Samples = 0;
+int Settings::m_EventLimit = 0;
+int Settings::m_MBoxLength = 0;
+int Settings::m_NumNeighbors = 0;
+int Settings::m_PortTCP = 0;
+int Settings::m_MaxTries = 0;
+int Settings::m_DelayTry = 0;
+int Settings::m_DelaySend = 0;
+
+
+TCPSocketServer Settings::m_ServerSocket;
+TCPSocketConnection Settings::m_Socket[NEIGHBORS];
+
+float Settings::m_gain[NUMBER_OF_CHANNELS];
+int Settings::m_offset[NUMBER_OF_CHANNELS];
+float Settings::m_limit[NUMBER_OF_CHANNELS];
+int Settings::m_outlet_number[NUMBER_OF_CHANNELS];
+char Settings::m_purpose[NUMBER_OF_CHANNELS];
+int Settings::m_outlet[NUMBER_OF_OUTLETS];
+char *Settings::m_Neighbor[NEIGHBORS];
+
+void Settings::LoadDefaults()
+{
+ set_ServerUrl("192.168.1.26");
+
+ set_IpAddress("192.168.1.100");
+
+ set_Netmask("255.255.255.0");
+ set_Gateway("192.168.1.5");
+
+ set_Dhcp(1);
+
+ set_ModuleNumber(1);
+ set_MaxChannels(NUMBER_OF_CHANNELS);
+ set_MaxOutlets(NUMBER_OF_OUTLETS);
+ set_FreqBase(60);
+ set_MaxHarmonics(12);
+ set_Samples(256);
+ set_EventLimit(3);
+ set_MBoxLength(10);
+ set_NumNeighbors(3);
+ set_PortTCP(7890);
+ set_MaxTries(10);
+ set_DelayTry(500);
+ set_DelaySend(50);
+
+ int i;
+
+ for(i=0;i<get_MaxChannels();i++)
+ {
+ set_Gain(i,1);
+ set_Offset(i,2048);
+ set_Limit(i,2048);
+ set_OutletNumber(i,i/2);
+ set_Purpose(i,(i%2)?'d':'p');
+ }
+ for(i=0;i<get_MaxOutlets();i++)
+ {
+ set_Outlet(i,i+1);
+ }
+
+ set_Neighbor(0, "192.168.1.6");
+ set_Neighbor(1, "192.168.1.7");
+ set_Neighbor(2, "192.168.1.8");
+
+ /*
+ m_ServerSocket.bind(get_PortTCP()); // liga o serversocket a porta
+ printf("Settings Default: fez bind na porta %d\n", get_PortTCP());
+
+ for(i=0;i<get_NumNeighbors();i++){
+ m_Socket[i].connect(get_Neighbor(i), get_PortTCP()); // conecta os sockets de envio aos IPs dos vizinhos
+ printf("Settings Default: conectou socket com %s:%d\n", get_Neighbor(i), get_PortTCP());
+ }
+ */
+
+}
+
+void Settings::ReadFile()
+{
+ int i;
+ FILE *f = fopen(FILENAME,"r");
+
+ if(f == NULL)
+ {
+ LoadDefaults();
+ WriteFile();
+ return;
+ }
+ char buf[50];
+ while(fgets(buf,50,f)!= NULL)
+ {
+ char* p = strchr(buf,'\n');
+ if(p)
+ {
+ if(isprint(*(p-1)) == 0) *(p-1) = '\0';
+ *p = '\0';
+ }
+ char **line;
+ int l = split(buf,"=",&line);
+ if(l!=2)continue;
+ if(!strcmp(line[0],"server"))
+ {
+ set_ServerUrl(line[1]);
+ }
+ if(!strcmp(line[0],"address"))
+ {
+ set_IpAddress(line[1]);
+ }
+ if(!strcmp(line[0],"netmask"))
+ {
+ set_Netmask(line[1]);
+ }
+ if(!strcmp(line[0],"gateway"))
+ {
+ set_Gateway(line[1]);
+ }
+ if(!strcmp(line[0],"dhcp"))
+ {
+ if(!strcmp(line[1],"false"))
+ set_Dhcp(0);
+ else
+ set_Dhcp(1);
+ }
+ if(!strcmp(line[0],"module"))
+ {
+ set_ModuleNumber(atoi(line[1]));
+ }
+
+ if(!strcmp(line[0],"FreqBase"))
+ {
+ set_FreqBase(atoi(line[1]));
+ }
+ if(!strcmp(line[0],"MaxChannels"))
+ {
+ set_MaxChannels(atoi(line[1]));
+ }
+ if(!strcmp(line[0],"MaxOutlets"))
+ {
+ set_MaxOutlets(atoi(line[1]));
+ }
+ if(!strcmp(line[0],"Samples"))
+ {
+ set_Samples(atoi(line[1]));
+ }
+ if(!strcmp(line[0],"EventLimit"))
+ {
+ set_EventLimit(atoi(line[1]));
+ }
+ if(!strcmp(line[0],"MBoxLength"))
+ {
+ set_MBoxLength(atoi(line[1]));
+ }
+
+ for(i=0;i<get_MaxChannels();i++)
+ {
+ char x[10];
+ sprintf(x,"gain%d",i);
+ if(!strcmp(line[0],x))
+ {
+ set_Gain(i,atof(line[1]));
+ }
+ sprintf(x,"offset%d",i);
+ if(!strcmp(line[0],x))
+ {
+ set_Offset(i,atoi(line[1]));
+ }
+ sprintf(x,"limit%d",i);
+ if(!strcmp(line[0],x))
+ {
+ set_Limit(i,atof(line[1]));
+ }
+ sprintf(x,"type%d",i);
+ if(!strcmp(line[0],x))
+ {
+ set_Purpose(i,line[1][0]);
+ set_OutletNumber(i,line[1][1]-'0');
+ }
+ }
+
+ for(i=0;i<get_MaxOutlets();i++)
+ {
+ char x[10];
+ sprintf(x,"outlet%d",i);
+ if(!strcmp(line[0],x))
+ {
+ set_Outlet(i,atoi(line[1]));
+ }
+ }
+ if(!strcmp(line[0],"MaxHarmonics"))
+ {
+ set_MaxHarmonics(atoi(line[1]));
+ }
+
+ if(!strcmp(line[0],"NumNeighbors"))
+ {
+ set_NumNeighbors(atoi(line[1]));
+ }
+
+ if(!strcmp(line[0],"TcpPort"))
+ {
+ set_PortTCP(atoi(line[1]));
+ //m_ServerSocket.bind(get_PortTCP()); // liga o serversocket a porta
+ }
+
+ for(i=0;i<get_NumNeighbors();i++)
+ {
+ char x[15];
+ sprintf(x,"Neighbor%d",i);
+ //printf("Vai buscar %d -> %s\n", i, x);
+ if(!strcmp(line[0],x))
+ {
+ // printf("Vai usar %d -> %s\n", i, line[1]);
+ set_Neighbor(i, line[1]) ;
+ //m_Socket[i].connect(get_Neighbor(i), get_PortTCP()); // conecta os sockets de envio aos IPs dos vizinhos
+ }
+ }
+
+ if(!strcmp(line[0],"MaxTries"))
+ {
+ set_MaxTries(atoi(line[1]));
+ //m_ServerSocket.bind(get_PortTCP()); // liga o serversocket a porta
+ }
+
+ if(!strcmp(line[0],"DelayTry"))
+ {
+ set_DelayTry(atoi(line[1]));
+ //m_ServerSocket.bind(get_PortTCP()); // liga o serversocket a porta
+ }
+
+ if(!strcmp(line[0],"DelaySend"))
+ {
+ set_DelaySend(atoi(line[1]));
+ //m_ServerSocket.bind(get_PortTCP()); // liga o serversocket a porta
+ }
+
+ //printf("Param=%s Value=%s\r\n",line[0],line[1]);
+ }
+
+ /*
+ m_ServerSocket.bind(get_PortTCP()); // liga o serversocket a porta
+ printf("Settings LoadFile: fez bind na porta %d\n", get_PortTCP());
+
+ for(i=0;i<get_NumNeighbors();i++){
+ m_Socket[i].connect(get_Neighbor(i), get_PortTCP()); // conecta os sockets de envio aos IPs dos vizinhos
+ printf("Settings LoadFile: conectou socket com %s:%d\n", get_Neighbor(i), get_PortTCP());
+ }
+ */
+
+ fclose(f);
+}
+
+
+void Settings::WriteFile()
+{
+ FILE *f = fopen(FILENAME,"w");
+ int i;
+
+ if(f == NULL)
+ {
+ printf("Error creating settings file\r\n");
+ return;
+ }
+
+ fprintf(f,"server=%s\r\n",get_ServerUrl());
+ fprintf(f,"address=%s\r\n",get_IpAddress());
+ fprintf(f,"netmask=%s\r\n",get_Netmask());
+ fprintf(f,"gateway=%s\r\n",get_Gateway());
+
+ if(get_Dhcp())
+ fprintf(f,"dhcp=true\r\n");
+ else
+ fprintf(f,"dhcp=false\r\n");
+
+ fprintf(f,"module=%d\r\n",get_ModuleNumber());
+ fprintf(f,"MaxChannels=%d\r\n",get_MaxChannels());
+ fprintf(f,"MaxOutlets=%d\r\n",get_MaxOutlets());
+ fprintf(f,"FreqBase=%d\r\n",get_FreqBase());
+ fprintf(f,"Samples=%d\r\n",get_Samples());
+ fprintf(f,"EventLimit=%d\r\n",get_EventLimit());
+ fprintf(f,"MBoxLength=%d\r\n",get_MBoxLength());
+
+ for(i=0;i<get_MaxChannels();i++)
+ {
+ fprintf(f,"gain%d=%0.4f\r\n",i,get_Gain(i));
+ fprintf(f,"offset%d=%d\r\n",i,get_Offset(i));
+ fprintf(f,"limit%d=%0.4f\r\n",i,get_Limit(i));
+ fprintf(f,"type%d=%c%d\r\n",i,get_Purpose(i),get_OutletNumber(i));
+ }
+
+ for(i=0;i<get_MaxOutlets();i++)
+ {
+ fprintf(f,"outlet%d=%d\r\n",i,get_Outlet(i));
+ }
+ fprintf(f,"MaxHarmonics=%d\r\n",get_MaxHarmonics());
+
+ fprintf(f,"NumNeighbors=%d\r\n",get_NumNeighbors());
+ fprintf(f,"TcpPort=%d\r\n",get_PortTCP());
+ for(i=0;i<get_NumNeighbors();i++)
+ {
+ fprintf(f,"Neighbor%d=%s\r\n",i,get_Neighbor(i));
+ }
+ fprintf(f,"MaxTries=%d\r\n",get_MaxTries());
+ fprintf(f,"DelayTry=%d\r\n",get_DelayTry());
+ fprintf(f,"DelaySend=%d\r\n",get_DelaySend());
+
+ fclose(f);
+}
+
+void Settings::ShowValues()
+{
+ printf("ServerUrl: %s\n", get_ServerUrl());
+ printf("IpAddress: %s\n", get_IpAddress());
+ printf("NetMask: %s\n", get_Netmask());
+ printf("Gateway: %s\n", get_Gateway());
+ printf("Dhcp: %d\n", get_Dhcp());
+ printf("ModuleNumber: %d\n", get_ModuleNumber() );
+ printf("FreqBase : %d\n", get_FreqBase() );
+ printf("Samples : %d\n" , get_Samples() );
+ printf("EventLimit : %d\n" , get_EventLimit() );
+ printf("MBoxLength : %d\n" , get_MBoxLength() );
+ printf("MaxChannels : %d\n", get_MaxChannels() );
+ printf("MaxOutlets : %d\n", get_MaxOutlets() );
+ printf("Per Channel\n");
+ int i;
+ for(i=0;i<get_MaxChannels();i++)
+ {
+ printf("Channel %d Gain %f Offset %d Limmit %f Outlet %d Purpose %c\n ", i, get_Gain(i), get_Offset(i), get_Limit(i), get_OutletNumber(i), get_Purpose(i));
+ }
+ printf("Per Outlet \n");
+ for(i=0;i<get_MaxOutlets();i++)
+ {
+ printf("Outlet %d Number %d \n ", i, get_Outlet(i));
+ }
+ printf("MaxHarmonics : %d\n", get_MaxHarmonics() );
+
+ printf("NumNeighbors : %d\n", get_NumNeighbors() );
+ for(i=0;i<get_NumNeighbors();i++)
+ {
+ printf("Neighbor %d Value %s \n ", i, get_Neighbor(i));
+ }
+ printf("TcpPort : %d\n", get_PortTCP() );
+ printf("MaxTries : %d\n", get_MaxTries() );
+ printf("DelayTry : %d\n", get_DelayTry() );
+ printf("DelaySend : %d\n", get_DelaySend() );
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/SignalProcessor.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,174 @@
+/*
+ * SignalProcessor.cpp
+ *
+ * Created on:
+ * Author:
+ */
+
+#include <math.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "SignalProcessor.h"
+
+#define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr
+#define PI 3.14159265358979323846
+
+
+void SignalProcessor::CalculateRMSBulk(float *result)
+{
+ int nChannel,nSample;
+
+ for(nChannel=0;nChannel<Settings::get_MaxChannels();nChannel++)
+ result[nChannel] = 0;
+
+ for(nChannel=0;nChannel<Settings::get_MaxChannels();nChannel++)
+ {
+ for(nSample=0;nSample<Settings::get_Samples();nSample++)
+ {
+
+ unsigned short int v = Capture::GetValue(nSample, nChannel);
+ float val = (float)v;
+
+ val -= Settings::get_Offset(nChannel);
+ val /= Settings::get_Gain(nChannel);
+ val *= val;
+ result[nChannel] += val;
+ }
+ result[nChannel] /= (float)Settings::get_Samples();
+ result[nChannel] = sqrt(result[nChannel]);
+ }
+}
+
+float SignalProcessor::CalculateRMS(unsigned short int *buffer,int nChannel)
+{
+ float result=0;
+ int nSample;
+
+ for(nSample=0;nSample<Settings::get_Samples();nSample++)
+ {
+
+ unsigned short int v = buffer[nSample];
+ float val = (float)v;
+
+ val -= Settings::get_Offset(nChannel);
+ val /= Settings::get_Gain(nChannel);
+ val *= val;
+ result += val;
+ }
+ result /= (float)Settings::get_Samples();
+ result = sqrt(result);
+ return result;
+}
+
+void SignalProcessor::CalculateFFT(unsigned short int *buffer,float *sen,float *cos,float *vm,int sign)
+{
+ float* fft = ComplexFFT(buffer,1); //deve desalocar memoria do ptr retornado
+ /*
+ Mapa do vetor fft.
+ O vetor tem 2 vezes o no. de amostras. Cada par de valores (portanto n e n+1), representam, respectivamente
+ COS e SEN.
+ Os dois primeiros valores reprensetam a frequencia 0Hz, portanto sao atribuidas ao valor medio.
+ Os demais pares de valores representam a fundamental e suas harmonicas,
+ sendo que se a fundamental for 60Hz, teremos: 60,120,180,240...
+ Para a nossa aplicacao apenas as 12 primeiras harmonicas serao utilizadas (720Hz)
+ */
+ *vm = fft[0];
+
+ for(int i=1;i<Settings::get_MaxHarmonics()+1;i++)
+ //for(int i=1;i<257;i++) // para testar com a FFT inversa.
+ {
+ cos[i-1] = fft[i*2];
+ sen[i-1] = fft[i*2+1]*-1;
+ }
+
+ free(fft);
+}
+
+
+float* SignalProcessor::ComplexFFT(unsigned short int* data, int sign)
+{
+
+ //variables for the fft
+ unsigned long n,mmax,m,j,istep,i;
+ double wtemp,wr,wpr,wpi,wi,theta,tempr,tempi;
+ float *vector;
+ //the complex array is real+complex so the array
+ //as a size n = 2* number of complex samples
+ //real part is the data[index] and
+ //the complex part is the data[index+1]
+
+ //new complex array of size n=2*sample_rate
+ //if(vector==0)
+ //vector=(float*)malloc(2*SAMPLE_RATE*sizeof(float)); era assim, define estava em Capture.h
+ vector=(float*)malloc(2*Settings::get_Samples()*sizeof(float));
+ memset(vector,0,2*Settings::get_Samples()*sizeof(float));
+
+ //put the real array in a complex array
+ //the complex part is filled with 0's
+ //the remaining vector with no data is filled with 0's
+ //for(n=0; n<SAMPLE_RATE;n++)era assim, define estava em Capture.h
+ for(n=0; n<Settings::get_Samples();n++)
+ {
+ if(n<Settings::get_Samples())
+ vector[2*n]=(float)data[n];
+ else
+ vector[2*n]=0;
+ vector[2*n+1]=0;
+ }
+
+ //binary inversion (note that the indexes
+ //start from 0 witch means that the
+ //real part of the complex is on the even-indexes
+ //and the complex part is on the odd-indexes)
+ //n=SAMPLE_RATE << 1; //multiply by 2era assim, define estava em Capture.h
+ n=Settings::get_Samples() << 1; //multiply by 2
+ j=0;
+ for (i=0;i<n/2;i+=2) {
+ if (j > i) {
+ SWAP(vector[j],vector[i]);
+ SWAP(vector[j+1],vector[i+1]);
+ if((j/2)<(n/4)){
+ SWAP(vector[(n-(i+2))],vector[(n-(j+2))]);
+ SWAP(vector[(n-(i+2))+1],vector[(n-(j+2))+1]);
+ }
+ }
+ m=n >> 1;
+ while (m >= 2 && j >= m) {
+ j -= m;
+ m >>= 1;
+ }
+ j += m;
+ }
+ //end of the bit-reversed order algorithm
+
+ //Danielson-Lanzcos routine
+ mmax=2;
+ while (n > mmax) {
+ istep=mmax << 1;
+ theta=sign*(2*PI/mmax);
+ wtemp=sin(0.5*theta);
+ wpr = -2.0*wtemp*wtemp;
+ wpi=sin(theta);
+ wr=1.0;
+ wi=0.0;
+ for (m=1;m<mmax;m+=2) {
+ for (i=m;i<=n;i+=istep) {
+ j=i+mmax;
+ tempr=wr*vector[j-1]-wi*vector[j];
+ tempi=wr*vector[j]+wi*vector[j-1];
+ vector[j-1]=vector[i-1]-tempr;
+ vector[j]=vector[i]-tempi;
+ vector[i-1] += tempr;
+ vector[i] += tempi;
+ }
+ wr=(wtemp=wr)*wpr-wi*wpi+wr;
+ wi=wi*wpr+wtemp*wpi+wi;
+ }
+ mmax=istep;
+ }
+ //end of the algorithm
+
+ return vector;
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_getparam.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,97 @@
+#include "TelnetServer.h"
+
+#include "Settings.h"
+
+ char *wrong_args_msg_get = "Wrong number of arguments.\r\n\r\nUsage: getparam <parameter name>\r\n";
+ char *param_not_found_msg_get = "Parameter not found.\r\n\r\n";
+
+
+int TelnetServer::GetParamCommand(TCPSocketConnection *conn,char** argv,int argc)
+{
+
+ if(argc != 2)
+ {
+ conn->send(wrong_args_msg_get,strlen(wrong_args_msg_get));
+ return 0;
+ }
+
+ printf("Getting parameter\n");
+
+ if(!strcmp(argv[1],"ipserver"))
+ {
+ conn->send("\r\nipserver=",strlen("\r\nipserver="));
+ conn->send(Settings::get_ServerUrl(),strlen(Settings::get_ServerUrl()));
+ conn->send("\r\n",strlen("\r\n"));
+ return 0;
+ }
+
+ if(!strcmp(argv[1],"module"))
+ {
+ char b[12];
+ conn->send("\r\nmodule=",strlen("\r\nmodule="));
+ sprintf(b,"%d\r\n",Settings::get_ModuleNumber());
+ conn->send(b,strlen(b));
+ return 0;
+ }
+
+ int i;
+ for(i=0;i<Settings::get_MaxOutlets();i++)
+ {
+ char b[12];
+ sprintf(b,"outlet%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ sprintf(b,"\r\noutlet%d=%d\r\n",i,Settings::get_Outlet(i));
+ conn->send(b,strlen(b));
+ return 0;
+ }
+ }
+ for(i=0;i<Settings::get_MaxChannels();i++)
+ {
+ char b[12];
+ sprintf(b,"gain%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ sprintf(b,"\r\ngain%d=%f\r\n",i,Settings::get_Gain(i));
+ printf("Getting gain\n");
+ conn->send(b,strlen(b));
+ return 0;
+ }
+
+ sprintf(b,"offset%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ sprintf(b,"\r\noffset%d=%d\r\n",i,Settings::get_Offset(i));
+ conn->send(b,strlen(b));
+ return 0;
+ }
+
+ sprintf(b,"limit%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ sprintf(b,"\r\nlimit%d=%f\r\n",i,Settings::get_Limit(i));
+ conn->send(b,strlen(b));
+ return 0;
+ }
+
+ sprintf(b,"outlet_number%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ sprintf(b,"\r\noutlet_number%d=%d\r\n",i,Settings::get_OutletNumber(i));
+ conn->send(b,strlen(b));
+ return 0;
+ }
+
+ sprintf(b,"purpose%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ sprintf(b,"\r\npurpose%d=%c\r\n",i,Settings::get_Purpose(i));
+ conn->send(b,strlen(b));
+ return 0;
+ }
+ }
+
+ conn->send(param_not_found_msg_get,strlen(param_not_found_msg_get));
+ return 0;
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_help.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,25 @@
+
+#include "TelnetServer.h"
+
+
+char *header_msg_help = "This is a list of available commands:\r\n\r\n";
+
+int TelnetServer::HelpCommand(TCPSocketConnection *conn, char ** argv,int argc)
+{
+ printf("Entering help command...\n");
+
+ conn->send(header_msg_help,strlen(header_msg_help));
+
+ int i;
+ for(i=0;(unsigned int)cmds[i].pfn != 0;i++)
+ {
+
+ Thread::wait(20);
+ conn->send(cmds[i].command_name,strlen(cmds[i].command_name));
+
+ //printf("cmd=%s\n",cmds[i].command_name);
+ conn->send("\r\n",2);
+ }
+
+ return 0;
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_listparam.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,29 @@
+#include "TelnetServer.h"
+#define NUMBERPARAM 3
+
+char *msg_list_param[NUMBERPARAM] = { "bla",
+ "bla2",
+ "Bla23" };
+
+char *header_msg_listparam = "This is a list of available parameters:\r\n\r\n";
+
+
+int TelnetServer::ListParamCommand(TCPSocketConnection *conn, char ** argv,int argc)
+{
+ printf("Entering list parameters command...\n");
+
+ conn->send(header_msg_listparam,strlen(header_msg_listparam));
+
+ int i;
+ for(i=0;i < NUMBERPARAM ;i++)
+ {
+
+ Thread::wait(20);
+ conn->send(msg_list_param[i],strlen(msg_list_param[i]));
+
+ //printf("Parameter = %s\n",msg_list_param[i]);
+ conn->send("\r\n",2);
+ }
+
+ return 0;
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_remove.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,36 @@
+#include "TelnetServer.h"
+
+char *header_msg_remove = "File removed successfully\r\n\r\n";
+char *wrong_args_msg_remove = "Wrong number of arguments.\r\n\r\nUsage: remove <filename>\r\n";
+char *file_not_found_msg_remove = "File not found.\r\n\r\n";
+
+extern LocalFileSystem local;
+
+int TelnetServer::RemoveCommand(TCPSocketConnection *conn,char** argv,int argc)
+{
+
+ if(argc != 2)
+ {
+ conn->send(wrong_args_msg_remove,strlen(wrong_args_msg_remove));
+ return 0;
+ }
+
+ char fullpath[256];
+ strcpy(fullpath,"/local/");
+ strcat(fullpath,argv[1]);
+ printf("File = %s\n",fullpath);
+ FILE* f = fopen(fullpath,"r");
+ if(f == NULL)
+ {
+ conn->send(file_not_found_msg_remove,strlen(file_not_found_msg_remove));
+ return 0;
+ }
+
+ fclose(f);
+
+ local.remove(argv[1]);
+
+ conn->send(header_msg_remove,strlen(header_msg_remove));
+
+ return 0;
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_reset.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,20 @@
+#include "TelnetServer.h"
+
+extern "C" void mbed_reset();
+
+char *header_msg_reset = "Resetting...";
+
+
+int TelnetServer::ResetCommand(TCPSocketConnection *conn,char** argv,int argc)
+{
+
+ conn->send(header_msg_reset,strlen(header_msg_reset));
+
+ conn->close();
+
+ delete conn;
+
+ mbed_reset();
+
+ return 0;
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_setparam.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,100 @@
+#include "TelnetServer.h"
+
+#include "Settings.h"
+
+char *wrong_args_msg_set = "Wrong number of arguments.\r\n\r\nUsage: setparam <parameter name> <parameter value>\r\n";
+char *param_not_found_msg_set = "Parameter not found.\r\n\r\n";
+char *bad_argument_set = "The parameter supplied does not have a valid format.\r\n\r\n";
+
+int TelnetServer::SetParamCommand(TCPSocketConnection *conn,char** argv,int argc)
+{
+
+ if(argc != 3)
+ {
+ conn->send(wrong_args_msg_set,strlen(wrong_args_msg_set));
+ return 0;
+ }
+
+
+ if(!strcmp(argv[1],"ipserver"))
+ {
+ ip_addr_t addr;
+ if(ipaddr_aton(argv[2],&addr) != ERR_OK)
+ {
+ conn->send(bad_argument_set,strlen(bad_argument_set));
+ }
+ else
+ {
+ Settings::set_IpAddress(argv[2]);
+ Settings::WriteFile();
+ }
+ return 0;
+ }
+
+ if(!strcmp(argv[1],"module"))
+ {
+ Settings::set_ModuleNumber(atoi(argv[2]));
+ Settings::WriteFile();
+ return 0;
+ }
+
+ int i;
+ for(i=0;i<3;i++)
+ {
+ char b[12];
+ sprintf(b,"outlet%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ Settings::set_Outlet(i,atoi(argv[2]));
+ Settings::WriteFile();
+ return 0;
+ }
+ }
+ for(i=0;i<6;i++)
+ {
+ char b[12];
+ sprintf(b,"gain%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ Settings::set_Gain(i,atof(argv[2]));
+ Settings::WriteFile();
+ return 0;
+ }
+
+ sprintf(b,"offset%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ Settings::set_Offset(i,atoi(argv[2]));
+ Settings::WriteFile();
+ return 0;
+ }
+
+ sprintf(b,"limit%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ Settings::set_Limit(i,atof(argv[2]));
+ Settings::WriteFile();
+ return 0;
+ }
+
+ sprintf(b,"outlet_number%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ Settings::set_OutletNumber(i,atoi(argv[2]));
+ Settings::WriteFile();
+ return 0;
+ }
+
+ sprintf(b,"purpose%d",i);
+ if(!strcmp(argv[1],b))
+ {
+ Settings::set_Purpose(i,argv[2][0]);
+ Settings::WriteFile();
+ return 0;
+ }
+ }
+
+ conn->send(param_not_found_msg_set,strlen(param_not_found_msg_set));
+ return 0;
+
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_update.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,92 @@
+#include "TelnetServer.h"
+
+
+char *header_msg = "firmware update\r\n\r\n";
+char *usage_msg = "Wrong arguments\r\nUsage: update <firmware filename>\r\n\r\n";
+char *invalid_filename_msg = "Invalid filename. It must have at most 8 characters in the name and 3 in the extension\r\n\r\n";
+char *file_does_not_exist_msg = "A file with the supplied filename does not exist.\r\n\r\n";
+char *version_does_not_exist_msg = "Could not open version.txt. The update operation cannot continue.\r\n\r\n";
+char *unable_to_create_remove_msg = "Unable to create remove.txt. The update operation cannot continue.\r\n\r\n";
+char *unable_to_truncate_version_msg = "Unable to truncate version.txt. The update operation cannot continue.\r\n\r\n";
+char *operation_successful_msg = "Operation was completed successfully. Now resetting...\r\n\r\n";
+
+extern LocalFileSystem local;
+extern "C" void mbed_reset();
+
+int TelnetServer::UpdateCommand(TCPSocketConnection *conn,char** argv,int argc)
+{
+ char old_filename[20];
+ char new_filename[20];
+
+ conn->send(header_msg,strlen(header_msg));
+ //0 - check if the file informed exists
+ if(argc != 2)
+ {
+ conn->send(usage_msg,strlen(usage_msg));
+ return 0;
+ }
+
+ strcpy(new_filename,"/local/");
+ strcat(new_filename,argv[1]);
+ new_filename[19] = '\0';
+ printf("New filename = %s\n",new_filename);
+
+ if(strlen(new_filename) > 19)
+ {
+ conn->send(invalid_filename_msg,strlen(invalid_filename_msg));
+ return 0;
+ }
+
+ FILE* fn = fopen(new_filename,"r");
+ if(fn == NULL)
+ {
+ conn->send(file_does_not_exist_msg,strlen(file_does_not_exist_msg));
+ return 0;
+ }
+ fclose(fn);
+
+ //1 - write remove.txt with the current FW filename
+ fn = fopen("/local/version.txt","r");
+ if(fn == NULL)
+ {
+ conn->send(version_does_not_exist_msg,strlen(version_does_not_exist_msg));
+ return 0;
+ }
+ int rd = fread(old_filename,1,19,fn);
+ old_filename[rd]='\0';
+ fclose(fn);
+
+ fn = fopen("/local/remove.txt","w");
+ if(fn == NULL)
+ {
+ conn->send(unable_to_create_remove_msg,strlen(unable_to_create_remove_msg));
+ return 0;
+ }
+ fwrite(old_filename,1,strlen(old_filename),fn);
+ fclose(fn);
+
+ //2 - write version.txt with the new FW filename
+ fn = fopen("/local/version.txt","w");
+ if(fn == NULL)
+ {
+ conn->send(unable_to_truncate_version_msg,strlen(unable_to_truncate_version_msg));
+ return 0;
+ }
+ fwrite(new_filename,1,strlen(new_filename),fn);
+ fclose(fn);
+
+ //3 - remove the old fw file
+ local.remove(old_filename);
+
+ //4 - remove remove.txt
+ local.remove("remove.txt");
+
+ conn->send(operation_successful_msg,strlen(operation_successful_msg));
+
+ //5 - reset
+ delete conn;
+
+ mbed_reset();
+
+ return 0;
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetCommands/telnet_version.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,44 @@
+#include "TelnetServer.h"
+
+char *header_msg_version = "Protegemed - version information:\r\n\r\n";
+char *fwversion_msg = "FW Version: ";
+char *builddate_msg = "\r\nBuild Date: ";
+char *fwfile_msg = "\r\nFW Filename: ";
+char *fwfile_not_available_msg = "Information not available";
+
+#define VERSION_TEXT "2.0"
+#define BUILD_TEXT __TIME__
+
+int TelnetServer::VersionCommand(TCPSocketConnection *conn,char** argv,int argc)
+{
+
+
+ conn->send(header_msg_version,strlen(header_msg_version));
+
+ conn->send(fwversion_msg,strlen(fwversion_msg));
+
+ conn->send(VERSION_TEXT,strlen(VERSION_TEXT));
+
+ conn->send(builddate_msg,strlen(builddate_msg));
+
+ conn->send(BUILD_TEXT,strlen(BUILD_TEXT));
+ //printf("Version\n");
+ conn->send(fwfile_msg,strlen(fwfile_msg));
+
+ FILE *f = fopen("/local/version.txt","r");
+ if(f != NULL)
+ {
+ char buf[20];
+ fread(buf,1,19,f);
+ buf[19]='\0';
+ conn->send(buf,strlen(buf));
+ fclose(f);
+ }
+ else
+ {
+ conn->send(fwfile_not_available_msg,strlen(fwfile_not_available_msg));
+ }
+
+ conn->send("\r\n\r\n",strlen("\r\n\r\n"));
+ return 0;
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TelnetServer.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,206 @@
+/*
+ Original autor: Francisco
+ Modificacao do uso da rede: rebonatto
+*/
+
+
+#include "TelnetServer.h"
+
+#include "Split.h"
+
+#define OPT_WILL 251
+#define OPT_WONT 252
+#define OPT_DO 253
+#define OPT_DONT 254
+
+char* welcome_msg = "Protegemed - welcome to telnet\r\nType 'help' for a list of commands\r\n";
+char* prompt_msg = "\r\n$ ";
+char iac_will_echo[] = {0xFF,0xFB,0x01};
+char erase_cmd[] = { 0x1B,0x5B,0x44,0x1B,0x5B,0x4B};
+
+const struct telnet_cmd_handler TelnetServer::cmds[] = {
+ {"exit",(cmd_function)-1},
+ {"help",TelnetServer::HelpCommand},
+ {"reset",TelnetServer::ResetCommand},
+ {"remove",TelnetServer::RemoveCommand},
+ {"listparam",TelnetServer::ListParamCommand},
+ {"getparam",TelnetServer::GetParamCommand},
+ {"setparam",TelnetServer::SetParamCommand},
+ {"version",TelnetServer::VersionCommand},
+ {"update",TelnetServer::UpdateCommand},
+ {"",(cmd_function)0}
+};
+
+void TelnetServer::TelnetServer_Thread(void const* arg)
+{
+ int r=0;
+ printf("Telnet Thread starting... \r\nCommands up to 100 chars\n");
+
+ TCPSocketServer server;
+
+ server.bind(23);
+ server.listen();
+
+ while(1)
+ {
+ TCPSocketConnection* conn ;
+ TCPSocketConnection aux;
+ r = server.accept(aux);
+ conn = &aux;
+ printf("Aceitou conexao \n");
+ if (r != 0){
+ printf("Error in connection\n");
+ exit(1);
+ }
+
+ TelnetSession(conn);
+ printf("Fechou\n");
+ conn->close();
+ }
+}
+
+void TelnetServer::TelnetSession(TCPSocketConnection *conn)
+{
+ int r;
+ int buffer_ptr=0;
+
+ printf("Connected to %s:%d\n",conn->get_address(),conn->get_port());
+
+ conn->send(welcome_msg,strlen(welcome_msg));
+ conn->send(prompt_msg,strlen(prompt_msg));
+
+ conn->set_blocking(true);
+
+ while(1)
+ {
+ char buf_rec[260];
+ unsigned char buf[260];
+ char buffer[260];
+
+ //printf("Vai recevber\n");
+ r = conn->receive(buf_rec, strlen(buf_rec) );
+
+ /* need memcpy becouse commands are ready to unsigned char and tcp receive char */
+ memcpy(buf, buf_rec, r);
+
+ //printf("Receive %d\n", r);
+
+ if(r == -1)
+ {
+ printf("Error %d %s\n", r, buf);
+ break;
+ }
+
+ if (r > 120){
+ printf("Max command length = 100 chars\n");
+ //send
+ break;
+ }
+
+ //printf("Got Here\n");
+
+ for(int i=0;i<r;i++)
+ {
+ //check if it is a printable or any of the line control chars
+ if((buf[i]>31 && buf[i] < 128) || buf[i]=='\r' || buf[i]=='\n' || buf[i]=='\t')
+ {
+ //append to the buffer
+ buffer[buffer_ptr] = buf[i];
+ buffer_ptr++;
+ }
+ else if(buf[i] == '\b') //backspace
+ {
+ //erases the character from the command buffer
+ if(buffer_ptr > 0)
+ {
+ buffer_ptr--;
+ }
+ //resets m variable state (will not cause error on the next block of code
+
+ }
+ else if((int)buf[i] == 255) //IAC - Interpret As Command
+ {
+ if((int)buf[i+1] >= 251)
+ {
+ option_negotiator(conn,buf[i+1],buf[i+2]);
+ i+=2;
+ }
+ else
+ i+=1;
+ }
+ }
+
+ //detect a carriage return and line feed sequence. Trigger command processor
+ if(buffer_ptr >= 2)
+ {
+ if(buffer[buffer_ptr-1] == '\n' && buffer[buffer_ptr-2] == '\r')
+ {
+ char **command;
+ int command_count;
+
+ buffer[buffer_ptr-2] = '\0';
+ command_count = split((char*)buffer," ",&command);
+
+ printf("Command found: %s\n", command[0]);
+
+ //must find a function in the table and then execute it, passing the command array as an argument
+ for(int i=0;cmds[i].pfn != 0;i++)
+ {
+ if(!strcasecmp(command[0],cmds[i].command_name))
+ {
+ if((int)cmds[i].pfn == -1)//exit cmd
+ {
+ //delete buffer;
+ return;
+ }
+ else
+ {
+ cmds[i].pfn(conn,command,command_count);
+ break;
+ }
+ }
+ }
+
+ //write the prompt
+ conn->send(prompt_msg,strlen(prompt_msg));
+ buffer_ptr=0;
+ }
+ }
+ }
+ //delete buffer;
+}
+
+void TelnetServer::option_negotiator(TCPSocketConnection *conn,unsigned char opt_cmd,unsigned char opt_param)
+{
+ char opt[3]={0,0,0};
+
+ if(opt_param == 1 && (opt_cmd == OPT_DO || opt_cmd == OPT_DONT)) //response for our will echo
+ {
+ printf("HERE");
+ return;
+ }
+ if(opt_cmd == OPT_DO) //every other option that it will ask to us to do, we won't
+ {
+ opt[0] = 255;
+ opt[1] = OPT_WONT;
+ opt[2] = opt_param;
+ conn->send(opt,3);
+ }
+ else if(opt_cmd == OPT_WILL && opt_param==3) //OK to supperss go ahead
+ {
+ opt[0] = 255;
+ opt[1] = OPT_DO;
+ opt[2] = opt_param;
+ conn->send(opt,3);
+ }
+ else if(opt_cmd == OPT_WILL) //every other option that it will ask do, we don't
+ {
+ opt[0] = 255;
+ opt[1] = OPT_DONT;
+ opt[2] = opt_param;
+ conn->send(opt,3);
+
+ }
+
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Codes/TftpServer.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,239 @@
+#include "TftpServer.h"
+
+#include <stdio.h>
+
+/*
+ *
+ * TFTP Formats
+
+
+Type Op # Format without header
+ 2 bytes string 1 byte string 1 byte
+ -----------------------------------------------
+RRQ/ | 01/02 | Filename | 0 | Mode | 0 |
+WRQ -----------------------------------------------
+ 2 bytes 2 bytes n bytes
+ ---------------------------------
+DATA | 03 | Block # | Data |
+ ---------------------------------
+ 2 bytes 2 bytes
+ -------------------
+ACK | 04 | Block # |
+ --------------------
+ 2 bytes 2 bytes string 1 byte
+ ----------------------------------------
+ERROR | 05 | ErrorCode | ErrMsg | 0 |
+ ----------------------------------------
+
+
+ Listen to UDP port 69
+
+ On receive RRQ: Opens the file with semihosting
+ Send the file
+
+ On receive WRQ: Open the file with semihosting
+ Send Ack
+ Receive Data Packet and write into the file
+ Send Ack
+ *
+ */
+
+ //LocalFileSystem local("local");
+
+/*
+static const char* file_not_found_msg = "\x00\x05\x00\x01\File not found.\x00"; //20
+static const char* file_too_big_msg = "\x00\x05\x00\x03\File is too big (>512kB).\x00"; //30
+static const char* file_already_exists_msg = "\x00\x05\x00\x06\File already exists.\x00"; //25
+static const char* file_unknown_error_msg = "\x00\x05\x00\x00Unable to open the file for write.\x00"; //40
+*/
+
+char* file_not_found_msg = "\x00\x05\x00\x01\File not found.\x00"; //20
+char* file_too_big_msg = "\x00\x05\x00\x03\File is too big (>512kB).\x00"; //30
+char* file_already_exists_msg = "\x00\x05\x00\x06\File already exists.\x00"; //25
+char* file_unknown_error_msg = "\x00\x05\x00\x00Unable to open the file for write.\x00"; //40
+
+
+
+void TftpServer::TftpServerThread(void const *arg)
+{
+/*
+ printf("TFTP Thread starting...\n");
+
+ UDPSocket server;
+
+ server.bind(69,NULL);
+
+ while(1)
+ {
+ char *buffer = NULL;
+ int length = 0;
+ Endpoint remote;
+ if(server.receiveFrom(remote,&buffer,&length) == ERR_OK)
+ {
+ printf("Received %d bytes from %s:%d\n",length,remote.get_address(),remote.get_port());
+ if(length > 2)
+ {
+ unsigned short int opcode = buffer[0]*0x100 + buffer[1];
+ printf("Got opcode [%X]\n",opcode);
+ if(opcode == 1)
+ {
+ TftpDoRead(remote,buffer,length);
+ }
+ else if(opcode == 2)
+ {
+ TftpDoWrite(remote,buffer,length);
+ }
+ delete buffer;
+ }
+ }
+ }
+*/
+}
+
+void TftpServer::TftpDoRead(Endpoint remote,char *buffer,int length)
+{
+/*
+ char *filename = buffer+2;
+
+ UDPSocket conn;
+
+ if(conn.connect(remote.get_address(),remote.get_port()) != ERR_OK)
+ return;
+
+ char fullpath[256];
+ strcpy(fullpath,"/local/");
+ strcat(fullpath,filename);
+ printf("File = %s\n",fullpath);
+ FILE *f = fopen(fullpath,"rb");
+
+ char *ans=NULL;
+ int len=0;
+
+ if(f == NULL)
+ {
+ conn.send((char*)file_not_found_msg,20);
+ conn.receive(&ans,&len);
+ delete ans;
+ return;
+ }
+
+ int idx = 1;
+
+ int readbytes;
+ unsigned char *hdrptr = new unsigned char[516];
+ unsigned char *dataptr = hdrptr+4;
+
+ do
+ {
+ //opcode
+ hdrptr[0] = 0;
+ hdrptr[1] = 3;
+ //block #
+ hdrptr[2] = idx/0x100;
+ hdrptr[3] = idx%0x100;
+
+ readbytes = fread(dataptr,1,512,f);
+ conn.send((char*)hdrptr,readbytes+4);
+ conn.receive(&ans,&len);
+ delete ans;
+ idx++;
+ }
+ while(readbytes == 512);
+
+ fclose(f);
+ delete hdrptr;
+*/
+}
+
+void TftpServer::TftpDoWrite(Endpoint remote,char *buffer,int length)
+{
+/*
+ char *filename = buffer+2;
+
+ UDPSocket conn;
+ err_t e;
+ if((e=conn.connect(remote.get_address(),remote.get_port())) != ERR_OK)
+ {
+ printf("Connect error %d\n",e);
+ return;
+ }
+
+ char fullpath[256];
+ strcpy(fullpath,"/local/");
+ strcat(fullpath,filename);
+ printf("File = %s\n",fullpath);
+
+ char *ans=NULL;
+ int len=0;
+
+ FILE *f = fopen(fullpath,"rb");
+ if(f != NULL)
+ {
+ conn.send((char*)file_already_exists_msg,25);
+ //conn.receive(&ans,&len);
+ fclose(f);
+ delete ans;
+ return;
+ }
+
+ f = fopen(fullpath,"wb");
+ if(f == NULL)
+ {
+ conn.send((char*)file_unknown_error_msg,40);
+ //conn.receive(&ans,&len);
+ delete ans;
+ return;
+ }
+
+ //int buflen;
+ unsigned char ack[4];
+ ack[0] = 0;
+ ack[1] = 4;
+ ack[2] = 0;
+ ack[3] = 0;
+
+ conn.send((char*)ack,4);
+ int error_tries = 5;
+ char *buf = NULL;
+
+ do
+ {
+
+ if(conn.receive(&buf,&len) != ERR_OK)
+ {
+ printf("Error\n");
+ error_tries--;
+ if(error_tries == 0)
+ {
+ return;
+ }
+ conn.send((char*)ack,4);
+ continue;
+ }
+
+ error_tries = 5;
+ int idx = buf[2]*0x100 + buf[3];
+
+ printf("Len = %d, Idx = %d\n",len,idx);
+
+ fwrite(buf+4,1,len-4,f);
+
+ delete buf;
+
+ if(idx >= 1024)
+ {
+ conn.send((char*)file_too_big_msg,30);
+ //conn.receive(&ans,&len);
+ delete ans;
+ return;
+ }
+
+ ack[2] = idx/0x100;
+ ack[3] = idx%0x100;
+ conn.send((char*)ack,4);
+ }
+ while(len == 516);
+
+ fclose(f);
+ */
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/adc.c Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,81 @@
+/*
+ * adc.c
+ *
+ * Created on: 02/07/2011
+ * Author: francisco
+ */
+
+#include <LPC17xx.h>
+#include "adc.h"
+
+void init_adc(int adc_clk)
+{
+ // Turn on power to ADC block
+ LPC_SC->PCONP |= PCADC;
+
+ // Turn on ADC peripheral clock
+ LPC_SC->PCLKSEL0 &= ~(3 << PCLK_ADC);
+ LPC_SC->PCLKSEL0 |= (ADC_CCLK << PCLK_ADC); //CLK/8
+
+ unsigned int clkdiv = (SystemCoreClock/1)/65;
+ clkdiv = clkdiv/adc_clk;
+
+ LPC_ADC->ADCR &= ~(ADC_OPERATIONAL|ADC_CLKDIV(255));
+ LPC_ADC->ADCR |= (ADC_OPERATIONAL|ADC_CLKDIV(clkdiv));
+
+ //NVIC_EnableIRQ(ADC_IRQn);
+}
+
+void setup_start(int mode,int edge)
+{
+ LPC_ADC->ADCR |= mode;
+}
+
+void select_channels(int adc_ch)
+{
+ LPC_ADC->ADCR &= ~(ADC_CH_0|ADC_CH_1|ADC_CH_2|ADC_CH_3|ADC_CH_4|ADC_CH_5|ADC_CH_6|ADC_CH_7);
+ LPC_ADC->ADCR |= adc_ch;
+
+ LPC_ADC->ADINTEN |= (1U<<8);//adc_ch;
+
+ if(adc_ch&ADC_CH_0)
+ {
+ LPC_PINCON->PINSEL1 |= 1U<<14;
+ LPC_PINCON->PINMODE1 |= 2U<<14;
+ }
+ if(adc_ch&ADC_CH_1)
+ {
+ LPC_PINCON->PINSEL1 |= 1U<<16;
+ LPC_PINCON->PINMODE1 |= 2U<<16;
+ }
+ if(adc_ch&ADC_CH_2)
+ {
+ LPC_PINCON->PINSEL1 |= 1U<<18;
+ LPC_PINCON->PINMODE1 |= 2U<<18;
+ }
+ if(adc_ch&ADC_CH_3)
+ {
+ LPC_PINCON->PINSEL1 |= 1U<<20;
+ LPC_PINCON->PINMODE1 |= 2U<<20;
+ }
+ if(adc_ch&ADC_CH_4)
+ {
+ LPC_PINCON->PINSEL3 |= 3U<<28;
+ LPC_PINCON->PINMODE3 |= 2U<<28;
+ }
+ if(adc_ch&ADC_CH_5)
+ {
+ LPC_PINCON->PINSEL3 |= 3U<<30;
+ LPC_PINCON->PINMODE3 |= 2U<<30;
+ }
+ if(adc_ch&ADC_CH_6)
+ {
+ LPC_PINCON->PINSEL0 |= 2U<<6;
+ LPC_PINCON->PINMODE0 |= 2U<<6;
+ }
+ if(adc_ch&ADC_CH_7)
+ {
+ LPC_PINCON->PINSEL0 |= 2U<<4;
+ LPC_PINCON->PINMODE0 |= 2U<<4;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/adc.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,76 @@
+/*
+ * adc.h
+ *
+ * Created on: 02/07/2011
+ * Author: francisco
+ */
+
+#ifndef ADC_H_
+#define ADC_H_
+
+
+#define PCADC (1U<<12)
+
+#define ADC_CCLK_4 0U
+#define ADC_CCLK 1U
+#define ADC_CCLK_2 2U
+#define ADC_CCLK_8 3U
+
+#define PCLK_ADC 24U
+
+#define ADC_CH_0 (1U<<0)
+#define ADC_CH_1 (1U<<1)
+#define ADC_CH_2 (1U<<2)
+#define ADC_CH_3 (1U<<3)
+#define ADC_CH_4 (1U<<4)
+#define ADC_CH_5 (1U<<5)
+#define ADC_CH_6 (1U<<6)
+#define ADC_CH_7 (1U<<7)
+#define ADC_CLKDIV(val) ((val)<<8)
+#define ADC_MODE_BURST (1U<<16)
+#define ADC_OPERATIONAL (1U<< 21)
+#define ADC_NO_START ~(7U<<24)
+#define ADC_START_NOW (1U<<24)
+#define ADC_START_ON_PIO2_10 (2U<<24)
+#define ADC_START_ON_PIO1_27 (3U<<24)
+#define ADC_START_ON_MAT0_1 (4U<<24)
+#define ADC_START_ON_MAT0_3 (5U<<24)
+#define ADC_START_ON_MAT1_0 (6U<<24)
+#define ADC_START_ON_MAT1_1 (7U<<24)
+#define ADC_EDGE_FALLING (1U<<27)
+#define ADC_EDGE_RAISING ~(1U<<27)
+
+#define ADC_GLOBAL_INT (1U<<8)
+#define ADC_INT_CH_0 (1U<<0)
+#define ADC_INT_CH_1 (1U<<1)
+#define ADC_INT_CH_2 (1U<<2)
+#define ADC_INT_CH_3 (1U<<3)
+#define ADC_INT_CH_4 (1U<<4)
+#define ADC_INT_CH_5 (1U<<5)
+#define ADC_INT_CH_6 (1U<<6)
+#define ADC_INT_CH_7 (1U<<7)
+
+#define ADC_LAST_CONVERSION() ((LPC_ADC->ADGDR&(0xFFFU<<4))>>4)
+#define ADC_LAST_CONVERSION_CHANNEL() ((LPC_ADC->ADGDR&(7U<<24))>>24)
+#define ADC_LAST_CONVERSION_DONE() (LPC_ADC->ADGDR&(1U<<31))
+#define ADC_LAST_CONVERSION_OVERUN() (LPC_ADC->ADGDR&(1U<<30))
+#define ADC_CONVERSION_CH(ch) ((LPC_ADC->ADDR[ch]&(0xFFFU<<4))>>4)
+#define ADC_CONVERSION_DONE_CH(ch) (LPC_ADC->ADDR[ch]&(1U<<31))
+#define ADC_CONVERSION_OVERUN_CH(ch) (LPC_ADC->ADDR[ch]&(1U<<30))
+
+#define ADC_CONVERT(val) ((val&(0xFFFU<<4))>>4)
+#define ADC_CHANNEL(val) ((val&(7U<<24))>>24)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void init_adc(int adc_clk);
+extern void setup_start(int mode,int edge);
+extern void select_channels(int adc_ch);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ADC_H_ */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/dma.c Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,63 @@
+/*
+ * dma.c
+ *
+ * Created on: 03/07/2011
+ * Author: francisco
+ */
+#include <LPC17xx.h>
+#include "dma.h"
+
+#define LPC_GPDMACH ((LPC_GPDMACH_TypeDef **) LPC_GPDMACH0_BASE )
+
+void init_dma()
+{
+ LPC_SC->PCONP |= 1<<29; //Power GPDMA module
+
+ LPC_GPDMA->DMACConfig = 1; //Enable GPDMA
+
+ //Clear any previous interrupts
+ LPC_GPDMA->DMACIntTCClear = 0xFF;
+ LPC_GPDMA->DMACIntErrClr = 0xFF;
+
+ NVIC_SetPriority(DMA_IRQn,(1<<__NVIC_PRIO_BITS) - 1);
+ NVIC_EnableIRQ(DMA_IRQn);
+}
+
+void setup_channel(dmaLinkedListNode* pList,int ch,int src,int dst)
+{
+ //Initialize the channel with previously configured LL;
+ LPC_GPDMACH0->DMACCSrcAddr = pList->sourceAddr;
+ LPC_GPDMACH0->DMACCDestAddr = pList->destAddr;
+ LPC_GPDMACH0->DMACCControl = pList->dmaControl;
+ LPC_GPDMACH0->DMACCLLI = (unsigned long int) pList & 0xFFFFFFFC; //Lower bits must be 0
+
+ int transfer_type;
+ if(src == DMA_MEMORY && dst != DMA_MEMORY)
+ {
+ transfer_type = DMA_MEMORY_TO_PERIPHERAL;
+ src = 0;
+ }
+ else if(src != DMA_MEMORY && dst == DMA_MEMORY)
+ {
+ transfer_type = DMA_PERIPHERAL_TO_MEMORY;
+ dst = 0;
+ }
+ else if(src == DMA_MEMORY && dst == DMA_MEMORY)
+ {
+ transfer_type = DMA_MEMORY_TO_MEMORY;
+ src=dst = 0;
+ }
+ else if(src != DMA_MEMORY && dst != DMA_MEMORY)
+ transfer_type = DMA_PERIPHERAL_TO_PERIPHERAL;
+
+ //Set up all relevant bits
+ LPC_GPDMACH0->DMACCConfig = (src<<1) | (dst<<5) | (transfer_type<<11) | (1<<15);
+
+ //Finally, enable the channel -
+ LPC_GPDMACH0->DMACCConfig |= 1<<0;
+}
+
+void stop_channel()
+{
+ LPC_GPDMACH0->DMACCConfig &= ~(1<<0);
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/dma.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,70 @@
+/*
+ * dma.h
+ *
+ * Created on: 03/07/2011
+ * Author: francisco
+ */
+ #ifndef DMA_H
+ #define DMA_H
+
+#define DMA_MEMORY -1
+
+#define DMA_PERIPHERAL_SSP0_TX 0U
+#define DMA_PERIPHERAL_SSP0_RX 1U
+#define DMA_PERIPHERAL_SSP1_TX 2U
+#define DMA_PERIPHERAL_SSP1_RX 3U
+#define DMA_PERIPHERAL_ADC 4U
+#define DMA_PERIPHERAL_I2S0 5U
+#define DMA_PERIPHERAL_I2S1 6U
+#define DMA_PERIPHERAL_DAC 7U
+#define DMA_PERIPHERAL_UART0_TX 8U
+#define DMA_PERIPHERAL_UART0_RX 9U
+#define DMA_PERIPHERAL_UART1_TX 10U
+#define DMA_PERIPHERAL_UART1_RX 11U
+#define DMA_PERIPHERAL_UART2_TX 12U
+#define DMA_PERIPHERAL_UART2_RX 13U
+#define DMA_PERIPHERAL_UART3_TX 14U
+#define DMA_PERIPHERAL_UART3_RX 15U
+
+#define DMA_MEMORY_TO_MEMORY 0U
+#define DMA_MEMORY_TO_PERIPHERAL 1U
+#define DMA_PERIPHERAL_TO_MEMORY 2U
+#define DMA_PERIPHERAL_TO_PERIPHERAL 3U
+
+#define DMA_DEST_SIZE(n) (n<<15)
+#define DMA_SRC_SIZE(n) (n<<12)
+
+#define DMA_SRC_WIDTH_BYTE (0U<<18)
+#define DMA_SRC_WIDTH_HALFWORD (1U<<18)
+#define DMA_SRC_WIDTH_WORD (2U<<18)
+
+#define DMA_DST_WIDTH_BYTE (0U<<21)
+#define DMA_DST_WIDTH_HALFWORD (1U<<21)
+#define DMA_DST_WIDTH_WORD (2U<<21)
+
+#define DMA_SRC_INCREMENT (1U<<26)
+#define DMA_DST_INCREMENT (1U<<27)
+
+#define DMA_TC_INT (1U<<31)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct
+{
+ unsigned long int sourceAddr;
+ unsigned long int destAddr;
+ unsigned long int nextNode;
+ unsigned long int dmaControl;
+} dmaLinkedListNode;
+
+extern void init_dma(void);
+extern void setup_channel(dmaLinkedListNode* pList,int ch,int src,int dst);
+extern void stop_channel(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //#define DMA_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/EthernetInterface.lib Fri Dec 13 11:42:59 2013 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/mbed_official/code/EthernetInterface/#da1aeab518f2
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Functions/Split.c Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,47 @@
+/*
+ * Split.c
+ *
+ * Created on: 12/04/2012
+ * Author: francisco
+ */
+
+#include "Split.h"
+
+int split(char* str,char* delim,char*** ret )
+{
+ char *p = NULL;
+ char *e = NULL;
+ char **array = NULL;
+ int qty = 0;
+ int len = strlen(str);
+
+ p = str;
+
+ e = strstr(p,delim);
+
+ while( e != NULL)
+ {
+ qty++;
+ if(qty==1)
+ array = (char**)malloc(sizeof(char*)*qty);
+ else
+ array = (char**)realloc(array,sizeof(char*)*qty);
+
+ array[qty-1] = p;
+ *e = '\0';
+ p = e + strlen(delim);
+ e = strstr(p,delim);
+ }
+ if(p-str < len)
+ {
+ qty++;
+ if(qty==1)
+ array = (char**)malloc(sizeof(char*)*qty);
+ else
+ array = (char**)realloc(array,sizeof(char*)*qty);
+ array[qty-1] = p;
+ }
+
+ *ret = array;
+ return qty;
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Functions/Split.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,25 @@
+/*
+ * Split.h
+ *
+ * Created on: 12/04/2012
+ * Author: francisco
+ */
+
+#ifndef SPLIT_H_
+#define SPLIT_H_
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int split(char* str,char* delim,char*** ret );
+
+#ifdef __cplusplus
+};
+#endif
+
+#endif /* SPLIT_H_ */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/Capture.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,50 @@
+/*
+ * capture.h
+ *
+ * Created on:
+ * Author:
+ */
+
+#ifndef CAPTURE_H
+#define CAPTURE_H
+
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#include "mbed.h"
+#include "rtos.h"
+#include "dma.h"
+#include "adc.h"
+
+#include "Settings.h"
+
+// MTR: Estes defines nao deveriam estar no arquivo de configuraçeos?
+//#define SAMPLE_RATE 256U
+
+class Capture
+{
+protected:
+
+ static Semaphore m_CaptureSemaphore; //used to alert the capture thread about a ready capture
+ static int m_BufferIndex;
+
+ static dmaLinkedListNode m_Nodes[2]; //this list holds the buffer configuration for the DMA peripheral
+public:
+ static unsigned short int m_AdcBuffers[2][NUMBER_OF_SAMPLES][NUMBER_OF_CHANNELS];
+
+public:
+
+ static unsigned short int GetValue(int nsamples, int nchannel);
+ static void CopyBuffer(int channel, unsigned short int *dest);
+
+ static void ISRHandler();
+
+ static void Initialize();
+ static void Start();
+ static void Stop();
+ static void Wait();
+
+};
+
+#endif
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/CommTCP.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,29 @@
+/*
+ * CommTCP.h
+ *
+ * Created on: 07/07/2013
+ * Author: Rebonatto
+ */
+#ifndef COMM_TCP_H
+#define COMM_TCP_H
+
+#include <mbed.h>
+#include <rtos.h>
+
+#include "EthernetInterface.h"
+
+#include "Settings.h"
+#include "EventDetector.h"
+
+extern void CommTCP_Thread(void const *arg);
+
+class CommTCP
+{
+public:
+
+ static void CommTCP_Thread(void const *arg);
+ static void RequestAcom();
+ static void SendAcom(int tipo,int tomada);
+};
+
+#endif //#ifndef COMM_TCP_H
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/EventDetector.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,84 @@
+/*
+ * EventDetector.h
+ *
+ * Created on:
+ * Author:
+ */
+
+#ifndef EVENTDETECTOR_H
+#define EVENTDETECTOR_H
+
+#include <stdlib.h>
+
+#include "rtos.h"
+
+#include "Settings.h"
+#include "Capture.h"
+#include "SignalProcessor.h"
+
+class CaptureEvent
+{
+ char m_RFID[9];
+ int m_Type;
+ int m_OutletNumber;
+ float m_MeanValue;
+ float m_RMSValue;
+ float m_Gain;
+ int m_Offset;
+ float m_Sin[NUMBER_OF_HARMONICS];
+ float m_Cos[NUMBER_OF_HARMONICS];
+
+public:
+
+ CaptureEvent();
+
+ void Setup(char* rfid,int type,int outlet,float mv,float rms,float gain, int offset,float* sin, float* cos);
+
+ char* get_RFID() { return m_RFID; }
+ int get_Type() { return m_Type; }
+ int get_OutletNumber() { return m_OutletNumber; }
+ float get_MeanValue() { return m_MeanValue; }
+ float get_RMSValue() { return m_RMSValue; }
+ float get_Gain() { return m_Gain; }
+ int get_Offset() { return m_Offset; }
+ float get_SineValue(int idx) { return m_Sin[idx]; }
+ float get_CossineValue(int idx) { return m_Cos[idx]; }
+};
+
+typedef Mail<CaptureEvent,LENGTH_MAIL_BOX> CaptureMailbox;
+
+class EventDetector
+{
+protected:
+
+ static CaptureMailbox m_EventMailbox;
+ static const int m_EventLimit;
+
+ static EventDetector m_Detector[NUMBER_OF_CHANNELS];
+
+ bool m_OutletTriggered;
+ int m_EventCounter;
+ int m_Channel;
+
+ void OnTrigger(float rmsvalue);
+
+ void SendMessage(int ext,float rmsvalue);
+
+ int TimeDelay(int t);
+
+public:
+
+ EventDetector(int ch);
+
+ void ExternalTrigger();
+
+ void ProcessEvent(float rmsvalue, int t);
+
+ void ShowValues(CaptureEvent* e);
+
+ static CaptureMailbox& GetMailbox() { return m_EventMailbox; }
+ static EventDetector& get_Detector(int ch) { return m_Detector[ch]; }
+
+};
+
+#endif
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/Http_post.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,29 @@
+/*
+ * Http_post.h
+ *
+ * Created on:
+ * Author:
+ */
+#ifndef HTTP_POST_H
+#define HTTP_POST_H
+
+#include <mbed.h>
+#include <rtos.h>
+
+#include "EthernetInterface.h"
+
+#include "Settings.h"
+#include "EventDetector.h"
+
+extern void HttpPost_Thread(void const *arg);
+
+class HttpPost
+{
+public:
+
+ static void HttpPost_Thread(void const *arg);
+ static void DoPost(TCPSocketConnection sock, char *host, CaptureEvent* dados);
+ static void PreparePost(CaptureEvent* dados,char *strfinal);
+};
+
+#endif //#ifndef HTTP_POST_H
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/Settings.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,211 @@
+/*
+ * Settings.h
+ *
+ * Created on:
+ * Author:
+ */
+
+#ifndef SETTINGS_H
+#define SETTINGS_H
+
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "mbed.h"
+#include "EthernetInterface.h"
+
+#include "Split.h"
+
+#define FILENAME "/local/pmed.txt"
+#define FILENAMERESET "/local/foi.txt"
+#define NUMBER_OF_CHANNELS 6U
+#define NUMBER_OF_OUTLETS 3U
+#define NUMBER_OF_HARMONICS 12U
+#define NUMBER_OF_SAMPLES 256U
+#define LENGTH_MAIL_BOX 50U
+#define NEIGHBORS 3U
+
+class Settings
+{
+
+ //server URL
+ static char* m_serverurl;
+ //module number
+ static int m_module_number;
+ //ip address
+ static char* m_ipaddress;
+ //netmask
+ static char* m_netmask;
+ //gateway
+ static char* m_gateway;
+ //dhcp
+ static int m_dhcp;
+
+ //gain x6(float)
+ static float m_gain[NUMBER_OF_CHANNELS];
+ //offset x6(int)
+ static int m_offset[NUMBER_OF_CHANNELS];
+ //limit x6(float)
+ static float m_limit[NUMBER_OF_CHANNELS];
+ //outlet x6 (int)
+ static int m_outlet_number[NUMBER_OF_CHANNELS];
+ //purpose x6(char)
+ static char m_purpose[NUMBER_OF_CHANNELS];
+
+ //outlet x3(int)
+ static int m_outlet[NUMBER_OF_OUTLETS];
+
+ //MaxChannels
+ static int m_MaxChannels;
+ //MaxOutlets
+ static int m_MaxOutlets;
+ //Samples
+ static int m_Samples;
+
+ //FreqBase
+ static int m_FreqBase;
+
+ //MaxHarmonics
+ static int m_MaxHarmonics;
+
+ //EventLimit
+ static int m_EventLimit;
+
+ //MailBoxLength
+ static int m_MBoxLength;
+
+ //NumberNeighbors
+ static int m_NumNeighbors;
+
+ //Neighbors x3(char [16])
+ static char *m_Neighbor[NEIGHBORS];
+
+ //PortTCP
+ static int m_PortTCP;
+
+ //Socket to receive requests
+ static TCPSocketServer m_ServerSocket;
+
+ //Socket to send requests
+ static TCPSocketConnection m_Socket[NEIGHBORS];
+
+ //Maximum number of try connect and send
+ static int m_MaxTries;
+
+ //Delay time (ms) between 2 tries
+ static int m_DelayTry;
+
+ //Delay time (ms) after Send (post)
+ static int m_DelaySend;
+
+
+public:
+
+ Settings();
+
+ static char* get_ServerUrl() { return m_serverurl; }
+ static void set_ServerUrl(char *value)
+ {
+ if(m_serverurl!=NULL) delete m_serverurl;
+ int sz = strlen(value)+1;
+ m_serverurl = new char[sz];
+ strcpy(m_serverurl,value);
+ }
+ static char* get_IpAddress() { return m_ipaddress; }
+ static void set_IpAddress(char *value)
+ {
+ if(m_ipaddress!=NULL) delete m_ipaddress;
+ int sz = strlen(value)+1;
+ m_ipaddress = new char[sz];
+ strcpy(m_ipaddress,value);
+ }
+ static char* get_Netmask() { return m_netmask; }
+ static void set_Netmask(char *value)
+ {
+ if(m_netmask!=NULL) delete m_netmask;
+ int sz = strlen(value)+1;
+ m_netmask = new char[sz];
+ strcpy(m_netmask,value);
+ }
+
+ static char* get_Gateway() { return m_gateway; }
+ static void set_Gateway(char *value)
+ {
+ if(m_gateway!=NULL) delete m_gateway;
+ int sz = strlen(value)+1;
+ m_gateway = new char[sz];
+ strcpy(m_gateway,value);
+ }
+ static int get_Dhcp() { return m_dhcp; }
+ static void set_Dhcp(int value) { m_dhcp = value; }
+ static int get_ModuleNumber() { return m_module_number; }
+ static void set_ModuleNumber(int value) { m_module_number = value; }
+
+ static float get_Gain(int i) { return m_gain[i]; }
+ static void set_Gain(int i, float value) { m_gain[i] = value; }
+ static int get_Offset(int i) { return m_offset[i]; }
+ static void set_Offset(int i, int value) { m_offset[i] = value; }
+ static float get_Limit(int i) { return m_limit[i]; }
+ static void set_Limit(int i, float value) { m_limit[i] = value; }
+ static int get_OutletNumber(int i) { return m_outlet_number[i]; }
+ static void set_OutletNumber(int i, int value) { m_outlet_number[i] = value; }
+ static char get_Purpose(int i) { return m_purpose[i]; }
+ static void set_Purpose(int i, char value) { m_purpose[i] = value; }
+
+ static int get_Outlet(int i) { return m_outlet[i]; }
+ static void set_Outlet(int i, int value) { m_outlet[i] = value; }
+
+ static int get_MaxChannels() { return m_MaxChannels; }
+ static void set_MaxChannels(int value) { m_MaxChannels = value; }
+ static int get_MaxOutlets() { return m_MaxOutlets; }
+ static void set_MaxOutlets(int value) { m_MaxOutlets = value; }
+ static int get_FreqBase() { return m_FreqBase; }
+ static void set_FreqBase(int value) { m_FreqBase = value; }
+ static int get_MaxHarmonics() { return m_MaxHarmonics; }
+ static void set_MaxHarmonics(int value) { m_MaxHarmonics = value; }
+ static int get_Samples() { return m_Samples; }
+ static void set_Samples(int value) { m_Samples = value; }
+ static int get_EventLimit() { return m_EventLimit; }
+ static void set_EventLimit(int value) { m_EventLimit = value; }
+ static int get_MBoxLength() { return m_MBoxLength; }
+ static void set_MBoxLength(int value) { m_MBoxLength = value; }
+
+ static int get_NumNeighbors() { return m_NumNeighbors; }
+ static void set_NumNeighbors(int value) { m_NumNeighbors = value; }
+
+ static char* get_Neighbor(int i) { return m_Neighbor[i]; }
+ static void set_Neighbor(int i, char *value)
+ {
+ if(m_Neighbor[i]!=NULL) delete m_Neighbor[i];
+ int sz = strlen(value)+1;
+ m_Neighbor[i] = new char[sz];
+ strcpy(m_Neighbor[i],value);
+ }
+
+ static int get_PortTCP() { return m_PortTCP; }
+ static void set_PortTCP(int value) { m_PortTCP = value; }
+
+ static TCPSocketServer& get_ServerSocket() { return m_ServerSocket; }
+ static void set_ServerSocket(TCPSocketServer value) { m_ServerSocket = value; }
+
+ static TCPSocketConnection& get_Socket(int i) { return m_Socket[i]; }
+ static void set_Socket(int i, TCPSocketConnection value) { m_Socket[i] = value; }
+
+ static int get_MaxTries() { return m_MaxTries; }
+ static void set_MaxTries(int value) { m_MaxTries = value; }
+
+ static int get_DelayTry() { return m_DelayTry; }
+ static void set_DelayTry(int value) { m_DelayTry = value; }
+
+ static int get_DelaySend() { return m_DelaySend; }
+ static void set_DelaySend(int value) { m_DelaySend = value; }
+
+ static void ReadFile(); //Read the config file and places the values in the internal variables
+ static void LoadDefaults();
+ static void WriteFile();
+ static void ShowValues();
+
+};
+
+#endif //#ifndef SETTINGS
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/SignalProcessor.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,29 @@
+/*
+ * SignalProcessor.h
+ *
+ * Created on:
+ * Author:
+ */
+
+#ifndef SIGNALPROCESSOR_H
+#define SIGNALPROCESSOR_H
+
+#include <math.h>
+
+#include "Capture.h"
+#include "Settings.h"
+
+class SignalProcessor
+{
+
+ static float* ComplexFFT(unsigned short int* data, int sign);
+
+public:
+
+ static void CalculateRMSBulk(float *result);
+ static float CalculateRMS(unsigned short int *buffer,int nChannel);
+ static void CalculateFFT(unsigned short int *buffer,float *sen,float *cos,float *vm,int sign);
+
+};
+
+#endif
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/TelnetServer.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,31 @@
+#include "mbed.h"
+#include "rtos.h"
+
+#include "EthernetInterface.h"
+
+typedef int(*cmd_function)(TCPSocketConnection *conn,char**,int);
+
+struct telnet_cmd_handler {
+ char* command_name;
+ cmd_function pfn;
+};
+
+
+class TelnetServer
+{
+ static const struct telnet_cmd_handler cmds[];
+
+public:
+ static void TelnetServer_Thread(void const* arg);
+ static void TelnetSession(TCPSocketConnection *conn);
+ static void option_negotiator(TCPSocketConnection *conn,unsigned char opt_cmd,unsigned char opt_param);
+ static int HelpCommand(TCPSocketConnection *conn,char** argv,int argc);
+ static int ListParamCommand(TCPSocketConnection *conn,char** argv,int argc);
+ static int GetParamCommand(TCPSocketConnection *conn,char** argv,int argc);
+ static int SetParamCommand(TCPSocketConnection *conn,char** argv,int argc);
+ static int ResetCommand(TCPSocketConnection *conn,char** argv,int argc);
+ static int RemoveCommand(TCPSocketConnection *conn,char** argv,int argc);
+ static int VersionCommand(TCPSocketConnection *conn,char** argv,int argc);
+ static int UpdateCommand(TCPSocketConnection *conn,char** argv,int argc);
+
+};
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Headers/TftpServer.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,19 @@
+#include "mbed.h"
+#include "rtos.h"
+
+#include "EthernetInterface.h"
+
+
+
+
+class TftpServer
+{
+
+public:
+
+ static void TftpServerThread(void const *arg);
+
+ static void TftpDoRead(Endpoint remote,char *buffer,int length);
+ static void TftpDoWrite(Endpoint remote,char *buffer,int length);
+
+};
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Rede/EthernetIf.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,188 @@
+#include "Rede/EthernetIf.h"
+
+#include "lwip/inet.h"
+#include "lwip/netif.h"
+#include "netif/etharp.h"
+#include "lwip/dhcp.h"
+#include "arch/lpc17_emac.h"
+#include "lpc_phy.h"
+#include "lwip/tcpip.h"
+
+#include "mbed.h"
+
+struct netif EthernetIf::lpcNetif;
+bool EthernetIf::use_dhcp;
+ip_addr_t EthernetIf::ip_n;
+ip_addr_t EthernetIf::netmask_n;
+ip_addr_t EthernetIf::gw_n;
+Semaphore EthernetIf::tcpip_initialized(0);
+Semaphore EthernetIf::link_up(0);
+Semaphore EthernetIf::netif_up(0);
+bool EthernetIf::link_is_up(false);
+
+uint32_t EthernetIf::os_timer_cb_led[5];
+osTimerDef_t EthernetIf::os_timer_def_led = { (led_refresh), (os_timer_cb_led) };
+
+void EthernetIf::tcpip_init_done(void *arg)
+{
+ //This function is called when the TCPIP stack finishes to initialize
+ tcpip_initialized.release();
+}
+
+void EthernetIf::link_status_callback(struct netif *netif)
+{
+ //Called when the interface link goes up or down
+ if(netif_is_link_up(netif))
+ {
+ printf("Link up!!!\n");
+ if(!link_is_up)
+ {
+ if(use_dhcp)
+ {
+ dhcp_start(&lpcNetif);
+ }
+ else
+ {
+ netif_set_addr(&lpcNetif,&ip_n,&netmask_n,&gw_n);
+ netif_set_up(&lpcNetif);
+ }
+ }
+ link_up.release();
+ link_is_up = true;
+ }
+ else
+ {
+ printf("Link down!!!\n");
+ netif_set_down(&lpcNetif);
+ link_is_up = false;
+ }
+}
+
+void EthernetIf::interface_status_callback(struct netif *netif)
+{
+ //called when the status of the interface is up or down
+ if(netif_is_up(netif))
+ {
+ netif_up.release();
+ printf("Interface Ethernet is up\n");
+ printf("IP Address: %s\n",get_IpAddress());
+ printf("Netmask: %s\n",get_Netmask());
+ printf("Gateway: %s\n\n",get_Gateway());
+ }
+}
+
+void EthernetIf::led_refresh(void const* arg)
+{
+ if(LPC_GPIO1->FIOPIN & (1<<25))
+ LPC_GPIO0->FIOSET |= (1<<4);
+ else
+ LPC_GPIO0->FIOCLR |= (1<<4);
+
+ if(LPC_GPIO1->FIOPIN & (1<<26))
+ LPC_GPIO0->FIOSET |= (1<<5);
+ else
+ LPC_GPIO0->FIOCLR |= (1<<5);
+}
+
+int EthernetIf::_init()
+{
+
+ LPC_PINCON->PINSEL3 &= ~(3<<18); //GPIO P1.25 - MBED LED LINK
+ LPC_PINCON->PINSEL3 &= ~(3<<20); //GPIO P1.26 - MBED LED SPEED
+ LPC_PINCON->PINSEL0 &= ~(3<<8); //GPIO P0.4 - ETHERNET GREEN LED
+ LPC_PINCON->PINSEL0 &= ~(3<<10); //GPIO P0.5 - ETHERNET YELLOW LED
+ LPC_GPIO1->FIODIR &= ~((1<<25)|(1<<26));
+ LPC_GPIO0->FIODIR |= ((1<<4)|(1<<5));
+
+ tcpip_init(tcpip_init_done, NULL);
+ tcpip_initialized.wait();
+
+ memset((void*) &lpcNetif, 0, sizeof(lpcNetif));
+ netif_add(&lpcNetif, &ip_n, &netmask_n, &gw_n, NULL, lpc_enetif_init, tcpip_input);
+ netif_set_default(&lpcNetif);
+
+ netif_set_link_callback (&lpcNetif, link_status_callback);
+ netif_set_status_callback(&lpcNetif, interface_status_callback);
+
+ return 0;
+}
+
+int EthernetIf::Initialize()
+{
+ use_dhcp = true;
+
+ return _init();
+}
+
+int EthernetIf::Initialize(char *ip,char *netmask,char *gw)
+{
+ use_dhcp = false;
+ inet_aton(ip,&ip_n);
+ inet_aton(netmask,&netmask_n);
+ inet_aton(gw,&gw_n);
+
+ return _init();
+}
+
+int EthernetIf::Connect(unsigned int timeout /*= 1500*/)
+{
+ NVIC_SetPriority(ENET_IRQn, ((0x01 << 3) | 0x01));
+ NVIC_EnableIRQ(ENET_IRQn);
+
+ netif_set_link_up(&lpcNetif);
+ int inited;
+ inited = netif_up.wait(timeout);
+
+ osTimerId led_timer = osTimerCreate(osTimer(led), osTimerPeriodic, NULL);
+ osTimerStart(led_timer, 100);
+
+ return (inited > 0) ? (0) : (-1);
+}
+
+int EthernetIf::Disconnect()
+{
+ if (use_dhcp)
+ {
+ dhcp_release(&lpcNetif);
+ dhcp_stop(&lpcNetif);
+ }
+ else
+ {
+ netif_set_down(&lpcNetif);
+ }
+
+ NVIC_DisableIRQ(ENET_IRQn);
+
+ return 0;
+}
+
+bool EthernetIf::is_LinkUp()
+{
+ if(netif_is_link_up(&lpcNetif))
+ return true;
+ else
+ return false;
+}
+
+bool EthernetIf::is_InterfaceUp()
+{
+ if(netif_is_up(&lpcNetif))
+ return true;
+ else
+ return false;
+}
+
+char* EthernetIf::get_IpAddress()
+{
+ return ipaddr_ntoa(&lpcNetif.ip_addr);
+}
+
+char* EthernetIf::get_Netmask()
+{
+ return ipaddr_ntoa(&lpcNetif.netmask);
+}
+
+char* EthernetIf::get_Gateway()
+{
+ return ipaddr_ntoa(&lpcNetif.gw);
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Rede/EthernetIf.h Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,56 @@
+#ifndef ETHERNETIF_H
+#define ETHERNETIF_H
+
+#if !defined(TARGET_LPC1768)
+#error The Ethernet Interface library is supported only on the mbed NXP LPC1768
+#endif
+
+#include "rtos.h"
+#include "lwip/netif.h"
+
+
+class EthernetIf
+{
+ static struct netif lpcNetif;
+ static bool use_dhcp;
+
+ static ip_addr_t ip_n,netmask_n,gw_n;
+
+ static Semaphore tcpip_initialized;
+ static void tcpip_init_done(void *arg);
+ static void link_status_callback(struct netif *netif);
+ static void interface_status_callback(struct netif *netif);
+
+ static Semaphore link_up;
+ static Semaphore netif_up;
+
+ static bool link_is_up;
+
+ static uint32_t os_timer_cb_led[5];
+ static osTimerDef_t os_timer_def_led;
+
+ static int _init();
+ static void led_refresh(void const* arg);
+public:
+ static int Initialize();
+ static int Initialize(char *ip,char *netmask,char *gw);
+
+ static int Connect(unsigned int timeout = 15000);
+ static int Disconnect();
+
+ static char* get_IpAddress();
+ static char* get_Netmask();
+ static char* get_Gateway();
+ static bool is_LinkUp();
+ static bool is_InterfaceUp();
+
+
+};
+
+#include "TCPSocketConnection.h"
+#include "TCPSocketServer.h"
+
+#include "Endpoint.h"
+#include "UDPSocket.h"
+
+#endif //#ifndef ETHERNETIF_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp Fri Dec 13 11:42:59 2013 +0000
@@ -0,0 +1,153 @@
+#include <stdio.h>
+
+#include "mbed.h"
+#include "rtos.h"
+#include "cmsis_os.h"
+#include "EthernetIf.h"
+
+#include "Settings.h"
+#include "Capture.h"
+#include "Http_post.h"
+#include "CommTCP.h"
+#include "SignalProcessor.h"
+#include "EventDetector.h"
+
+#include "TelnetServer.h"
+
+
+EthernetInterface eth;
+
+void thread1(void const *args)
+{
+ DigitalOut led1(LED1);
+ int n = 0;
+ //int tatual, tnovo;
+ float rms[NUMBER_OF_CHANNELS];
+
+ Capture::Initialize();
+ /*
+ Timer t;
+ t.start();
+ tatual = 0;
+ */
+ while(1)
+ {
+ Capture::Wait();
+
+ SignalProcessor::CalculateRMSBulk(rms);
+
+ //rms[0] = 2050;
+ //rms[1]=rms[2]=rms[3]=rms[4]=rms[5]=2000;
+
+ for(int i=0;i<6;i++){
+ //printf("Main %d\n", i);
+ EventDetector::get_Detector(i).ProcessEvent(rms[i], i);
+ //wait_ms(2);
+ }
+ //Thread::yield();
+
+
+ /*
+ for(int i =0; i < 6; i++)
+ printf("%5.2f\t", rms[i]);
+ printf("\n");
+
+ wait(5);
+ */
+ n++;
+ if(n==60)
+ {
+ printf("%f %f %f %f %f %f\n",rms[0],rms[1],rms[2],rms[3],rms[4],rms[5]);
+ led1 = !led1;
+ n=0;
+ //t.stop();
+
+ /*
+ for(int i =0; i < 6; i++)
+ printf("%5.2f\t", rms[i]);
+ printf("\n");
+ //
+ */
+ /*
+ tnovo = t.read_us();
+ printf("MAIN: The time XXX taken loop %d\n", tnovo - tatual);
+ tatual = tnovo;
+ t.reset();
+ */
+ //Thread::wait(1000); //1000
+ wait(1);
+ }
+ }
+}
+
+/*
+void InitializeEthernetLink()
+{
+ if(Settings::get_Dhcp())
+ eth.init(); //Use DHCP
+ else
+ eth.init(Settings::get_IpAddress(),Settings::get_Netmask(),Settings::get_Gateway());
+
+ eth.connect();
+ printf("IP Address is %s\n", eth.getIPAddress());
+}
+*/
+void InitializeEthernetLink()
+{
+ if(Settings::get_Dhcp())
+ EthernetIf::Initialize(); //Use DHCP
+ else
+ EthernetIf::Initialize(Settings::get_IpAddress(),Settings::get_Netmask(),Settings::get_Gateway());
+
+ EthernetIf::Connect();
+ printf("IP Address is %s\n", EthernetIf::get_IpAddress());
+}
+
+int main() {
+ FILE *f;
+ //Set Highest Priority
+ //osThreadSetPriority(osThreadGetId(),osPriorityHigh);
+
+ Settings::ReadFile();
+ //printf("Passou Settings, carregou arquivo\n");
+ //Settings::ShowValues();
+
+ InitializeEthernetLink();
+ //printf("Inicializou link Ethernet\n");
+
+ //Start HTTP POST service
+ Thread http_post(HttpPost::HttpPost_Thread);
+
+ //Start TCP daemon service
+ //Thread TcpService(CommTCP::CommTCP_Thread);
+
+
+ //Start Telnet Service
+ //Thread telnetserver(TelnetServer::TelnetServer_Thread);
+ //Start TFTP Service
+
+ /*
+ unsigned short vet[256] = {2105,2105,2113,2127,2127,2125,2112,2113,2130,2130,2123,2112,2112,2128,2128,2123,2112,2113,2136,2136,2374,2551,2671,2869,2887,3036,2964,2964,2964,3145,3145,3206,3209,3298,3298,3264,3261,3208,3239,3239,3197,3197,3113,3032,3065,3065,3000,2901,2943,2943,2900,2852,2844,2863,2863,2838,2764,2791,2724,2724,2668,2710,2636,2658,2658,2606,2527,2443,2434,2434,2258,2066,2061,2080,2080,2063,2055,2055,2070,2070,2064,2051,2054,2069,2069,2062,2054,2058,2066,2309,2062,2052,2054,2067,2067,2063,2051,2049,2068,2068,2060,2053,2050,2067,2066,2069,2051,2053,2070,2070,2064,2050,2053,2070,2070,2062,2052,2055,2068,2068,2065,2052,2057,2072,2072,2064,2054,2054,2072,2072,2064,2053,2052,2069,2069,2064,2052,2053,2064,2064,2062,2049,2051,2067,2067,2059,2051,2050,2068,2068,2058,2046,2050,2068,2068,2061,2052,2058,2068,2068,2059,2052,2053,2067,2067,1744,1526,1471,1289,1289,1137,1142,1055,1120,1120,997,967,894,941,941,928,887,1001,949,949,1028,1105,1079,1191,1191,1223,1211,1223,1267,1267,1325,1267,1356,1327,1327,1369,1439,1381,1498,1498,1503,1503,1527,1545,1545,1635,1650,1778,1792,1792,1971,2108,2109,2126,2126,2124,2117,2118,2131,2131,2126,2118,2118,2138,2138,2134,2124,2114,2135,2135,2129,2121,2120,2136,2136,2128,2122,2122,2143,2120,2130,2120,2121,2139,2139,2130,2119,2121,2136,2136,2129};
+ float sen[12],cos[12],vm;
+ SignalProcessor::CalculateFFT(vet,sen,cos,&vm,1);
+
+ printf("VM = %f\n",vm);
+ for(int i=0;i<12;i++)
+ {
+ printf("SEN%d = %f, COS%d = %f\n",i,sen[i],i,cos[i]);
+ }
+ */
+
+ //Jump to the capture routine(will run on this thread)
+ thread1(NULL);
+
+ while(1){//never reaches here
+ printf("Reset\n");
+ f = fopen(FILENAMERESET, "a");
+ if (f == NULL)
+ f = fopen(FILENAMERESET, "w");
+ fprintf(f, "Laco Errado\n");
+ fclose(f);
+ Thread::yield();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos.lib Fri Dec 13 11:42:59 2013 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/mbed_official/code/mbed-rtos/#db1fc233faa9
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed.bld Fri Dec 13 11:42:59 2013 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/mbed_official/code/mbed/builds/9c8f0e3462fb \ No newline at end of file
