ATT example code
Dependencies: WNCInterface mbed-rtos mbed
Revision 0:2bfa06d10e28, committed 2017-05-22
- Comitter:
- surajdagar
- Date:
- Mon May 22 19:50:26 2017 +0000
- Commit message:
- Wireless solution ATT kit
Changed in this revision
diff -r 000000000000 -r 2bfa06d10e28 HTS221.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HTS221.cpp Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,240 @@ +/* =================================================================== +Copyright © 2016, AVNET Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +either express or implied. See the License for the specific +language governing permissions and limitations under the License. + +======================================================================== */ + +#include "HTS221.h" + + +// ------------------------------------------------------------------------------ +//jmf -- define I2C pins and functions to read & write to I2C device + +#include <string> +#include "mbed.h" +#include "hardware.h" + +// Read a single unsigned char from addressToRead and return it as a unsigned char +unsigned char HTS221::readRegister(unsigned char slaveAddress, unsigned char ToRead) +{ + char data = ToRead; + + //i2c.write(slaveAddress, &data, 1, 0); + i2c.write(slaveAddress, &data, 1, 1); //by Stefan + i2c.read(slaveAddress, &data, 1, 0); + return data; +} + +// Writes a single unsigned char (dataToWrite) into regToWrite +int HTS221::writeRegister(unsigned char slaveAddress, unsigned char regToWrite, unsigned char dataToWrite) +{ + const char data[] = {regToWrite, dataToWrite}; + + return i2c.write(slaveAddress,data,2,0); +} + + +//jmf end +// ------------------------------------------------------------------------------ + +HTS221::HTS221(void) : _address(HTS221_ADDRESS) { + _temperature = 0; + _humidity = 0; +} + + +int HTS221::init(void) { + uint8_t data; + + data = readRegister(_address, WHO_AM_I); + if (data == WHO_AM_I_RETURN){ + if (activate()){ + storeCalibration(); + return data; + } + } + + return 0; +} + +int HTS221::storeCalibration(void) { + uint8_t data; + uint16_t tmp; + + for (int reg=CALIB_START; reg<=CALIB_END; reg++) { + if ((reg!=CALIB_START+8) && (reg!=CALIB_START+9) && (reg!=CALIB_START+4)) { + + data = readRegister(HTS221_ADDRESS, reg); + + switch (reg) { + case CALIB_START: + _h0_rH = data; + break; + case CALIB_START+1: + _h1_rH = data; + break; + case CALIB_START+2: + _T0_degC = data; + break; + case CALIB_START+3: + _T1_degC = data; + break; + + case CALIB_START+5: + tmp = _T0_degC; + _T0_degC = (data&0x3)<<8; + _T0_degC |= tmp; + + tmp = _T1_degC; + _T1_degC = ((data&0xC)>>2)<<8; + _T1_degC |= tmp; + break; + case CALIB_START+6: + _H0_T0 = data; + break; + case CALIB_START+7: + _H0_T0 |= data<<8; + break; + case CALIB_START+0xA: + _H1_T0 = data; + break; + case CALIB_START+0xB: + _H1_T0 |= data <<8; + break; + case CALIB_START+0xC: + _T0_OUT = data; + break; + case CALIB_START+0xD: + _T0_OUT |= data << 8; + break; + case CALIB_START+0xE: + _T1_OUT = data; + break; + case CALIB_START+0xF: + _T1_OUT |= data << 8; + break; + + + case CALIB_START+8: + case CALIB_START+9: + case CALIB_START+4: + //DO NOTHING + break; + + // to cover any possible error + default: + return false; + } /* switch */ + } /* if */ + } /* for */ + return true; +} + + +int HTS221::activate(void) { + uint8_t data; + + data = readRegister(_address, CTRL_REG1); + data |= POWER_UP; + data |= ODR0_SET; + writeRegister(_address, CTRL_REG1, data); + + return true; +} + + +int HTS221::deactivate(void) { + uint8_t data; + + data = readRegister(_address, CTRL_REG1); + data &= ~POWER_UP; + writeRegister(_address, CTRL_REG1, data); + return true; +} + + +int HTS221::bduActivate(void) { + uint8_t data; + + data = readRegister(_address, CTRL_REG1); + data |= BDU_SET; + writeRegister(_address, CTRL_REG1, data); + + return true; +} + + +int HTS221::bduDeactivate(void) { + uint8_t data; + + data = readRegister(_address, CTRL_REG1); + data &= ~BDU_SET; + writeRegister(_address, CTRL_REG1, data); + return true; +} + + +int HTS221::readHumidity(void) { + uint8_t data = 0; + uint16_t h_out = 0; + double h_temp = 0.0; + double hum = 0.0; + + data = readRegister(_address, STATUS_REG); + + if (data & HUMIDITY_READY) { + data = readRegister(_address, HUMIDITY_H_REG); + h_out = data << 8; // MSB + data = readRegister(_address, HUMIDITY_L_REG); + h_out |= data; // LSB + + // Decode Humidity + hum = ((int16_t)(_h1_rH) - (int16_t)(_h0_rH))/2.0; // remove x2 multiple + + // Calculate humidity in decimal of grade centigrades i.e. 15.0 = 150. + h_temp = (((int16_t)h_out - (int16_t)_H0_T0) * hum) / ((int16_t)_H1_T0 - (int16_t)_H0_T0); + hum = ((int16_t)_h0_rH) / 2.0; // remove x2 multiple + _humidity = (int16_t)((hum + h_temp)); // provide signed % measurement unit + } + return _humidity; +} + + + +double HTS221::readTemperature(void) { + uint8_t data = 0; + uint16_t t_out = 0; + double t_temp = 0.0; + double deg = 0.0; + + data = readRegister(_address, STATUS_REG); + + if (data & TEMPERATURE_READY) { + + data= readRegister(_address, TEMP_H_REG); + t_out = data << 8; // MSB + data = readRegister(_address, TEMP_L_REG); + t_out |= data; // LSB + + // Decode Temperature + deg = ((int16_t)(_T1_degC) - (int16_t)(_T0_degC))/8.0; // remove x8 multiple + + // Calculate Temperature in decimal of grade centigrades i.e. 15.0 = 150. + t_temp = (((int16_t)t_out - (int16_t)_T0_OUT) * deg) / ((int16_t)_T1_OUT - (int16_t)_T0_OUT); + deg = ((int16_t)_T0_degC) / 8.0; // remove x8 multiple + _temperature = deg + t_temp; // provide signed celsius measurement unit + } + + return _temperature; +}
diff -r 000000000000 -r 2bfa06d10e28 HTS221.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HTS221.h Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,108 @@ +/* =================================================================== +Copyright © 2016, AVNET Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +either express or implied. See the License for the specific +language governing permissions and limitations under the License. + +======================================================================== */ + +#ifndef HTS221_H_ +#define HTS221_H_ + +class HTS221 { +public: + HTS221(void); + int init(void); + int activate(void); + int deactivate(void); + + int bduActivate(void); + int bduDeactivate(void); + + int readHumidity(void); + double readTemperature(void); +private: + int storeCalibration(void); + unsigned char _h0_rH, _h1_rH; + unsigned int _T0_degC, _T1_degC; + unsigned int _H0_T0, _H1_T0; + unsigned int _T0_OUT, _T1_OUT; + double _temperature; + int _humidity; + unsigned char _address; + + unsigned char readRegister(unsigned char slaveAddress, unsigned char regToRead); + int writeRegister(unsigned char slaveAddress, unsigned char regToWrite, unsigned char dataToWrite); +}; + +#define HTS221_ADDRESS 0xBF + +//Define a few of the registers that we will be accessing on the HTS221 +#define WHO_AM_I 0x0F +#define WHO_AM_I_RETURN 0xBC //This read-only register contains the device identifier, set to BCh + +#define AVERAGE_REG 0x10 // To configure humidity/temperature average. +#define AVERAGE_DEFAULT 0x1B + +/* + * [7] PD: power down control + * (0: power-down mode; 1: active mode) + * + * [6:3] Reserved + * + * [2] BDU: block data update + * (0: continuous update; 1: output registers not updated until MSB and LSB reading) +The BDU bit is used to inhibit the output register update between the reading of the upper +and lower register parts. In default mode (BDU = ?0?), the lower and upper register parts are +updated continuously. If it is not certain whether the read will be faster than output data rate, +it is recommended to set the BDU bit to ?1?. In this way, after the reading of the lower (upper) +register part, the content of that output register is not updated until the upper (lower) part is +read also. + * + * [1:0] ODR1, ODR0: output data rate selection (see table 17) + */ +#define CTRL_REG1 0x20 +#define POWER_UP 0x80 +#define BDU_SET 0x4 +#define ODR0_SET 0x1 // setting sensor reading period 1Hz + +#define CTRL_REG2 0x21 +#define CTRL_REG3 0x22 +#define REG_DEFAULT 0x00 + +#define STATUS_REG 0x27 +#define TEMPERATURE_READY 0x1 +#define HUMIDITY_READY 0x2 + +#define HUMIDITY_L_REG 0x28 +#define HUMIDITY_H_REG 0x29 +#define TEMP_L_REG 0x2A +#define TEMP_H_REG 0x2B +/* + * calibration registry should be read for temperature and humidity calculation. + * Before the first calculation of temperature and humidity, + * the master reads out the calibration coefficients. + * will do at init phase + */ +#define CALIB_START 0x30 +#define CALIB_END 0x3F +/* +#define CALIB_T0_DEGC_X8 0x32 +#define CALIB_T1_DEGC_X8 0x33 +#define CALIB_T1_T0_MSB 0x35 +#define CALIB_T0_OUT_L 0x3C +#define CALIB_T0_OUT_H 0x3D +#define CALIB_T1_OUT_L 0x3E +#define CALIB_T1_OUT_H 0x3F + */ + +#endif
diff -r 000000000000 -r 2bfa06d10e28 MQTT-JMF.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/MQTT-JMF.lib Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,1 @@ +http://developer.mbed.org/users/JMF/code/MQTT-JMF/#21d6fba046df
diff -r 000000000000 -r 2bfa06d10e28 WNCInterface.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/WNCInterface.lib Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,1 @@ +http://developer.mbed.org/teams/Avnet/code/WNCInterface/#b278b745fb4f
diff -r 000000000000 -r 2bfa06d10e28 hardware.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/hardware.h Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,57 @@ +/* =================================================================== +Copyright © 2016, AVNET Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +either express or implied. See the License for the specific +language governing permissions and limitations under the License. + +======================================================================== */ + +#ifndef Hardware_H_ +#define Hardware_H_ +#include "MODSERIAL.h" + +extern I2C i2c; //SDA, SCL -- define the I2C pins being used +extern MODSERIAL pc; // tx, rx with default tx, rx buffer sizes + +// comment out the following line if color is not supported on the terminal +#define USE_COLOR +#ifdef USE_COLOR + #define BLK "\033[30m" + #define RED "\033[31m" + #define GRN "\033[32m" + #define YEL "\033[33m" + #define BLU "\033[34m" + #define MAG "\033[35m" + #define CYN "\033[36m" + #define WHT "\033[37m" + #define DEF "\033[39m" +#else + #define BLK + #define RED + #define GRN + #define YEL + #define BLU + #define MAG + #define CYN + #define WHT + #define DEF +#endif + +#define CTOF(x) ((x)*1.8+32) + +#ifdef _ULINK_PRINT +#include "itm_output.h" +#else +#define PRINTF printf +#define PUTS puts +#endif +#endif
diff -r 000000000000 -r 2bfa06d10e28 k64f.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/k64f.h Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,15 @@ +#ifndef K64F_H_ +#define K64F_H_ + +typedef enum color {off, red, green, blue} color_t; + +//Serial pc(USBTX, USBRX); +DigitalOut redLED(LED_RED); +DigitalOut greenLED(LED_GREEN); +DigitalOut blueLED(LED_BLUE); +InterruptIn switch2(SW2); +InterruptIn switch3(SW3); + +#endif // K64F.H + +
diff -r 000000000000 -r 2bfa06d10e28 main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,312 @@ +#include "mbed.h" +#include "MQTTClient.h" +#include "MQTTFormat.h" +#include "MQTTWNCInterface.h" +#include "rtos.h" +#include "k64f.h" +#include "HTS221.h" +#include "MODSERIAL.h" + +I2C i2c(PTC11, PTC10); //SDA, SCL -- define the I2C pins being used +MODSERIAL pc(USBTX, USBRX); +MODSERIAL pump(PTC15, PTC14);//TX, RX to connect pump + +#include "hardware.h" +/* +#define ORG_ID "44a8w4" +#define DEVICE_TYPE "IoT-Moog-1" +#define DEVICE_NAME "IoT-Moog-Device1" +#define USERNAME "use-token-auth" +#define PASSWORD "ih*SKz2AyUSt+I*L0N" +*/ + +#define ORG_ID "hpy42p" +#define DEVICE_TYPE "PumpTest" +#define DEVICE_NAME "SomethingOtherThanPumpTest" +#define USERNAME "use-token-auth" +#define PASSWORD "SLD21utaPZP7TE8Vgk" + +#define URL ORG_ID ".messaging.internetofthings.ibmcloud.com" +#define CLIENTSTR "d:" ORG_ID ":" DEVICE_TYPE ":%s" + +#define PORT 1883 // MQTT broker port number +#define PUBLISH_TOPIC "iot-2/evt/status/fmt/json" // MQTT topic +#define SUBSCRIBTOPIC "iot-2/cmd/+/fmt/+" +/// Largest msg possible is 111 bytes - header, 99 data bytes, CheckSum, LF/CR +#define PDMS_MAX_COMMAND_SIZE 111 +Thread serial_thread; +volatile int key_reader =0; +volatile int old_Key =0; +char command_str[PDMS_MAX_COMMAND_SIZE]; +unsigned char AIL_Enable=0; +Queue<uint32_t, 6> messageQ; + +// LED color control function +void controlLED(color_t led_color) { + switch(led_color) { + case red : + greenLED = blueLED = 1; + redLED = 0.7; + break; + case green : + redLED = blueLED = 1; + greenLED = 0.7; + break; + case blue : + redLED = greenLED = 1; + blueLED = 0.7; + break; + case off : + redLED = greenLED = blueLED = 1; + break; + } +} + +// Switch 2 interrupt handler +void sw2_ISR(void) { + messageQ.put((uint32_t*)22); +} + +// Switch3 interrupt handler +void sw3_ISR(void) { + messageQ.put((uint32_t*)33); +} + +// MQTT message arrived callback function +void messageArrived(MQTT::MessageData& md) { + MQTT::Message &message = md.message; + PRINTF("Receiving MQTT message: %.*s\r\n", message.payloadlen, (char*)message.payload); + + if (message.payloadlen == 3) { + if (strncmp((char*)message.payload, "red", 3) == 0) + controlLED(red); + + else if(strncmp((char*)message.payload, "grn", 3) == 0) + controlLED(green); + + else if(strncmp((char*)message.payload, "blu", 3) == 0) + controlLED(blue); + + else if(strncmp((char*)message.payload, "off", 3) == 0) + controlLED(off); + } +} + +void alla_serial() +{ + printf("Enter Thread alla_serial"); + while(1) + { + memset(command_str, 0x00,PDMS_MAX_COMMAND_SIZE); + pump.gets(command_str, PDMS_MAX_COMMAND_SIZE); + printf("%s", command_str); //print data received from Pump + if(strstr(command_str, "Standby")) + { + key_reader=8; + } + else if(strstr(command_str, "Paused")) + { + if(AIL_Enable == 0) + key_reader=1; + else + AIL_Enable--; + } + else if(strstr(command_str, "AIR IN LINE")) + { + key_reader=2; + AIL_Enable=2; + } + else if(strstr(command_str, "Run Interval")) + { + key_reader=3; + } + else if(strstr(command_str, "Run Continous")) + { + key_reader=4; + } + else if(strstr(command_str, "DOOR OPEN")) + { + key_reader=5; + AIL_Enable=2; + } + else if(strstr(command_str, "Priming")) + { + key_reader=6; + } + else if(strstr(command_str, "PUMP WAITING")) + { + key_reader=7; + } + else if(strstr(command_str, "Cleared")) + { + key_reader=9; + } + else + { + printf("\n %s", command_str); + } + } +} +int main() { +////////////////////////////////////////////////////// + pump.baud(115200); + // pump.format(8, SerialBase::Even, 1); + serial_thread.start(&alla_serial); +////////////////////////////////////////////////////// + + int rc, pSW2=0, txSel=0, good = 0; + Timer tmr; + char* topic = PUBLISH_TOPIC; + char clientID[100], buf[100]; + string st, uniqueID; + + HTS221 hts221; + + pc.baud(115200); + rc = hts221.init(); + if ( rc ) { + PRINTF(BLU "HTS221 Detected (0x%02X)\n\r",rc); + PRINTF(" Temp is: %0.2f F \r\n Huumid is: %02d %%\r\n\r\n", + CTOF(hts221.readTemperature()), hts221.readHumidity()/10); + } + else { + PRINTF(RED "HTS221 NOT DETECTED!\n\r"); + } + + controlLED(green); + + // set SW2 and SW3 to generate interrupt on falling edge + switch2.fall(&sw2_ISR); + switch3.fall(&sw3_ISR); + + // initialize ethernet interface + MQTTwnc ipstack = MQTTwnc(); + + // get and display client network info + WNCInterface& eth = ipstack.getEth(); + + // construct the MQTT client + MQTT::Client<MQTTwnc, Countdown> client = MQTT::Client<MQTTwnc, Countdown>(ipstack); + + controlLED(blue); + + char* hostname = URL; + int port = PORT; + // uniqueID = "IoT-Moog-Device1"; //Guru Device + uniqueID = "SomethingOtherThanPumpTest"; // Suraj Device + sprintf(clientID, CLIENTSTR, uniqueID.c_str()); + + PRINTF("Local network info...\r\n"); + PRINTF("IP address is %s\r\n", eth.getIPAddress()); + PRINTF("MAC address is %s\r\n", eth.getMACAddress()); + PRINTF("Gateway address is %s\r\n", eth.getGateway()); + PRINTF("Your <uniqueID> is: %s\r\n", uniqueID.c_str()); + PRINTF("---------------------------------------------------------------\r\n"); + + MQTTPacket_connectData data = MQTTPacket_connectData_initializer; + + int tries; + + while( !good ) { + + tries=0; + // connect to TCP socket and check return code + tmr.start(); + rc = 1; + while( rc && tries < 3) { + PRINTF("\r\n\r\n(%d) Attempting TCP connect to %s:%d: ", tries++, hostname, port); + rc = ipstack.connect(hostname, port); + if( rc ) { + PRINTF("Failed (%d)!\r\n",rc); + while( tmr.read_ms() < 5000 ) ; + tmr.reset(); + } + else { + PRINTF("Success!\r\n"); + rc = 0; + } + } + if( tries < 3 ) + tries = 0; + else + continue; + + data.willFlag = 0; + data.MQTTVersion = 3; + + data.clientID.cstring = clientID; + data.username.cstring = USERNAME; + data.password.cstring = PASSWORD; + data.keepAliveInterval = 10; + data.cleansession = 1; + + rc = 1; + tmr.reset(); + while( !client.isConnected() && rc && tries < 3) { + PRINTF("(%d) Attempting MQTT connect to '%s': ", tries++, clientID); + rc = client.connect(data); + if( rc ) { + PRINTF("Failed (%d)!\r\n",rc); + while( tmr.read_ms() < 5000 ); + tmr.reset(); + } + else + PRINTF("Success!\r\n"); + } + + if( tries < 3 ) + tries = 0; + else + continue; + + // subscribe to MQTT topic + tmr.reset(); + rc = 1; + while( rc && client.isConnected() && tries < 3) { + PRINTF("(%d) Attempting to subscribing to MQTT topic '%s': ", tries, SUBSCRIBTOPIC); + rc = client.subscribe(SUBSCRIBTOPIC, MQTT::QOS0, messageArrived); + if( rc ) { + PRINTF("Failed (%d)!\r\n", rc); + while( tmr.read_ms() < 5000 ); + tries++; + tmr.reset(); + } + else { + good=1; + PRINTF("Subscribe successful!\r\n"); + } + } + while (!good); + } + + MQTT::Message message; + message.qos = MQTT::QOS0; + message.retained = false; + message.dup = false; + message.payload = (void*)buf; + + while(true) + { + osEvent switchEvent = messageQ.get(100); + if(key_reader != old_Key) + { + old_Key = key_reader; + memset(buf,0x00,sizeof(buf)); + //sprintf(buf, "{\"d\" : {\"Key\" : %d }}", key_reader); + sprintf(buf, "{\"Key\":\"%d\"}", key_reader); + PRINTF("Publishing MQTT message '%s' ", (char*)message.payload); + message.payloadlen = strlen(buf); + PRINTF("\n payloadlen:(%d)\r\n",message.payloadlen); + rc = client.publish(topic, message); + if( rc ) + { + PRINTF("Publish request failed! (%d)\r\n",rc); + FATAL_WNC_ERROR(resume); + } + } + else + { + client.yield(1000); + } + } +}
diff -r 000000000000 -r 2bfa06d10e28 mbed-rtos.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos.lib Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,1 @@ +http://mbed.org/users/mbed_official/code/mbed-rtos/#58563e6cba1e
diff -r 000000000000 -r 2bfa06d10e28 mbed.bld --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed.bld Mon May 22 19:50:26 2017 +0000 @@ -0,0 +1,1 @@ +https://mbed.org/users/mbed_official/code/mbed/builds/794e51388b66 \ No newline at end of file