How can I get the value of pin A0 from the second sketch into the JSON array in the first sketch? - json

Can anyone help me figure out how to piece these two pieces of code together so I get the result I need? My eyes are crossing from looking at this. I know this is a breeze for probably everyone other than myself, but I am not a programmer and this is just for one small personal project.
So far, after hours and hours of reading and watching any videos I could find relating to Arduino, Pubnub and sensors, I have sensor reading publishing to Pubnub. I created a Freeboard account for visualization and that's all working. The problem is, the data being published is wrong.
Basically, I'm wanting to read a battery voltage and publish it to PubNub. I can get the Arduino (Uno R3) to read the voltage and I can adjust the values in the code to match the actual voltage. The problem I run into is taking that bit of code that works and stuffing it into the JSON array that gets published to PubNub.
If anyone would be willing to help me and maybe explain a little (or not - I'm okay if I just get it working), I would SO appreciate the time, help and effort.
Thanks!
//Each sketch works indepently. I need to merge them to get the correct reading published.
//VoltagePubNub.ino
(This is the one that publishes, which is what I want. I just want the published value to be the value of the second sketch.)
#include <SPI.h>
#include <Ethernet.h>
#include <PubNub.h>
#include <aJSON.h>
// Some Ethernet shields have a MAC address printed on a sticker on the shield;
// fill in that address here, or choose your own at random:
const static byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Memory saving tip: remove myI and dnsI from your sketch if you
// are content to rely on DHCP autoconfiguration.
IPAddress myI(192, 168, 2, 114);
IPAddress dnsI(8, 8, 8, 8);
const static char pubkey[] = "publish_key";
const static char subkey[] = "subscribe_key";
const static char channel[] = "channel_name";
char uuid[] = "UUID";
#define NUM_CHANNELS 1 // How many analog channels do you want to read?
const static uint8_t analog_pins[] = {A0}; // which pins are you reading?
void setup()
{
Serial.begin(9600);
Serial.println("Serial set up");
Ethernet.begin((byte*) mac, myI, dnsI);
Serial.println("Ethernet set up");
delay(1000);
Serial.println("Ethernet set up");
PubNub.begin(pubkey, subkey);
Serial.println("PubNub set up");
delay(5000);
}
void loop()
{
Ethernet.maintain();
EthernetClient *client;
// create JSON objects
aJsonObject *msg, *analogReadings;
msg = aJson.createObject();
aJson.addItemToObject(msg, "analogReadings", analogReadings = aJson.createObject());
// get latest sensor values then add to JSON message
for (int i = 0; i < NUM_CHANNELS; i++) {
String analogChannel = String(analog_pins[i]);
char charBuf[analogChannel.length()+1];
analogChannel.toCharArray(charBuf, analogChannel.length()+1);
int analogValues = analogRead(analog_pins[i]);
aJson.addNumberToObject(analogReadings, charBuf, analogValues);
}
// convert JSON object into char array, then delete JSON object
char *json_String = aJson.print(msg);
aJson.deleteItem(msg);
// publish JSON formatted char array to PubNub
Serial.print("publishing a message: ");
Serial.println(json_String);
client = PubNub.publish(channel, json_String);
if (!client) {
Serial.println("publishing error");
} else
free(json_String);
client->stop();
delay(5000);
}
//VoltageSensor.ino
(This is the one with the correct value, but no publish feature.)
int analogInput = A0;
float vout = 0.0;
float vin = 0.0;
float R1 = 31000.0; //
float R2 = 8700.0; //
int value = 0;
int volt = 0;
void setup(){
pinMode(analogInput, INPUT);
Serial.begin(9600);
Serial.print("DC VOLTMETER");
Serial.println("");
}
void loop(){
// read the value at analog input
value = analogRead(analogInput);
vout = (value * 4.092) / 1024.0;
vin = vout / (R2/(R1+R2));
Serial.print("INPUT V= ");
Serial.println(vin,2);
delay(2000);
}

It may not be the most glamorous or the proper way of doing it, but I got this to do what I need. I edited the first sketch with the following code:
// create JSON objects
aJsonObject *msg, *analogReadings;
msg = aJson.createObject();
aJson.addItemToObject(msg, "analogReadings", analogReadings = aJson.createObject());
// get latest sensor values then add to JSON message
for (int i = 0; i < NUM_CHANNELS; i++) {
float vout = 0.0;
float vin = 0.0;
float R1 = 33060.0; //
float R2 = 7600.0; //
int value = 0;
int volt = 0;
//Serial.print("INPUT V= ");
//Serial.println(vin,2);
String analogChannel = String(analog_pins[i]);
value = analogRead(analog_pins[i]);
vout = (value * 4.092) / 1024.0;
vin = vout / (R2/(R1+R2));
char charBuf[analogChannel.length()+1];
analogChannel.toCharArray(charBuf, analogChannel.length()+1);
float theVoltage = (vin);
int analogValues = analogRead(analog_pins[i]);
aJson.addNumberToObject(analogReadings, charBuf, theVoltage);
}
// convert JSON object into char array, then delete JSON object
char *json_String = aJson.print(msg);
aJson.deleteItem(msg);
Now the value is published to PubNub and is graphed on Freeboard.io at this link .

Related

Autokey Encryption

I am working on a project to write to and read from a TP Link / Kaza power strip or smart plug.
The data that is sent is encrypted json that has been "autokey encrypted".
So far I have been able to convert a typescript encrypt function and it works well. I get the expected result. However, I need to add a "header" to my encrypted data. That data is 3 null bytes followed by a byte that is a measure of the length of the encrypted bytes.
The typescript example has this bit of code to "encrypt with headers", however, I've hit a bit of a wall trying to convert it to something usable. Can someone nudge me along the path ?
First are the two typescript functions: (borrowed from https://github.com/plasticrake/tplink-smarthome-crypto/blob/master/src/index.ts)
/**
* Encrypts input where each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer
*/
export function encrypt(input: Buffer | string, firstKey = 0xab): Buffer {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i += 1) {
// eslint-disable-next-line no-bitwise
buf[i] ^= key;
key = buf[i];
}
return buf;
}
/**
* Encrypts input that has a 4 byte big-endian length header;
* each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer with header
*/
export function encryptWithHeader(
input: Buffer | string,
firstKey = 0xab
): Buffer {
const msgBuf = encrypt(input, firstKey);
const outBuf = Buffer.alloc(msgBuf.length + 4);
outBuf.writeUInt32BE(msgBuf.length, 0);
msgBuf.copy(outBuf, 4);
return outBuf;
}
Second is what I have so far.
// This part works well and produces the expected results
String encrypt(String input)
{
int16_t firstKey = 0xab;
String buf;
int key;
int i;
buf = input;
key = firstKey;
i = 0;
for (;i < buf.length();(i = i + 1))
{
buf[i] ^= key;
key = buf[i];
}
return buf;
}
// This does not function yet, as I'm pretty lost..
// This was orginally converted from typescript with https://andrei-markeev.github.io/ts2c/
// I started work on converting this, but ran into errors I don't know how to solve.
String encryptWithHeader(String input){
String msgBuf;
String outBuf;
int16_t firstKey = 0xab;
char * null = NULL;
msgBuf = encrypt(input);
outBuf = msgBuf.length() +1;
//this is where I got lost...
assert(null != NULL);
null[0] = '\0';
strncat(null, outBuf, msgBuf.length());
str_int16_t_cat(null, 4);
outBuf = msgBuf + 4
return outBuf;
}
Finally, the data:
//this is the unencrypted json
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
//current encrypt function produces:
d0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
//the working "withheaders" should produce:
00002ad0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
Admittedly my C/C++ ability is very limited and I can spell typescript, that's about all. I have a very extensive history with PHP. As useful as that is. So, I understand the basics of data structures and whatnot, but I'm venturing off into areas I've never been in. Any help would be greatly appreciated.
It looks like the encryption is fairly simple: write the current character XORed with the key to the buffer and make that newly written character the new key. It also looks like the "withHeaders" version adds the length of the encrypted string as a 4 byte integer to the start of the buffer. I think it might be easier to allocate a character array and pass that array to a function that writes the result to that buffer. For example:
void encryptWithHeader(byte buffer[], int bufferLength, byte key, String message) {
int i;
uint32_t messageLength = message.length();
Serial.println(message);
Serial.println(message.length());
// check that we won't overrun the buffer
if ( messageLength + 5 < bufferLength) {
buffer[0] = messageLength >> 24 & 0xFF;
buffer[1] = messageLength >> 16 & 0xFF;
buffer[2] = messageLength >> 8 & 0xFF;
buffer[3] = messageLength & 0xFF;
for (i = 0; i < messageLength; i++) {
buffer[i + 4] = message[i] ^ key;
key = buffer[i + 4];
}
}
else { // we would have overrun the buffer
Serial.println("not enough room in buffer for message");
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
byte theBuffer[64];
int i;
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
encryptWithHeader(theBuffer, 64, 0xab, offMsg);
// now print it out to check
for (i = 0; i < offMsg.length() + 4; i++) {
if (theBuffer[i] < 0x10) // adds an extra zero if a byte prints as on1y 1 char
Serial.print("0");
Serial.print(theBuffer[i], HEX);
}
while (true)
;
}
If you want to send the character buffer to a remote device you can send it out one byte at a time:
for (i = 0; i < offMsg.length() + 4; i++)
Serial.write(theBuffer[i]);

Why is for loop only out putting first and last entries

This is what is being asked to do...
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.
This is the code I have. It compiles and runs, but only outputs the first and last entries of the unique list. Any input greatly appreciated! Thanks in advance.
import java.util.Scanner;
public class DuplicateElimination{
// sets helper functions
public static boolean isIn(int x, int[]y)
{
boolean isIn = false;// sets boolean to false
for (int i=0; i<y.length; i++)// sets for loop to run for length of array
{
if(y[i]==x)
{
isIn = true;
}
}
return isIn;
}
public static int[] append(int x, int[] y)// going to change what has already been set. creates integer array
{
int len = y.length +1;// sets length
int[] a = new int[len];// initializes new array
for (int i=0; i<y.length; i++); // goes through length of y
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
}
public static void main(String[] args)// sets main
{
Scanner input = new Scanner (System.in);// sets scanner to read input info
int[]uniqueList = new int[1];
uniqueList[0] = 0;// sets unique list to 0
System.out.print("Enter an integer between 10 and 100:");// prompts input from user
int entered = input.nextInt();// inputs value from user
System.out.printf("This is the first time %d has been entered\n", entered);// adds first entered # to unique list
uniqueList[0] = entered;// adds entered value to unique list
for (int i=0; i<4; i++)// sets loop to find unique values
{
System.out.print("Enter an integer between 10 and 100:");// prompts use
entered = input.nextInt();// inputs value
if(isIn (entered, uniqueList) == false)// calls is in function
{
System.out.printf("This is the first time %d has been entered\n", entered);
uniqueList = append(entered, uniqueList);// puts entered values in unique values on list
}
}
System.out.println("The complete list of unique values entered is:");
for(int i =0; i< uniqueList.length; i++)// runs through list to check for unique #s
{
System.out.printf("Unique value %d: is %d\n", i + 1, uniqueList[i]);// outputs list
}
}// ends main
}// ends class
in the append part change your for loop to:
for (int i=0;i<y.length;i++)
a[i]=y[i];
it didn't work because of for (int i=0; i<y.length; i++); the semi-colon is hijacking your loop as for why the result is as it is, your
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
part is just copying the first element of y into a and then copying the new element in the last cel of a
import java.util.*;
class Example{
public static void main(String args[]){
int[] xr = new int[5];
Scanner input = new Scanner (System.in);
System.out.println("Input five different integers between 10 and 100 below");
L1: for (int i = 0; i < xr.length; i++){
System.out.print("\tInput number "+(i+1)+" : ");
xr[i] = input.nextInt();
for(;xr[i]<=10 || xr[i]>=100;){
i--;
System.out.println("\t Error : You entered number is not between 10 and 100.");
continue L1;
}
for (int x = 0; x < i; x++){
if(xr[x] == xr[i]){
i--;
System.out.println("\tError : You cannot use duplicate numbers.");
continue L1;
}
}
}
System.out.println(Arrays.toString(xr));
}
}

how to return a structure (defined in .h file) from a function in another cpp file?

I ran into this issue and I cannot handle it. Any suggestion is appreciated.
I have a structure defined in a header file as follows:
Results.h
#ifndef RESULTS_H
#define RESULTS_H
struct Results
{
double dOptSizeMWh;
double dOrigSOCFinal;
double dManiSOCFinal;
};
#endif
and a general definition of "Deterministic" function in Deterministic.h:
#ifndef DETERMINISTIC_H
#define DETERMINISTIC_H
Results Deterministic(int,int,int,double,double); //Deterministic(int nNoMonth, int nNOWind, int nWindLength, double dPreviousSizeMWh, double dPreviousSOC)
#endif;
This function is implemented in Deterministic.cpp:
#include "Results.h"
Results Deterministic(int nNoMonth, int nNOWind, int nWindLength, double dPreviousSizeMWh, double dPreviousSOC)
{
// returns number of rows and columns of the array created
struct Results sRes;
sRes.dOptSizeMWh = -1.0; // for the optimal size of battery in MWh
sRes.dOrigSOCFinal = -1.0; // for the SOC at the end of the window
sRes.dManiSOCFinal = -1.0; // this is set to 0.0 if final SOC is slightly below 0
//...........................////
// OTHER Calculation .......////
//...........................////
return sRes;
}
Finally, I have a main file which I call Deterministic function and I use Results structure, main.cpp:
#include <Results.h>
#include <Deterministic.h>
using namespace std;
int main ()
{
int nNoMonth = 1; // the month that we want to use in the input
int nWindLength = 1; // length of window, hour
int nNODays = 1; // number of days that we want to repeat optimization
struct Results dValues;
double **mRes = new double*[nNODays * 24 / nWindLength];
for (int i = 0; i < nNODays * 24 / nWindLength; ++i) mRes[i] = new double[3];
for (int i = 0; i < nNODays * 24 / nWindLength; i++)
{
if (i == 0)
{
dValues = Deterministic(nNoMonth, i, nWindLength, 0.0, 0.0);
}else
{
temp0 = *(*(mRes+i-1)); double temp1 = *(*(mRes+i-1)+1); double temp2 = *(*(mRes+i-1)+2);
if (temp2 == -1.0) {dValues = Deterministic(nNoMonth, i, nWindLength, temp0, temp1);}
else {dValues = Deterministic(nNoMonth, i, nWindLength, *(*(mRes+i-1)), *(*(mRes+i-1)));}
}
*(*(mRes+i)) = dValues.dOptSizeMWh;
*(*(mRes+i)+1) = dValues.dOrigSOCFinal;
*(*(mRes+i)+2) = dValues.dManiSOCFinal;
}
these are only a small portion of the codes in Deterministic.cpp and main.cpp which defines the problem. First loop goes well (i.e., i=0) without any problem, but it fails in the second loop and beyond with this error: "R6010 - abort() has been called"
This error comes up in the main.cpp where I call Deterministic function in the if statement.
I have no problem compiling and running the posted code (other than the missing double in front of the declaration of temp). Without knowing what Deterministic() is actually doing, it's a bit hard to guess what the problem is (divide by zero? playing a Justin Bieber mp3?). It shouldn't have anything to do with returning a structure from a function defined in another file (translation units are a fundamental feature of the language). To find the root cause, single-step through the (complete) Deterministic() using your debugger.

Fetch MySQL row result to dynamic array

When a retrieve info from my db fetch_row(result)
I want to select from these results and store them in a dynamic array
row[i] will be the info a need
I'll need to store it to tagid[trigger]
but char* can be stored to char
so what i now is tagid[trigger] = *row[i];
but when i check the results... it aint what i want
the number 358713020035990 needs to be in tagid...
row[i] 0x05df2090 "358713020035990" char *
tagid[i] -112 '' char
how do i get this right?
char *tagid;int trigger;
tagid = (char *) malloc(sizeof(char));
result = mysql_store_result(conn); // only one column of integers
num_rows = mysql_num_rows(result);
while (row = mysql_fetch_row(result))
{tagid[trigger] = *row[i];}
If you are trying to copy a string data buffer, and not just the pointer to that buffer, then you are going to have to use a memory copy operation or preferably a standard library function made for such purposes like strcpy, or strncpy. So assuming that tagid[trigger] is referring to a block of memory that is an array of type char, you could do the following:
#include <string.h>
//tagid is a two-dimensional array of chars of ROWSIZE x COLUMNSIZE
char** tagid;
tagid = malloc(sizeof(char*) * COLUMNSIZE);
for (int i=0; i < COLUMNSIZE; i++)
{
tagid[i] = malloc(sizeof(char) * ROWSIZE);
}
//copy some data into your array at row index "trigger"
int trigger = SOMEVALUE;
strncpy(tagid[trigger], row[i], ROWSIZE);
//free the memory you've allocated for your two dimensional array
for (int i=0; i < COLUMNSIZE; i++)
{
free(tagid[i]);
}
free(tagid);
The value of ROWSIZE will have to be big enough to hold your largest string plus a terminating NULL otherwise the copy will be truncated using strncpy, or the data will overflow the array bounds and will write-over something else you don't want it to if you use strcpy.

Rating the quality of string matches

What would be the best way to compare a pattern with a set of strings, one by one, while rating the amount with which the pattern matches each string? In my limited experience with regex, matching strings with patterns using regex seems to be a pretty binary operation...no matter how complicated the pattern is, in the end, it either matches or it doesn't. I am looking for greater capabilities, beyond just matching. Is there a good technique or algorithm that relates to this?
Here's an example:
Lets say I have a pattern foo bar and I want to find the string that most closely matches it out of the following strings:
foo for
foo bax
foo buo
fxx bar
Now, none of these actually match the pattern, but which non-match is the closest to being a match? In this case, foo bax would be the best choice, since it matches 6 out of the 7 characters.
Apologies if this is a duplicate question, I didn't really know what exactly to search for when I looked to see if this question already exists.
This one works, I checked with Wikipedia example distance between "kitten" and "sitting" is 3
public class LevenshteinDistance {
public static final String TEST_STRING = "foo bar";
public static void main(String ...args){
LevenshteinDistance test = new LevenshteinDistance();
List<String> testList = new ArrayList<String>();
testList.add("foo for");
testList.add("foo bax");
testList.add("foo buo");
testList.add("fxx bar");
for (String string : testList) {
System.out.println("Levenshtein Distance for " + string + " is " + test.getLevenshteinDistance(TEST_STRING, string));
}
}
public int getLevenshteinDistance (String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
}
That's an interesting question! The first thing that came to mind is that the way regular expressions are matched is by building a DFA. If you had direct access to the DFA that was built for a given regex (or just built it yourself!) you could run the input measure the distance from the last state you transitioned to and an accept state, using a shortest path as a measure of how close it was to being accepted, but I'm not aware of any libraries that would let you do that easily and even this measure probably wouldn't exactly map onto your intuition in a number of cases.