![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Versão estável sem DMA e FFT. 128 amostras.
Dependencies: EthernetInterface NTPClient mbed-rtos mbed
Revision 0:fac116e94d44, committed 2016-01-05
- Comitter:
- rebonatto
- Date:
- Tue Jan 05 11:47:35 2016 +0000
- Commit message:
- Vers?o est?vel sem DMA e FFT. 128 amostras.
Changed in this revision
diff -r 000000000000 -r fac116e94d44 Codes/Capture.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/Capture.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,102 @@ +/* + * 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; + +//__attribute((section("AHBSRAM1"),aligned)) dmaLinkedListNode Capture::m_Nodes[2];// __attribute__((section("AHBSRAM0"))); //this list holds the buffer configuration for the DMA peripheral +__attribute((section("AHBSRAM1"),aligned)) short int Capture::m_AdcBuffers[NUMBER_OF_CHANNELS][NUMBER_OF_SAMPLES];// __attribute__((section("AHBSRAM0"))); +Serial rfid_serial(p28,p27); + +AnalogIn AdcChannel0(CHANNEL0); +AnalogIn AdcChannel1(CHANNEL1); +AnalogIn AdcChannel2(CHANNEL2); +AnalogIn AdcChannel3(CHANNEL3); +AnalogIn AdcChannel4(CHANNEL4); +AnalogIn AdcChannel5(CHANNEL5); + +//ADC_CONVERT(m_AdcBuffers[m_BufferIndex][nsamples][nchannel]); + +short int Capture::GetValue(int nsamples, int nchannel) +{ + return m_AdcBuffers[nchannel][nsamples]; +} + +void Capture::PutValue(int nsamples, int nchannel, short int value) +{ + m_AdcBuffers[nchannel][nsamples] = value; +} + +void Capture::CopyBuffer(int channel, short int *dest) +{ + memcpy(dest, &m_AdcBuffers[channel][0], sizeof(short int) * NUMBER_OF_SAMPLES); + /* + for(int i=0;i<NUMBER_OF_SAMPLES;i++) + { + dest[i] = GetValue(i,channel); + } + */ +} + + +void Capture::AcquireValues(){ + int i; + + for(i=0; i < NUMBER_OF_SAMPLES; i++){ + m_AdcBuffers[0][i] = ADC_CONVERT(AdcChannel0.read_u16()); + //wait_us(10); + m_AdcBuffers[1][i] = ADC_CONVERT(AdcChannel1.read_u16()); + //wait_us(10); + m_AdcBuffers[2][i] = ADC_CONVERT(AdcChannel2.read_u16()); + //wait_us(10); + m_AdcBuffers[3][i] = ADC_CONVERT(AdcChannel3.read_u16()); + //wait_us(10); + m_AdcBuffers[4][i] = ADC_CONVERT(AdcChannel4.read_u16()); + //wait_us(10); + m_AdcBuffers[5][i] = ADC_CONVERT(AdcChannel5.read_u16()); + wait_us(13); + } +} + +//void Capture::Initialize(){ //AnalogIn adcChannel0; } + + +void Capture::ReadRFID(int channel,char *rfid) +{ + + char cmd[4]; + cmd[0] = 'S'; + cmd[1] = '0'+channel; + cmd[2] = '\n'; + cmd[3] = '\0'; + + //send + rfid_serial.puts(cmd); + + //receive + char ch=0; + char ans[10]; + int cnt=0; + int tmout=1000; + while(ch != '\n' && tmout-- && cnt<9) + { + if(rfid_serial.readable()) + { + ch = rfid_serial.getc(); + if(!((ch>='0' && ch<='9') || (ch >= 'A' && ch <= 'F')))ch='0'; + ans[cnt++] = ch; + } + else + wait_ms(1); + + } + ans[cnt-1] = '\0'; + for(int i=0;i<9;i++) + rfid[i] = ans[i]; + +} \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Codes/CommTCP.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/CommTCP.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,116 @@ +/* + * CommTCP.cpp + * + * Created on: 07/07/2013 + * Author: Rebonatto + */ +#include "CommTCP.h" +#include "EventDetector.h" + +#define PORTTCP 7890U +#define NEIGHBORS 2U + +void CommTCP::CommTCP_Thread(void const *arg) +{ + char buffer[5]; + int ret=0,i, r; + int cont = 0; + TCPSocketServer ServerSocket; + + ServerSocket.bind(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 < 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 < 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()); + */ + /* desabilitado pela falta do vetor de vizinhos + for(i=0; i< NEIGHBORS; 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<NUMBER_OF_CHANNELS;i++) + { + EventDetector::get_Detector(i).ExternalTrigger(); + } +} +
diff -r 000000000000 -r fac116e94d44 Codes/EventDetector.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/EventDetector.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,290 @@ +/* + * EventDetector.cpp + * + * Created on: + * Author: + */ + + #include "EthernetInterface.h" + #include "Settings.h" + #include "Http_post.h" + + #include "EventDetector.h" + + + #define MARCA 10 + #define GERAFUGA 0 + #define UMCICLO 16.666666667 + +CaptureMailbox EventDetector::m_EventMailbox; +EventDetector EventDetector::m_Detector[NUMBER_OF_CHANNELS] = {0,1,2,3,4,5}; + +CaptureEvent::CaptureEvent() +{ +} + +//void CaptureEvent::Setup(char* rfid,int type,int outlet,float mv,float rms,float gain, int offset,float* sin, float* cos) +void CaptureEvent::Setup(char* rfid, int type, int outlet, float mv, float mv2, float rms, int under, int over, float gain, int offset, int duration, short int *samples) +{ + memcpy(m_RFID,rfid,9); + m_Type = type; + m_OutletNumber = outlet; + m_MeanValue = mv; + m_MV2 = mv2; + m_RMSValue = rms; + m_Under = under; + m_Over = over; + m_Gain = gain; + m_Offset = offset; + m_Duration = duration; + memcpy(m_Samples, samples, (sizeof(short int) * NUMBER_OF_SAMPLES) ); +} + +EventDetector::EventDetector(int ch) +{ + m_Channel = ch; + m_OutletTriggered = false; + m_EventCounter = 0; +} + +//void EventDetector::ProcessEvent(float rmsvalue, int t) +void EventDetector::ProcessEvent(float rmsvalue, float mv2, int under, int over) +{ + int i, tempofuga = 0; + short int aux; + //short int buf[NUMBER_OF_SAMPLES]; + float newvm; + + if(rmsvalue > Settings::get_Limit(m_Channel)) + { + /* Retira o VM das amostras */ + //pega os dados da captura atual + newvm = 0; + //Capture::CopyBuffer(m_Channel,buf); + + /* Retira o valorMedio de todas as amostras */ + for(i=0; i < NUMBER_OF_SAMPLES; i++){ + aux = Capture::GetValue(i, m_Channel) - mv2; + Capture::PutValue(i, m_Channel, aux) ; + newvm += aux; + } + + if ( m_EventCounter == Settings::get_EventLimit() ){ + mv2 = newvm / NUMBER_OF_SAMPLES; + //printf("Novo valor medio %f RMS original %f\n", mv2, rmsvalue); + } + + rmsvalue = SignalProcessor::CalculateRMS( m_Channel ); + + if(!m_OutletTriggered) + { + if (rmsvalue > Settings::get_Limit(m_Channel)) { + if(m_EventCounter < Settings::get_EventLimit() ) + { + m_EventCounter++; + } + else + { + //printf("Deu evento de liga ou Fuga\n"); + if (m_Channel % 2 == 1) // Canais impares sao de diferencial + m_tempo.start(); + m_OutletTriggered = true; + + SendMessage(0, rmsvalue, mv2, under, over, 0); + + //OnTrigger(buf, rmsvalue, mv2, under, over, 0); //TODO: must change the parameter of this function call + + m_EventCounter = 0; + } + } + } + else + m_EventCounter = 0; + } + else + { + if(m_OutletTriggered) + { + if(m_EventCounter < Settings::get_EventLimit()) + { + m_EventCounter++; + } + else + { + //printf("Terminou evento de liga ou Fuga\n"); + if (m_Channel % 2 == 1){ // Canais impares sao de diferencial + //m_tempo.stop(); + tempofuga = (int) (Settings::get_EventLimit() * UMCICLO) + m_tempo.read_ms(); + //printf("Limite %d\n", (int) (Settings::get_EventLimit() * UMCICLO)); + m_tempo.reset(); + } + else + tempofuga = 0; + m_OutletTriggered = false; + + SendMessage(0, rmsvalue, mv2, under, over, tempofuga); + //OnTrigger(buf, rmsvalue, mv2, under, over, tempofuga);//TODO: must change the parameter of this function call + //printf("===> contliga %d contdesliga %d\n", contliga, contdesl); + + m_EventCounter = 0; + } + } + else + m_EventCounter = 0; + } +} + +void EventDetector::ShowValues(CaptureEvent* e) +{ + int i; + + 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("MV2: %f\n", e->get_MV2()); + printf("RMSValue: %f\n", e->get_RMSValue()); + printf("Underflow: %d\n", e->get_Under()); + printf("Overflow: %d\n", e->get_Over()); + printf("Gain: %f\n", e->get_Gain()); + printf("Offset: %d\n", e->get_Offset()); + printf("Duration: %d\n", e->get_Duration()); + + + for(i=0;i<NUMBER_OF_SAMPLES;i++) + { + printf("%d,",e->get_SampleValue(i)); + } + +} + +void EventDetector::ExternalTrigger() +{ + // Ajustar valores de mv2, under, over e duration na chamada!!! + SendMessage(1, 0, 0, 0, 0, 0); +} + +//void EventDetector::SendMessage(int ext,float rmsvalue) +void EventDetector::SendMessage(int ext, float rmsvalue, float mv2, int under, int over, int duration) +{ + int flagrfid = 0; + short int buf[NUMBER_OF_SAMPLES]; + + //printf("Chegou SendMessage\n"); + //Here we must alloc a CaptureEvent object from mailbox pool, + + //CaptureEvent* event; + CaptureEvent* event = GetMailbox().alloc(); + + + //printf("Capturou evento\n"); + //then initialize the object properly + + /* O buffer foi coletado no ProcessEvent para retirada do VM + unsigned short int buf[NUMBER_OF_SAMPLES]; + Capture::CopyBuffer(m_Channel,buf); + */ + if(ext) + { + rmsvalue = 0;//SignalProcessor::CalculateRMS(buf,m_Channel); + } + + float mv; + + int type=0,outlet_number=0, aux=0; + aux = Settings::get_OutletNumber(m_Channel); + outlet_number = Settings::get_Outlet(aux); + + //Temporario - Sem leitor de RFID + //char rfid[9] = "1234560"; + //rfid[7] = (char)outlet_number + '0'; + + // Com leitor de RFID + char rfid[9], aux2[5]; + //rfid[0] = '\0'; + //send hitag request + //capture hitag response + //printf("OUTLET=%d\n",outlet_index+1); + + + if (Settings::get_ReadRfid()){ + + Capture::ReadRFID(outlet_number,rfid); + + if (strcmp(rfid, "00000000") != 0){ // get rfid number + //printf("Leu RFID [%s]\n", rfid); + flagrfid = 1; + } + } + if (! flagrfid){ + strcpy(rfid, "FFFF"); + sprintf(aux2, "%04d", outlet_number); + strcat(rfid, aux2); + //rfid[7] = (char)outlet_number + '0'; + } + //printf("#%s#\n", rfid); + + 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) + printf("Fuga na tomada %d com rms %f\n", outlet_number, rmsvalue); + + if (type == 4) + printf("Liga na tomada %d com rms %f\n", outlet_number, rmsvalue); + + if (type == 5) + printf("Desliga na tomada %d com rms %f\n", outlet_number, rmsvalue); + + if (type == 6) + printf("Final de fuga na tomada %d com rms %f\n", outlet_number, rmsvalue); + + //event->Setup(rfid,type,outlet_number,mv,rmsvalue,Settings::get_Gain(m_Channel),Settings::get_Offset(m_Channel),seno,coss); + + //printf("Chegou montar evento\n"); + + Capture::CopyBuffer( m_Channel, buf ); + + event->Setup(rfid,type,outlet_number,mv,mv2, rmsvalue,under, over, Settings::get_Gain(m_Channel),Settings::get_Offset(m_Channel),duration, buf); + + //printf("\n\nDuration: %d\n\n", duration); + //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; + } +}
diff -r 000000000000 -r fac116e94d44 Codes/Http_post.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/Http_post.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,203 @@ +/* + * Http_post.cpp + * + * Created on: + * Author: + */ +#include "Http_post.h" +#include "Pmed_reset.h" + +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 "); + tranca.wait(); + CaptureEvent* cap = (CaptureEvent*)evt.value.p; + //printf("Pegou evento\n"); + DoPost(sock,Settings::get_ServerUrl(),cap); + mbox.free(cap); + tranca.release(); + //printf("Enviado e Liberado Mbox ...\n "); + //sock.reset_address(); + } + //Thread::yield(); + } +} + + + +void HttpPost::DoPost(TCPSocketConnection sock, char *host, CaptureEvent* dados){ + char *http_cmd; + int escritos, r=-1, i; + + http_cmd = (char *) malloc(1800); + + if (http_cmd == NULL) + printf("Sem memoria\n"); + + memset(http_cmd, 0, 1800); + + PreparePost( dados,http_cmd ); + + //printf("Tamanho do comando %d\n", strlen(http_cmd)); + //printf("Comando: /* %s */\n", http_cmd); + + + + for(i=0; i < 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 < 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 != MAXTRIES ) + Thread::wait(Settings::get_DelaySend()); + else{ + //printf("Reset\n"); + + Pmed_reset(PMEDLOG_HTTP_CONNECT); + } + + //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"); + + Pmed_reset(PMEDLOG_HTTP_SEND); + } + + sock.close(); + free(http_cmd); + +} + +void HttpPost::PreparePost(CaptureEvent* dados,char *strfinal){ + char aux[20]; + int i, ContentLen = 1662; + + const char *header1 = "POST /capturesfft.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,"%d",ContentLen); + + strcat(strfinal, "Content-Length: "); + strcat(strfinal, aux); + strcat(strfinal, header2); + + sprintf(aux,"TYPE=%02d",dados->get_Type()); + strcat(strfinal, aux); + //ContentLen += 7; + + sprintf(aux,"&OUTLET=%03d",dados->get_OutletNumber()); + strcat(strfinal, aux); + //ContentLen += 11; + + sprintf(aux,"&RFID=%s", dados->get_RFID()); + strcat(strfinal,aux); + //ContentLen += 14; + + sprintf(aux,"&OFFSET=%04d",dados->get_Offset()); + strcat(strfinal,aux); + //ContentLen += 12; + + float f = dados->get_Gain(); + sprintf(aux,"&GAIN=%08X", *(unsigned int*)&f); + strcat(strfinal,aux); + //ContentLen += 14; + + f = dados->get_RMSValue(); + sprintf(aux,"&RMS=%08X",*(unsigned int*)&f); + strcat(strfinal,aux); + //ContentLen += 13; + + f = dados->get_MeanValue(); + sprintf(aux,"&MV=%08X",*(unsigned int*)&f); + strcat(strfinal,aux); + //ContentLen += 12; + + sprintf(aux,"&UNDER=%04d",dados->get_Under()); + strcat(strfinal,aux); + //ContentLen += 11; + + sprintf(aux,"&OVER=%04d",dados->get_Over()); + strcat(strfinal,aux); + //ContentLen += 10; + + sprintf(aux,"&DURATION=%04d",dados->get_Duration()); + strcat(strfinal,aux); + //ContentLen += 14; + + char s[7]; + strcat(strfinal,"&SAMPLES="); + + for(i=0;i<NUMBER_OF_SAMPLES;i++) + { + sprintf(s,"%05d",dados->get_SampleValue(i)); + + strcat(strfinal,s); + if (i < (NUMBER_OF_SAMPLES - 1)) + strcat(strfinal, ";"); + } + + strcat(strfinal,"\r\n"); + + //printf("Request=[%s]\n",strfinal); + //printf("Tamanho STRFINAL %d\n", strlen(strfinal)); + } \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Codes/PmedLog.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/PmedLog.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,48 @@ +/* + * Settings.cpp + * + * Created on: 19/jan/2015 + * Author: Marcos A. Lucas + */ + +#include "PmedLog.h" + +int PmedLog::m_entry = 0; +time_t PmedLog::m_lastMark = 0; + +void PmedLog::WriteEntry(const char *value) +{ + time_t seconds = time(NULL); + + char buffer[32]; + strftime(buffer, 32, "%T", localtime(&seconds)); + + printf("LOG : %s : %.5d : %s \n", buffer, m_entry, value); + + FILE *f = fopen(LOGFILE,"a"); + + if(f == NULL) + { + printf("Error creating log file\r\n"); + return; + } + + fprintf(f, "%s : %.5d : %s\n", buffer, m_entry, value); + + fclose(f); + + m_entry++; +} + +void PmedLog::Mark() +{ + if (!get_LogMarks()) return; + + time_t seconds = time(NULL); + time_t difference = seconds - m_lastMark; + + if ( difference >= get_LogMarksInterval() ) { + m_lastMark = seconds; + WriteEntry(" . -- === MARK === -- . "); + } +}
diff -r 000000000000 -r fac116e94d44 Codes/Settings.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/Settings.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,409 @@ +/* + * 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_ReadRfid = 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_Samples = 0; +int Settings::m_MaxHarmonics = 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; + +bool Settings::m_logMarks = true; +int Settings::m_logMarksInterval = 40; + +//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_ReadRfid(1); // default read RFID + + set_ModuleNumber(1); +// set_MaxChannels(NUMBER_OF_CHANNELS); +// set_MaxOutlets(NUMBER_OF_OUTLETS); +// set_FreqBase(60); +// set_Samples(256); + set_MaxHarmonics(12); + set_EventLimit(3); + set_MBoxLength(10); +// set_NumNeighbors(3); +// set_PortTCP(7890); +// set_MaxTries(10); + set_DelayTry(500); + set_DelaySend(50); + + set_LogMarks(true); + set_LogMarksInterval(40); + + int i; + + for(i=0;i<NUMBER_OF_CHANNELS;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<NUMBER_OF_OUTLETS;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],"ReadRFID")) + { + if(!strcmp(line[1],"false")) + set_ReadRfid(0); + else + set_ReadRfid(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<NUMBER_OF_CHANNELS;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<NUMBER_OF_OUTLETS;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 + } + + if(!strcmp(line[0],"LogMarks")) + { + if(!strcmp(line[1],"false")) + set_LogMarks(false); + else + set_LogMarks(true); + } + + if(!strcmp(line[0],"LogMarksInterval")) + { + set_LogMarksInterval(atoi(line[1])); + } + + //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"); + + if(get_ReadRfid()) + fprintf(f,"ReadRFID=true\r\n"); + else + fprintf(f,"ReadRFID=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<NUMBER_OF_CHANNELS;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<NUMBER_OF_OUTLETS;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()); + + if(get_LogMarks()) + fprintf(f,"LogMarks=true\r\n"); + else + fprintf(f,"LogMarks=false\r\n"); + + fprintf(f,"LogMarksInterval=%d\r\n",get_LogMarksInterval()); + + + 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("ReadRFID: %d\n", get_ReadRfid()); + printf("ModuleNumber: %d\n", get_ModuleNumber() ); +// printf("FreqBase : %d\n", get_FreqBase() ); +// printf("Samples : %d\n" , get_Samples() ); +// printf("MaxChannels : %d\n", get_MaxChannels() ); +// printf("MaxOutlets : %d\n", get_MaxOutlets() ); + printf("EventLimit : %d\n" , get_EventLimit() ); + printf("MBoxLength : %d\n" , get_MBoxLength() ); + printf("Per Channel\n"); + int i; + for(i=0;i<NUMBER_OF_CHANNELS;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<NUMBER_OF_OUTLETS;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
diff -r 000000000000 -r fac116e94d44 Codes/SignalProcessor.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/SignalProcessor.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,452 @@ +/* + * SignalProcessor.cpp + * + * Created on: + * Author: + */ + +#include <math.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> + +#include "SignalProcessor.h" +#include "limites.h" + +#define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr +#define PI 3.14159265358979323846F +// 3.141597653564793332212487132 +// 3.14159265358979323846 + + +/* Elementos vm2, under, over adicionados em 20/05/2014 por Rebonatto */ +/* vm2 eh o calculo do valor medio, under eh a cotagem dos valores do AD com 0 */ +/* over e a contagem do AD com 4095 */ +/* over e under sao para verificar se o processo de ajuste dos dados esta Ok e vm2 para conferir o vm da fft */ +void SignalProcessor::CalculateRMSBulk(float *result, float *vm2, int *under, int *over) +{ + int nChannel,nSample; + short int v; + float val; + + // initialized vectors of results + for(nChannel=0;nChannel<NUMBER_OF_CHANNELS;nChannel++) + result[nChannel] = vm2[nChannel] = under[nChannel] = over[nChannel] = 0; + + // procedd calculus + for(nChannel=0;nChannel<NUMBER_OF_CHANNELS;nChannel++) + { + for(nSample=0;nSample<NUMBER_OF_SAMPLES;nSample++) + { + v = Capture::GetValue(nSample, nChannel); + /* novos calculos */ + vm2[nChannel] += v; + if (v <= 20) + under[nChannel] = under[nChannel] + 1; + if (v >= 4075) + over[nChannel] = over[nChannel] + 1; + + val = (float)v; + + val -= Settings::get_Offset(nChannel); + val /= Settings::get_Gain(nChannel); + val *= val; + result[nChannel] += val; + } + result[nChannel] /= (float)NUMBER_OF_SAMPLES; + result[nChannel] = sqrt(result[nChannel]); + + /* novos calculos */ + vm2[nChannel] /= (float)NUMBER_OF_SAMPLES; + } +} + +float SignalProcessor::CalculateRMS(int nChannel) +{ + float val, result=0; + int nSample; + short int v; + + for(nSample=0;nSample<NUMBER_OF_SAMPLES;nSample++) + { + v = Capture::GetValue(nSample, nChannel); + val = (float)v; + // cada ponto + //val -= Settings::get_Offset(nChannel); // diminui o offset + val /= Settings::get_Gain(nChannel); // divide pelo ganhp + val *= val; // eleva ao quadrado + result += val; // soma + } + result /= (float)NUMBER_OF_SAMPLES; // divide pelo numero de amostras (256) + result = sqrt(result); + return result; +} + +float SignalProcessor::CalculateRMSFloat( float *buffer,int nChannel) +{ + float result=0, val; + int nSample; + + for(nSample=0;nSample<NUMBER_OF_SAMPLES;nSample++) + { + val = buffer[nSample]; + /* + short int v = buffer[nSample]; + float val = (float)v; + */ // cada ponto + //val -= Settings::get_Offset(nChannel); // diminui o offset + val /= Settings::get_Gain(nChannel); // divide pelo ganho + val *= val; // eleva ao quadrado + result += val; // soma + } + result /= NUMBER_OF_SAMPLES; // divide pelo numero de amostras (256) + result = sqrt(result); + return result; +} + + +void SignalProcessor::CalculateFFT(float *buffer,float *sen,float *cos,float *vm,int sign, int ch) +{ + /* + for(int i=0; i < Settings::get_Samples(); i++) + printf("%d*",buffer[i]); + printf("\n"); + */ + + //printf("[0] %d %d %d %d\n", buffer[0], buffer[100], buffer[200], buffer[255]); + /* + for(i=0; i<Settings::get_Samples();i++) + value[i]= (float) ( (buffer[i] - Settings::get_Offset(ch)) / Settings::get_Gain(ch) ); + */ + + //float* fft = ComplexFFT(buffer,1, ch); //deve desalocar memoria do ptr retornado + ComplexFFT(buffer,1, ch); //deve desalocar memoria do ptr retornado + + /* usado em teste + *vm = ComplexFFT(buffer, fft, 1, ch); //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 = DFT(value, sen, cos); + + *vm = buffer[0]; + //printf("Valor medio da FFT %.4f \n", buffer[0]); + + for(int i=1;i<Settings::get_MaxHarmonics()+1;i++) + { + cos[i-1] = buffer[i*2]; + sen[i-1] = buffer[i*2+1]; + } + + /* + for(int i=0;i<Settings::get_MaxHarmonics();i++) + { + printf("[%dHz]\tsen %.4f\tcos %.4f\n", (i+1)*60, sen[i], cos[i]); + } + */ + + //free(fft); + + //printf("[3] %d %d %d %d\n", buffer[0], buffer[100], buffer[200], buffer[255]); +} + +float* SignalProcessor::ComplexFFT(float* data, int sign, int ch) +{ + + //variables for the fft + unsigned long n,mmax,m,j,istep,i, met; + //double wtemp,wr,wpr,wpi,wi,theta,tempr,tempi; + float 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] + + /* + printf("Original\n"); + for(int i=0; i < NUMBER_OF_SAMPLES; i++) + printf("%.2f ", data[i]); + printf("\n"); + */ + + //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 + + //printf("Antes malloc\n"); + /* + vector=(float*)malloc(2*NUMBER_OF_SAMPLES*sizeof(float)); + memset(vector,0,2*NUMBER_OF_SAMPLES*sizeof(float)); + */ + //printf("DEpois malloc\n"); + + // DisplayRAMBanks(); + + //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<NUMBER_OF_SAMPLES;n++) + { + if(n<NUMBER_OF_SAMPLES){ + //vector[2*n]= (float) ( (data[n] - Settings::get_Offset(ch)) / Settings::get_Gain(ch) ); + vector[2*n]= (float) data[n] ; + // printf("%.4f$", vector[2*n]); + } + else + vector[2*n]=0; + vector[2*n+1]=0; + } + */ + /* trazendo o vetor em float, com metade ocupada, mudança dos valores reais e complexos + //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 + */ + /* + printf("Original\n"); + for(int i=0; i < NUMBER_OF_SAMPLES*2; i++) + printf("%.2f ", data[i]); + printf("\n"); + */ + met=NUMBER_OF_SAMPLES-1; + for(n=NUMBER_OF_SAMPLES*2-1; n > 0; n--){ + if (n % 2 == 0){ + data[n] = data[met]; + met--; + } + else + data[n] = 0; + } + + /* + printf("Modificado\n"); + for(int i=0; i < NUMBER_OF_SAMPLES*2; i++) + printf("%.2f ", data[i]); + printf("\n"); + */ + + //printf("[0] %.2f [100] %.2f [201] %.2f [255] %.2f\n", data[0], data[100], data[201], data[255]); + + //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=NUMBER_OF_SAMPLES << 1; //multiply by 2 + j=0; + for (i=0;i<n/2;i+=2) { + if (j > i) { + SWAP(data[j],data[i]); + SWAP(data[j+1],data[i+1]); + if((j/2)<(n/4)){ + SWAP(data[(n-(i+2))],data[(n-(j+2))]); + SWAP(data[(n-(i+2))+1],data[(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*data[j-1]-wi*data[j]; + tempi=wr*data[j]+wi*data[j-1]; + data[j-1]=data[i-1]-tempr; + data[j]=data[i]-tempi; + data[i-1] += tempr; + data[i] += tempi; + } + wr=(wtemp=wr)*wpr-wi*wpi+wr; + wi=wi*wpr+wtemp*wpi+wi; + } + mmax=istep; + } + //end of the algorithm + + + // Ajustes a FFT + for(i = 0; i < NUMBER_OF_SAMPLES*2; i++ ){ + data[i] = (float) ((2 * data[i]) / NUMBER_OF_SAMPLES ); + + if (i % 2 == 1) + data[i] = data[i] * -1; + } + + //printf("[2] %d %d %d %d\n", data[0], data[100], data[200], data[255]); + /* + printf("Na funcao\n"); + for(int i=1;i<Settings::get_MaxHarmonics()*2+1;i++) + { + printf("[%dHz]\tsen %.4f\tcos %.4f\n", i*60, data[i*2+1], data[i*2]); + } + */ + return NULL; +} + +float SignalProcessor::ComplexFFTTeste(unsigned short int* data, float *vector, int sign, int ch) +{ + + //variables for the fft + unsigned long n,mmax,m,j,istep,i; + //double wtemp,wr,wpr,wpi,wi,theta,tempr,tempi; + float 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 + + //printf("Antes malloc\n"); + //vector=(float*)malloc(2*Settings::get_Samples()*sizeof(float)); + memset(vector,0,2*NUMBER_OF_SAMPLES*sizeof(float)); + //printf("DEpois memset\n"); + + + DisplayRAMBanks(); + + //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<NUMBER_OF_SAMPLES;n++) + { + if(n<NUMBER_OF_SAMPLES){ + //vector[2*n]= (float) ( (data[n] - Settings::get_Offset(ch)) / Settings::get_Gain(ch) ); + vector[2*n]= (float) data[n] ; + // printf("%.4f$", vector[2*n]); + } + else + vector[2*n]=0; + vector[2*n+1]=0; + } + + //printf("Passou primeiro lcao\n"); + + //printf("[1] %d %d %d %d\n", data[0], data[100], data[200], data[255]); + + //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=NUMBER_OF_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 + + printf("Passou Segundo lcao\n"); + + //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 + + printf("Fim FFT\n"); + /* + // Ajustes a FFT + for(i = 0; i < Settings::get_Samples()*2; i++ ){ + vector[i] = (float) ((2 * vector[i]) / Settings::get_Samples() ); + + if (i % 2 == 1) + vector[i] = vector[i] * -1; + + } + */ + //printf("[2] %d %d %d %d\n", data[0], data[100], data[200], data[255]); + + return vector[0]; +} + + +/* +float SignalProcessor::DFT(float *data, float *seno, float *coss){ + int i, j; + + for(i=0; i < Settings::get_MaxHarmonics()+1; i++) + seno[i] = coss[i] = 0; + + for(i=0; i < Settings::get_Samples(); i++){ + for(j = 0; j < Settings::get_MaxHarmonics()+1; j++ ){ + coss[j] += (data[i] * (cos( (2 * PI * i * j) / Settings::get_Samples() ) ) ) ; + seno[j] += (data[i] * (sin( (2 * PI * i * j) / Settings::get_Samples() ) ) ) ; + } + } + + for(j = 1; j < Settings::get_MaxHarmonics()+1; j++ ){ + coss[j] = 2 * coss[j] / Settings::get_Samples(); + seno[j] = 2 * seno[j] / Settings::get_Samples() ; + } + return (float) (coss[0] / Settings::get_Samples()) + (seno[0] / Settings::get_Samples()); +} +*/ +
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_getparam.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_getparam.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,125 @@ +#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 %s\n", argv[1]); + + 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],"Ipaddress")) + { + conn->send("\r\nIpaddress=",strlen("\r\nIpaddress=")); + conn->send(Settings::get_IpAddress(),strlen(Settings::get_IpAddress())); + 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; + } + + /* Pega os numeros das tomadas [0..2]*/ + int i; + for(i=0;i<NUMBER_OF_OUTLETS;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; + } + } + /* pega os dados dos canais [0..5] */ + for(i=0;i<NUMBER_OF_CHANNELS;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; + } + } + +/* + if(!strcmp(argv[1],"Samples")) + { + char b[12]; + conn->send("\r\nSamples=",strlen("\r\nSamples=")); + sprintf(b,"%d\r\n",NUMBER_OF_SAMPLES); + conn->send(b,strlen(b)); + return 0; + } +*/ + if(!strcmp(argv[1],"EventLimit")) + { + char b[12]; + conn->send("\r\nEventLimit=",strlen("\r\nEventLimit=")); + sprintf(b,"%d\r\n",Settings::get_EventLimit()); + conn->send(b,strlen(b)); + return 0; + } + + conn->send(param_not_found_msg_get,strlen(param_not_found_msg_get)); + return 0; + +}
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_help.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_help.cpp Tue Jan 05 11:47:35 2016 +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
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_listparam.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_listparam.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,36 @@ +#include "TelnetServer.h" +#define NUMBERPARAM 10 + +char *msg_list_param[NUMBERPARAM] = { "Ipserver", + "Ipaddress", + "module", + "outlet[0..2]", + "gain[0..5]", + "offset[0..5]", + "limit[0..5]", + "outlet_number[0..5]", + "purpose[0..5]", + "EventLimit" }; + +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
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_remove.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_remove.cpp Tue Jan 05 11:47:35 2016 +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
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_reset.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_reset.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,19 @@ +#include "TelnetServer.h" +#include "Pmed_reset.h" + +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; + + Pmed_reset(PMEDLOG_RESETTELNET); + + return 0; +} \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_setparam.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_setparam.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,155 @@ +#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_ServerUrl(argv[2]); + Settings::WriteFile(); + } + return 0; + } + + if(!strcmp(argv[1],"Ipaddress")) + { + 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; + } + + /* Pega os números das tomadas [0..2]*/ + 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; + } + } + /* Pega os canais, de 0..5 */ + 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; + } + } + +/* + if(!strcmp(argv[1],"Samples")) + { + Settings::set_Samples(atoi(argv[2])); + Settings::WriteFile(); + return 0; + } +*/ + if(!strcmp(argv[1],"EventLimit")) + { + Settings::set_EventLimit(atoi(argv[2])); + Settings::WriteFile(); + return 0; + } + + if(!strcmp(argv[1],"LogMarksInterval")) + { + int value = atoi(argv[2]); + if ( ! ( value > 0 ) ) { + conn->send(bad_argument_set,strlen(bad_argument_set)); + return 0; + } + Settings::set_LogMarksInterval(atoi(argv[2])); + Settings::WriteFile(); + return 0; + } + + if(!strcmp(argv[1],"LogMarks")) + { + if ( strcmp(argv[2],"true") == 0 ) { + Settings::set_LogMarks(true); + } else { + Settings::set_LogMarks(false); + } + 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
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_update.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_update.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,92 @@ +#include "TelnetServer.h" +#include "Settings.h" +#include "Pmed_reset.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; + +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; + + Pmed_reset(PMEDLOG_UPDATETELNET); + + return 0; +}
diff -r 000000000000 -r fac116e94d44 Codes/TelnetCommands/telnet_version.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetCommands/telnet_version.cpp Tue Jan 05 11:47:35 2016 +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
diff -r 000000000000 -r fac116e94d44 Codes/TelnetServer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TelnetServer.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,216 @@ +/* + 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 *command_not_found_msg_get = "Command not found.\r\n\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, flag; + 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 %d *%s*\n", r, buf); + //printf("\n\nGot Here2 [%s]\n\n", buf_rec); + + 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]); + flag = 1; + //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 + { + flag = 0; + cmds[i].pfn(conn,command,command_count); + break; + } + } + } + + if (flag) + conn->send(command_not_found_msg_get,strlen(command_not_found_msg_get)); + + //write the prompt + conn->send(prompt_msg,strlen(prompt_msg)); + buffer_ptr=0; + } + } + //buf_rec[0] = buf[0] = buffer[0] = '\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); + + } + +} +
diff -r 000000000000 -r fac116e94d44 Codes/TftpServer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/TftpServer.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,238 @@ +#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
diff -r 000000000000 -r fac116e94d44 Codes/ntpc.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/ntpc.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,24 @@ +#include "ntpc.h" + +void ntpc::ntpc_Thread(void const* arg) +{ + printf("\r\nTrhead NTP client\r\n"); + while (true) + { + ntpcDo(); + wait(30); + } +} + +void ntpc::ntpcDo() +{ + printf("Pegando NTP...\r\n"); + if (ntpClient.setTime("ntp.ubuntu.com") == 0) { + printf("NTP OK!\r\n"); + time_t ctTime; + ctTime = time(NULL); + printf("Setando para hora (UTC): %s\r\n", ctime(&ctTime)); + } else { + printf("NTP Erro!\r\n"); + } +} \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Codes/tftpsrv.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Codes/tftpsrv.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,301 @@ +#include "tftpsrv.h" +#include <ctype.h> + +void tftpsrv::tftpsrv_Thread(void const* arg) +{ + printf("\r\nTFTP start...\r\n"); + + tftpInicia(); + + int tam = 0; + char buffer[516]; + + int instancias = 10; + while (instancias > 0) { + // DEBUG ("\r\nEsperando pacote...\r\n"); + tam = server.receiveFrom(client, buffer, sizeof(buffer)); + while ( tam > 0 ) { + // DEBUG ("\r\nPacote recebido...\r\n"); + switch (estado) { + case ESCUTANDO: + tftpEscutando(buffer); + break; + case LENDO: + tftpLendo(buffer); + break; + case ESCREVENDO: + tftpEscrevendo(tam, buffer); + break; + default: + tftpErr("Desconhecido ou nao implementado"); + } + // DEBUG ("\r\nEsperando pacote...\r\n"); + tam = server.receiveFrom(client, buffer, sizeof(buffer)); + } + tftpReinicia(); + instancias--; + printf("\r\nRestam %d instancias...\r\n", instancias); + //DEBUG ("\r\nRestam %d instancias...\r\n", instancias); + } + printf("Caiu fora TFTP\n"); + + // DEBUG ("\r\nTFTP end...\r\n"); +} + + + +void tftpsrv::tftpInicia() +{ + // DEBUG ("\r\nIniciando TFTP...\r\n"); + //server.init(); + server.bind(69); + estado = ESCUTANDO; + server.set_blocking(false, 20000); +} + +void tftpsrv::tftpPara() +{ + // DEBUG ("\r\nParando TFTP...\r\n"); + server.close(); + if (fp!=NULL) fclose(fp); +} + +void tftpsrv::tftpReinicia() +{ + tftpPara(); + tftpInicia(); +} + +// send ACK to remote +void tftpsrv::tftpAck(int val) +{ + char ack[4]; + ack[0] = 0x00; + ack[1] = 0x04; + if ((val>603135) || (val<0)) val = 0; + ack[2] = val >> 8; + ack[3] = val & 255; + + // DEBUG ("\r\nEnviando ACK...\r\n"); + server.sendTo(client, ack, 4); +} + +// send ERR message to named client +void tftpsrv::tftpErr(char* msg) +{ + char message[32]; + strncpy(message, msg, 32); + char err[37]; + sprintf(err, "0000%s0", message); + err[0] = 0x00; + err[1] = 0x05; + err[2]=0x00; + err[3]=0x00; + int len = strlen(err); + err[len-1] = 0x00; + // DEBUG ("\r\nEnviando ERR ( %s )...\r\n", message); + server.sendTo(client, err, len); +} + +int tftpsrv::tftpModo(char* buff) +{ + int x = 2; + while (buff[x++] != 0); // get beginning of mode field + int y = x; + while (buff[y] != 0) { + buff[y] = tolower(buff[y]); + y++; + } // make mode field lowercase + return (strcmp(&buff[x++], "octet") == 0); +} + +// get DATA block from file on disk into memory +void tftpsrv::tftpGetBlock() +{ + // DEBUG ("\r\nLendo bloco... (em %d)\r\n", blockcnt); + blockcnt++; + char *p; + p = &sendbuff[4]; + int len = fread(p, 1, 512, fp); + sendbuff[0] = 0x00; + sendbuff[1] = 0x03; + sendbuff[2] = blockcnt >> 8; + sendbuff[3] = blockcnt & 255; + blocksize = len+4; +} + +// send DATA block to the client +void tftpsrv::tftpSendBlock() +{ + // DEBUG ("\r\nEnviando bloco ( tam = %d )...\r\n", blocksize); + server.sendTo(client, sendbuff, blocksize); +} + + +void tftpsrv::tftpLer(char* buff) +{ + tftpAck(0); + + blockcnt = 0; + dupcnt = 0; + + sprintf(filename, "/local/%s", &buff[2]); + + fp = fopen(filename, "rb"); + if (fp == NULL) { + estado = ESCUTANDO; + tftpErr("Could not read file"); + } else { + // file ready for reading + estado = LENDO; + // DEBUG ("\r\nRequisitado arquivo %s para %s\r\n", filename, client.get_address()); + tftpGetBlock(); + tftpSendBlock(); + } +} + +void tftpsrv::tftpEscrever(char* buff) +{ + struct dirent *p; + DIR *dir = opendir("/local"); + while ((p = readdir(dir)) != NULL) { + char *str = p->d_name; + if ((strstr(str, ".bin") != NULL) || (strstr(str, ".BIN") != NULL)) { + char buf[BUFSIZ]; + snprintf(buf, sizeof(buf) - 1, "/local/%s", str); + remove(buf) == 0; + } + } + closedir(dir); + + tftpAck(0); + blockcnt = 0; + dupcnt = 0; + + sprintf(filename, "/local/%s", &buff[2]); + + fp = fopen(filename, "ab"); + if (fp == NULL) { + tftpErr("Could not open file to write"); + estado = ESCUTANDO; + } else { + // file ready for writing + fseek(fp, 0, SEEK_SET); + blockcnt = 0; + estado = ESCREVENDO; + // DEBUG ("\r\nRecebendo arquivo %s de %s\r\n", filename, client.get_address()); + } +} + +void tftpsrv::tftpEscutando(char* buff) +{ + // DEBUG ("\r\nEscutando...\r\n"); + switch (buff[1]) { + case 0x01: // RRQ + if (tftpModo(buff)) + tftpLer(buff); + else + tftpErr("Not in octet mode"); + break; + case 0x02: // WRQ + if (tftpModo(buff)) + tftpEscrever(buff); + else + tftpErr("Not in octet mode"); + break; + case 0x03: // DATA before connection established + tftpErr("No data expected"); + break; + case 0x04: // ACK before connection established + tftpErr("No ack expected"); + break; + case 0x05: // ERROR packet received + // DEBUG ("TFTP Eror received\n\r"); + break; + default: // unknown TFTP packet type + tftpErr("Unknown TFTP packet type"); + break; + } // switch buff[1] +} + +void tftpsrv::tftpLendo(char *buff) +{ + // DEBUG ("\r\nLendo...\r\n"); + switch (buff[1]) { + case 0x01: + // to-do: verificar host e ip + break; + case 0x02: + // this should never happen, ignore + break; // case 0x02 + case 0x03: + // we are the sending side, ignore + break; + case 0x04: + // last packet received, send next if there is one + dupcnt = 0; + if (blocksize == 516) { + tftpGetBlock(); + tftpSendBlock(); + } else { //EOF + // DEBUG ("\r\nFim de arquivo\r\n"); + fclose(fp); + estado = ESCUTANDO; + } + break; + default: // this includes 0x05 errors + fclose(fp); + estado = ESCUTANDO; + break; + } // switch (buff[1]) +} + +void tftpsrv::tftpEscrevendo(int tam, char *buff) +{ + // DEBUG ("\r\nEscrevendo...\r\n"); + + int block; + switch (buff[1]) { + case 0x02: + // a fazer: verificar host, ip e porta + break; // case 0x02 + case 0x03: + block = (buff[2] << 8) + buff[3]; + if ((blockcnt+1) == block) { + tftpAck(block); + // new packet + char *data = &buff[4]; + fwrite(data, 1,tam-4, fp); + blockcnt++; + dupcnt = 0; + } else { + if ((blockcnt+1) < block) { // high block nr + // we missed a packet, error + // DEBUG ("\r\nMissed packet!\r\n"); + fclose(fp); + estado = ESCUTANDO; + } else { // duplicate packet, do nothing + // DEBUG ("\r\nPacote duplicado ( %d )\r\n", blockcnt); + if (dupcnt > 10) { + tftpErr("Too many dups"); + fclose(fp); + estado = ESCUTANDO; + } else { + tftpAck(blockcnt); + } + dupcnt++; + } + } + // DEBUG ("\r\nLendo pacote %d com blocksize = %d\n\r", blockcnt, tam); + if (tam<516) { + // DEBUG ("\r\nFim do arquivo -> %d\r\n", tam); + fflush(fp); + fclose(fp); + estado = ESCUTANDO; + } + break; // case 0x03 + default: + tftpErr("No idea why you're sending me this!"); + break; // default + } // switch (buff[1]) +}
diff -r 000000000000 -r fac116e94d44 Drivers/adc.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Drivers/adc.c Tue Jan 05 11:47:35 2016 +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; + } +}
diff -r 000000000000 -r fac116e94d44 Drivers/adc.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Drivers/adc.h Tue Jan 05 11:47:35 2016 +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_ */
diff -r 000000000000 -r fac116e94d44 Drivers/dma.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Drivers/dma.c Tue Jan 05 11:47:35 2016 +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); +}
diff -r 000000000000 -r fac116e94d44 Drivers/dma.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Drivers/dma.h Tue Jan 05 11:47:35 2016 +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
diff -r 000000000000 -r fac116e94d44 EthernetInterface.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/EthernetInterface.lib Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/mbed_official/code/EthernetInterface/#2fc406e2553f
diff -r 000000000000 -r fac116e94d44 Functions/Split.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Functions/Split.c Tue Jan 05 11:47:35 2016 +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; +}
diff -r 000000000000 -r fac116e94d44 Functions/Split.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Functions/Split.h Tue Jan 05 11:47:35 2016 +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_ */
diff -r 000000000000 -r fac116e94d44 Functions/limites.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Functions/limites.c Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,34 @@ +/* + * limites.c + * + * Created on: 20/07/2014 + * Author: rebonatto + */ + +#include "limites.h" + + +// These external symbols are maintained by the linker to indicate the +// location of various regions in the device's memory. They will be used by +// DisplayRAMBanks() to dump the size of each RAM bank to stdout. + +extern unsigned int Image$$RW_IRAM1$$Base; +extern unsigned int Image$$RW_IRAM1$$ZI$$Limit; +extern unsigned int Image$$RW_IRAM2$$Base; +extern unsigned int Image$$RW_IRAM2$$ZI$$Limit; +extern unsigned int Image$$RW_IRAM3$$Base; +extern unsigned int Image$$RW_IRAM3$$ZI$$Limit; + + +// Displays the size of static allocations for each RAM bank as indicated by +// ARM linker to stdout. +void DisplayRAMBanks(void) +{ + printf("Static RAM bank allocations\r\n"); + printf(" Main RAM = %u\r\n", (unsigned int)&Image$$RW_IRAM1$$ZI$$Limit - + (unsigned int)&Image$$RW_IRAM1$$Base); + printf(" RAM0 = %u\r\n", (unsigned int)&Image$$RW_IRAM2$$ZI$$Limit - + (unsigned int)&Image$$RW_IRAM2$$Base); + printf(" RAM1 = %u\r\n", (unsigned int)&Image$$RW_IRAM3$$ZI$$Limit - + (unsigned int)&Image$$RW_IRAM3$$Base); +}
diff -r 000000000000 -r fac116e94d44 Functions/limites.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Functions/limites.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,23 @@ +/* + * limites.h + * + * Created on: 20/07/2014 + * Author: rebonatto + */ + +#ifndef LIMITES_H_ +#define LIMITES_H_ + +#include <stdio.h> + +#ifdef __cplusplus +extern "C" { +#endif + +extern void DisplayRAMBanks(void); + +#ifdef __cplusplus +}; +#endif + +#endif /* LIMITES_H_ */ \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Functions/whatchdog.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Functions/whatchdog.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,19 @@ +// Simon's Watchdog code from +// http://mbed.org/forum/mbed/topic/508/ +class Watchdog { +public: +// Load timeout value in watchdog timer and enable + void kick(float s) { + LPC_WDT->WDCLKSEL = 0x1; // Set CLK src to PCLK + uint32_t clk = SystemCoreClock / 16; // WD has a fixed /4 prescaler, PCLK default is /4 + LPC_WDT->WDTC = s * (float)clk; + LPC_WDT->WDMOD = 0x3; // Enabled and Reset + kick(); + } +// "kick" or "feed" the dog - reset the watchdog timer +// by writing this required bit pattern + void kick() { + LPC_WDT->WDFEED = 0xAA; + LPC_WDT->WDFEED = 0x55; + } +}; \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Headers/Capture.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/Capture.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,62 @@ +/* + * 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" + +#define CHANNEL0 p15 +#define CHANNEL1 p16 +#define CHANNEL2 p17 +#define CHANNEL3 p18 +#define CHANNEL4 p19 +#define CHANNEL5 p20 + +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 short int m_AdcBuffers[NUMBER_OF_CHANNELS][NUMBER_OF_SAMPLES]; + // matrix m_AdcBuffers[6][128] + +public: + + static short int GetValue(int nsamples, int nchannel); + static void PutValue(int nsamples, int nchannel, short int value); + static void CopyBuffer(int channel, short int *dest); + //static void CopyBufferFloat(int channel, float *dest); + + //static void ISRHandler(); + + //static void Initialize(); + static void AcquireValues(); + //static void Start(); + //static void Stop(); + //static void Wait(); + + static void ReadRFID(int channel,char *rfid); + +}; + +#endif \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Headers/CommTCP.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/CommTCP.h Tue Jan 05 11:47:35 2016 +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
diff -r 000000000000 -r fac116e94d44 Headers/EventDetector.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/EventDetector.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,92 @@ +/* + * 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_MV2; + float m_RMSValue; + int m_Under; + int m_Over; + float m_Gain; + int m_Offset; + int m_Duration; + short int m_Samples[NUMBER_OF_SAMPLES]; + +public: + + CaptureEvent(); + + //void Setup(char* rfid,int type,int outlet,float mv,float rms,float gain, int offset,float* sin, float* cos); + void Setup(char* rfid, int type, int outlet, float mv, float mv2, float rms, int under, int over, float gain, int offset, int duration, short int *samples); + + 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_MV2() { return m_MV2; } + float get_RMSValue() { return m_RMSValue; } + int get_Under() { return m_Under; } + int get_Over() { return m_Over; } + float get_Gain() { return m_Gain; } + int get_Offset() { return m_Offset; } + int get_Duration() { return m_Duration; } + short int get_SampleValue(int idx) { return m_Samples[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; + Timer m_tempo; + + //void SendMessage(int ext,float rmsvalue); + void SendMessage(int ext, float rmsvalue, float mv2, int under, int over, int duration); + + int TimeDelay(int t); + +public: + + EventDetector(int ch); + + void ExternalTrigger(); + + //void ProcessEvent(float rmsvalue, int t); + void ProcessEvent(float rmsvalue, float mv2, int under, int over); + + 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
diff -r 000000000000 -r fac116e94d44 Headers/Http_post.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/Http_post.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,32 @@ +/* + * 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); +extern Semaphore tranca; + +class HttpPost +{ +protected: + +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
diff -r 000000000000 -r fac116e94d44 Headers/PmedLog.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/PmedLog.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,55 @@ +/* + * Settings.h + * + * Created on: 19/jan/2015 + * Author: Marcos A. Lucas + */ + +#ifndef PMEDLOG_H +#define PMEDLOG_H + +#include "mbed.h" +#include "Settings.h" + +#define LOGFILE "/local/pmedlog.txt" + + +//define as constant some log entries +static const char *PMEDLOG_INITIALIZING = " Initializing Protegemed ... "; +static const char *PMEDLOG_INITIALIZINGWDT = " Initializing Protegemed by WhatchDog Timer... "; +static const char *PMEDLOG_STARTED = " Started Protegemed ! "; +static const char *PMEDLOG_WRONGCODE = " Oops... wrong code, a reset may be expected "; +static const char *PMEDLOG_RESET = " No reason given "; +static const char *PMEDLOG_DEFAULTS = " Loaded defaults in Settings ! "; + +static const char *PMEDLOG_RESETTELNET = " by telnet reset "; +static const char *PMEDLOG_UPDATETELNET = " by telnet update "; + +static const char *PMEDLOG_HTTP_CONNECT = "On HTTP_POST - Connect"; +static const char *PMEDLOG_HTTP_SEND = "On HTTP_POST - Send"; + +class PmedLog +{ + +protected: + + static int m_entry; + static time_t m_lastMark; + +public: + + PmedLog(); + + // Control the marks behavior in log file + static bool get_LogMarks() { return Settings::get_LogMarks(); } + static void set_LogMarks(bool value) { Settings::set_LogMarks(value); } + static int get_LogMarksInterval() { return Settings::get_LogMarksInterval(); } + static void set_LogMarksInterval(int value) { Settings::set_LogMarksInterval(value); } + + static void WriteEntry(const char *value); + static void Mark(); + +}; + +#endif //#ifndef PMEDLOGS_H +
diff -r 000000000000 -r fac116e94d44 Headers/Pmed_reset.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/Pmed_reset.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,40 @@ +/* + * Settings.h + * + * Created on: 19/jan/2015 + * Author: Marcos A. Lucas + */ + +#ifndef PMEDRESET_H +#define PMEDRESET_H + +#include "mbed.h" +#include "Settings.h" + +#include "PmedLog.h" + +extern "C" void mbed_reset(); + +static void Pmed_reset(); +static void Pmed_reset(const char* value); + + +static void Pmed_reset() +{ + Pmed_reset(PMEDLOG_RESET); +} + +static void Pmed_reset(const char* value) +{ + char entry[80]; + + entry[0] = '\0'; + strcat(entry, "RESET : "); + strcat(entry, value); + PmedLog::WriteEntry(entry); + wait(1); + mbed_reset(); +} + +#endif //#ifndef PMEDRESET_H +
diff -r 000000000000 -r fac116e94d44 Headers/Settings.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/Settings.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,224 @@ +/* + * 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 FREQBASE 60U +#define NUMBER_OF_CHANNELS 6U +#define NUMBER_OF_OUTLETS 3U +#define NUMBER_OF_HARMONICS 12U +#define NUMBER_OF_SAMPLES 128U +#define LENGTH_MAIL_BOX 10U +#define MAXTRIES 10U + +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; + + //read RFID + static int m_ReadRfid; + + //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; + + // Control the marks behavior in log file + static bool m_logMarks; + static int m_logMarksInterval; + +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_ReadRfid() { return m_ReadRfid; } + static void set_ReadRfid(int value) { m_ReadRfid = 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_Samples() { return m_Samples; } +// static void set_Samples(int value) { m_Samples = value; } + + static int get_MaxHarmonics() { return m_MaxHarmonics; } + static void set_MaxHarmonics(int value) { m_MaxHarmonics = 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) +// for(...) +// { +// 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; } + + // Control the marks behavior in log file + static bool get_LogMarks() { return m_logMarks; } + static void set_LogMarks(bool value) { m_logMarks = value; } + static int get_LogMarksInterval() { return m_logMarksInterval; } + static void set_LogMarksInterval(int value) { m_logMarksInterval = 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
diff -r 000000000000 -r fac116e94d44 Headers/SignalProcessor.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/SignalProcessor.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,33 @@ +/* + * 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(float* data, int sign, int ch); + static float ComplexFFTTeste(unsigned short int* data, float *vector, int sign, int ch); + +public: + + //static void CalculateRMSBulk(float *result); + static void CalculateRMSBulk(float *result, float *vm2, int *under, int *over); + static float CalculateRMS(int nChannel); + static float CalculateRMSFloat( float *buffer,int nChannel); + static void CalculateFFT(float *buffer,float *sen,float *cos,float *vm,int sign, int ch); + //static float DFT(float *data, float *seno, float *coss); + +}; + +#endif \ No newline at end of file
diff -r 000000000000 -r fac116e94d44 Headers/TelnetServer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/TelnetServer.h Tue Jan 05 11:47:35 2016 +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); + +};
diff -r 000000000000 -r fac116e94d44 Headers/TftpServer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/TftpServer.h Tue Jan 05 11:47:35 2016 +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
diff -r 000000000000 -r fac116e94d44 Headers/ntpc.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/ntpc.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,20 @@ +#include "mbed.h" +#include "rtos.h" + +#include "EthernetInterface.h" +#include "NTPClient.h" + +static NTPClient ntpClient; + +class ntpc +{ + +protected: + + static void ntpcDo(); + +public: + + static void ntpc_Thread(void const* arg); + +};
diff -r 000000000000 -r fac116e94d44 Headers/tftpsrv.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Headers/tftpsrv.h Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,47 @@ +#include "mbed.h" +#include "rtos.h" + +#include "EthernetInterface.h" + + + static UDPSocket server; + static Endpoint client; + + static int estado; + + static int blockcnt, dupcnt; // block counter, and DUP counter + static FILE* fp; // current file to read or write + static char sendbuff[516]; // current DATA block; + static int blocksize; // last DATA block size while sending + static char filename[256]; // current (or most recent) filename + +class tftpsrv +{ + +#define ESCUTANDO 0 +#define LENDO 1 +#define ESCREVENDO 2 +#define ERRO 3 + +protected: + + static void tftpInicia(); + static void tftpPara(); + static void tftpReinicia(); + static void tftpAck(int val); + static void tftpErr(char* msg); + static int tftpModo(char* buff); + static void tftpGetBlock(); + static void tftpSendBlock(); + static void tftpLer(char* buff); + static void tftpEscrever(char* buff); + static void tftpEscutando(char* buff); + static void tftpLendo(char *buff); + static void tftpEscrevendo(int tam, char *buff); + static void tftpVai(); + +public: + + static void tftpsrv_Thread(void const* arg); + +};
diff -r 000000000000 -r fac116e94d44 NTPClient.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/NTPClient.lib Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/donatien/code/NTPClient/#881559865a93
diff -r 000000000000 -r fac116e94d44 main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,184 @@ +/* + Projeto teste de Enviar dados coletados sem calcular a FFT. + Aquisição das amostras realizada sem DMA + +*/ + +#define MSGWINDOW "Version 4" + +#include <stdio.h> + +#include "mbed.h" +#include "rtos.h" +#include "cmsis_os.h" +#include "EthernetInterface.h" +#include "Settings.h" +#include "Capture.h" +#include "Http_post.h" +#include "SignalProcessor.h" +#include "EventDetector.h" +#include "limites.h" + +#include "TelnetServer.h" + +#include "tftpsrv.h" +#include "ntpc.h" + +#include "PmedLog.h" + +#include "NTPClient.h" + +#include "whatchdog.h" + +EthernetInterface eth; +Watchdog wdt; + +Semaphore tranca(1); + +void InitializeEthernetLink() +{ + if(Settings::get_Dhcp()) + //EthernetIf::Initialize(); //Use DHCP + eth.init(); //Use DHCP + else + //EthernetIf::Initialize(Settings::get_IpAddress(),Settings::get_Netmask(),Settings::get_Gateway()); + eth.init(Settings::get_IpAddress(),Settings::get_Netmask(),Settings::get_Gateway()); + + //EthernetIf::Connect(); + eth.connect(); + //printf("IP Address is %s\n", EthernetIf::get_IpAddress()); + printf("IP Address is NEW %s\n", eth.getIPAddress()); +} + +int main() { + float inicio, fim, maior, menor, dif; + float inicioc, fimc, maiorc, menorc, difc; + Timer t,tc; + + if ((LPC_WDT->WDMOD >> 2) & 1){ + //myled4 = 1; + PmedLog::WriteEntry(PMEDLOG_INITIALIZINGWDT); + } + else{ + //myled3 = 1; + PmedLog::WriteEntry(PMEDLOG_INITIALIZING); + } + + printf("\r\n %s \r\n", MSGWINDOW); + FILE *f; + + Settings::ReadFile(); + + InitializeEthernetLink(); + printf("Inicializou link Ethernet\n"); + + //Start HTTP POST service + Thread http_post(HttpPost::HttpPost_Thread); + + //Start Telnet Service + //Thread telnetserver(TelnetServer::TelnetServer_Thread); + + //Start TFTP Service + //Thread tftpsrv(tftpsrv::tftpsrv_Thread); + + //Start NTP Client for refresh time + //Thread ntpc(ntpc::ntpc_Thread); + time_t tempo = time(NULL); + if ((tempo+60) < 1420077600) set_time(1420077600); + + // ntpClient.setTime("192.168.103.101"); + + DisplayRAMBanks(); + + printf(PMEDLOG_INITIALIZINGWDT); + printf("\n\n"); + + PmedLog::WriteEntry(PMEDLOG_STARTED); + + /* start test WahtchDog */ + DigitalOut led1(LED1); + int i, n = 0; + //int tatual, tnovo; + float rms[NUMBER_OF_CHANNELS], mv2[NUMBER_OF_CHANNELS]; + int under[NUMBER_OF_CHANNELS], over[NUMBER_OF_CHANNELS]; + + wdt.kick(10.0); + + //Capture::Initialize(); + + while(1) + { + tranca.wait(); + t.start(); + inicio = t.read(); + + //get sample values from 6 channels + Capture::AcquireValues(); + + fim = t.read(); + dif = fim-inicio; + + if (n == 0) + maior = menor = dif; + + if (dif > maior) + maior = dif; + if (dif < menor) + menor = dif; + t.reset(); + t.stop(); + tranca.release(); + + tranca.wait(); + tc.start(); + inicioc = tc.read(); + // Calcula o RMS dos 6 canais + SignalProcessor::CalculateRMSBulk(rms, mv2, under, over); + fimc = tc.read(); + difc = fimc-inicioc; + + if (n == 0) + maiorc = menorc = difc; + + if (difc > maiorc) + maiorc = difc; + if (difc < menorc) + menorc = difc; + + for(i=0;i<6;i++){ + EventDetector::get_Detector(i).ProcessEvent(rms[i], mv2[i], under[i], over[i]); + } + + n++; + if(n % 60 == 0) + { + printf("%.2f %.0f %.2f %.0f\t%.2f %.0f %.2f %.0f\t%.2f %.0f %.2f %.0f\n",rms[0], mv2[0],rms[1],mv2[1],rms[2],mv2[2],rms[3],mv2[3],rms[4],mv2[4],rms[5],mv2[5]); + led1 = !led1; + // n=0; + + PmedLog::Mark(); + } + + if (n % 600 == 0){ + printf("Captura: Maior %f Menor %f\tCalculo Maior %f Menor %f\n", maior, menor, maiorc, menorc); + } + + // End of main loop so "kick" to reset watchdog timer and avoid a reset + wdt.kick(); + tc.reset(); + tc.stop(); + tranca.release(); + } + + while(1){//never reaches here + PmedLog::WriteEntry(PMEDLOG_WRONGCODE); + printf("Reset\n"); + f = fopen(FILENAMERESET, "a"); + if (f == NULL) + f = fopen(FILENAMERESET, "w"); + fprintf(f, "Laco Errado\n"); + fclose(f); + Thread::yield(); + } +} +
diff -r 000000000000 -r fac116e94d44 mbed-rtos.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos.lib Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/mbed_official/code/mbed-rtos/#c825593ece39
diff -r 000000000000 -r fac116e94d44 mbed.bld --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed.bld Tue Jan 05 11:47:35 2016 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/mbed_official/code/mbed/builds/4336505e4b1c \ No newline at end of file