Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Can We send data from arduino that using ethernet or wifi shield to RAILS server using API? If it possibly to be done, can you tell me which library and how to use it?
Yes, you can make calls to RESTful APIs from Arduino through ethernet or wifi shields. I prefer using standard libraries such as Ethernet / Ethernet 2.
Here is a sample (ethernet) implementation for your reference:
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetUdp2.h>
#include <util.h>
IPAddress _ip(192, 168, 1, 12); // Client (Arduino) IP address
byte _mac[] = {0x90, 0xA2, 0xDA, 0x11, 0x3C, 0x69}; // Arduino mac address
char _server[] = "192.168.1.10"; // Server IP address
int _port = 9200; // Server port number
EthernetClient _client;
void setup() {
Ethernet.begin(_mac, _ip);
delay(1000);
Serial.print("Local IP: ");
Serial.println(Ethernet.localIP());
if (_client.connect(_server, _port)) {
Serial.println("SUCCESS: Connected to the server!");
} else {
Serial.println("ERROR: Connection failed to the server!");
return;
}
delay(1000);
}
void loop() {
// JSON formatted data package including sample
// 'temperature', 'humidity', and 'timestamp' values
String data = "{\"temperature\": " + String(temperature) + ", " +
"\"humidity\": " + String(humidity) + ", " +
"\"timestamp\": " + String(timestamp) + "}";
String url = "/my-api/savedata"; // API url hosted on the server
// Finally, make an API call: POST request
_client.print("POST " + url + " HTTP/1.1 \r\n" +
"Content-Type: application/json \r\n" +
"Content-Length: " + data.length() + " \r\n" +
"\r\n" + data);
delay(500); // Give the network some time
// Read all the lines of the reply from server and
// print them to Serial to validate your API call
while (_client.available()) {
String reply = _client.readStringUntil('\r');
Serial.print(reply);
}
Serial.println();
}
Related
I am aiming to make a post request to trigger a IFTTT webhook action. I am using the MKR1010 board. I am able to connect to the network and turn the connected LED on and off using the cloud integration.
The code is as follows, but doesn't trigger the web hook. I can manually paste the web address in a browser and this does trigger the web hook. When the code is posted it returns a 400 bad request error.
The key has been replaced in the below code with a dummy value.
Does anybody know why this is not triggering the web hook? / Can you explain why the post request is being rejected by the server? I don't even really need to read the response from the server as long as it is sent.
Thank you
// ArduinoHttpClient - Version: Latest
#include <ArduinoHttpClient.h>
#include "thingProperties.h"
#define LED_PIN 13
#define BTN1 6
char serverAddress[] = "maker.ifttt.com"; // server address
int port = 443;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
// variables will change:
int btnState = 0; // variable for reading the pushbutton status
int btnPrevState = 0;
void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
// Defined in thingProperties.h
initProperties();
// Connect to Arduino IoT Cloud
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
/*
The following function allows you to obtain more information
related to the state of network and IoT Cloud connection and errors
the higher number the more granular information you’ll get.
The default is 0 (only errors).
Maximum is 4
*/
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
// setup the board devices
pinMode(LED_PIN, OUTPUT);
pinMode(BTN1, INPUT);
}
void loop() {
ArduinoCloud.update();
// Your code here
// read the state of the pushbutton value:
btnState = digitalRead(BTN1);
if (btnPrevState == 0 && btnState == 1) {
led2 = !led2;
postrequest();
}
digitalWrite(LED_PIN, led2);
btnPrevState = btnState;
}
void onLed1Change() {
// Do something
digitalWrite(LED_PIN, led1);
//Serial.print("The light is ");
if (led1) {
Serial.println("The light is ON");
} else {
// Serial.println("OFF");
}
}
void onLed2Change() {
// Do something
digitalWrite(LED_PIN, led2);
}
void postrequest() {
// String("POST /trigger/btn1press/with/key/mykeyhere")
Serial.println("making POST request");
String contentType = "/trigger/btn1press/with/key";
String postData = "mykeyhere";
client.post("/", contentType, postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}
Why do you want to make a POST request and send the key in the POST body? The browser sends a GET request. It would be
client.get("/trigger/btn1press/with/key/mykeyhere");
In HttpClient post() the first parameter is 'path', the second parameter is contentType (for example "text/plain") and the third parameter is the body of the HTTP POST request.
So your post should look like
client.post("/trigger/btn1press/with/key/mykeyhere", contentType, postData);
I'd like to update attributes from the device using Thingsboard IoT Gateway, but it will not work.
Thingsboard 1.4.0
Thingsboard IoT Gateway 1.2
Mosqquito(Broker)
Node.js(Client)
It all starts up and calls the attribute update API of the device, but the Gateway log does not appear and it does not seem to have arrived.
Client ->(OK) Mosqquito ->(??? no log) Gateway -> Thingsboard
mqtt-config.json uses this as it is.
https://github.com/thingsboard/thingsboard-gateway/blob/master/src/main/resources/mqtt-config.json
teremetoryAPI is working (value has been updated as seen in Console)
Please tell me what settings should be made to update the attributes of the device.
var mqtt = require('mqtt');
var os = require("os");
require('date-utils');
var device = 'T-001';
const thingsboardHost = "mqtt://127.0.0.1:1883";
console.log('Connecting to: %s', thingsboardHost);
var client = mqtt.connect(thingsboardHost, {
will: {topic: device + '/disconnect', payload: '', qos: 1}
});
var appState;
client.on('connect', function () {
publish(device + '/connect', "");
console.log('Client connected!');
// teremetory OK
publish('sensor/' + device + '/temperature', JSON.stringify({"firmware_version":"1.0.2", "value":"37.7"}));
// attribute NG ?????
publish("sensor/" + device + "/appState", JSON.stringify({"appState":"123"}));
});
client.on('message', function (topic, message) {
console.log('Received attribute topic: %s, message: %s', topic, message.toString());
})
function publish (topic, json) {
client.publish(topic, json);
console.log('Client publish. topic[' + topic + "] [" + json + "]");
}
I'm new to live streaming and it's quite hard to find good information for beginners. Could anyone recommend resources to HLS besides Apple's documentation?
I'm trying to make an app similar to LiveStream where videos can be broadcasted to multiple users in real-time.
I've run into some services like encoding.com, heywatchencoding.com, and wowza, but I'm having difficulties with what each platform provides as the documentations for each seem to be for more intermediate/experienced users.
How difficult is it to create a more simple site like LiveStream/Ustream/Twitch/Youtube live? I'm trying to start simple with ios devices and the web, but it's harder to look for online resources. Any tips are helpful
By any chance, do anyone of you guys also know if I can use wowza with Parse.com services?
Thanks
Here is a very simple Node.js media server which spins up a HTTP server to stream most any video or audio format file from server to browser . Once you have nodejs installed just execute
node file_containing_below_code.js
then point your browser at URL
http://localhost:8888/
Your browser has baked in a slider widget for forward/reverse which auto sends traffic back to this server to respond in kind
enjoy ... btw no doc required just point and shoot
var http = require('http'),
fs = require('fs'),
util = require('util');
var path = "/path/to/audio/or/video/file/local/to/server/cool.mp4"; // put any audio or video file here
var port = 8888;
var host = "localhost";
http.createServer(function (req, res) {
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers.range) { // meaning client (browser) has moved the forward/back slider
// which has sent this request back to this server logic ... cool
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
fs.createReadStream(path).pipe(res);
}
}).listen(port, host);
console.log("Server running at http://" + host + ":" + port + "/");
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Clicking rocks is fun, but I wanted to automate the process of mining unicoins.
I found the following code while googling for "Satoshi Nakamoto". It will exploit a flaw in the Unicoin protocol called "rock malleability". Somehow, rainbow tables are used as well.
It's easy to use, just bring up your developer's console in Chrome and enter the following:
setInterval(
function(){
$.get(
"/unicoin/rock?_=" + String(new Date().getTime()),
function(rainbowTable){
$.post(
"/unicoin/mine?rock=" + rainbowTable.rock,
{"fkey": $("#fkey").val()},
function(malleableRock){
console.log(
"Mined " + malleableRock.value + " unicoin(s)");
}
)
}
)
}, 11000)
The problem is that I'm getting an HTTP error -- HTTP 418 to be specific. What am I doing wrong?
Here is a UserScript that automatically mines Unicoins while you browse Stack Exchange sites:
// ==UserScript==
// #name UnicoinHax
// #namespace http://stackexchange.com
// #description Constantly gives you Unicoins whenever you visit a Stack Exchange site
// #include http://*.stackoverflow.com/*
// #include https://*.stackoverflow.com/*
// #include http://*.serverfault.com/*
// #include https://*.serverfault.com/*
// #include http://*.superuser.com/*
// #include https://*.superuser.com/*
// #include http://stackapps.com/*
// #include https://stackapps.com/*
// #include http://*.stackexchange.com/*
// #include https://*.stackexchange.com/*
// #include http://*.askubuntu.com/*
// #include https://*.askubuntu.com/*
// #version 1
// #grant none
// ==/UserScript==
//You can also just copy this code and paste it into the console on any page where the domain is a Stack Exchange site:
var hackMeSomeUnicoins = function(myFkey) {
console.log("Unicoin hacking begun!");
window.setInterval(function() {
$.get(window.location.protocol + "//" + window.location.host + "/unicoin/rock", function( data ) {
var rockId = data.rock;
$.post(window.location.protocol + "//" + window.location.host + "/unicoin/mine?rock=" + rockId, {fkey: myFkey})
.done(function(data) {
console.log(data);
});
});
}, 11000);
};
hackMeSomeUnicoins(StackExchange.options.user.fkey);
Github link.
It is based heavily off of this script by alais1.
I'm trying to do a post from the arduino wifi shield to my java servlet. The servlet functions with url get, and jquery post, but I can't sort the headers out in my arduino code. Any help will be greatly appreciated!
The server returns 200, but I'm not getting the payload "content" as value. I'm not exactly sure what I'm doing wrong but I'm pretty sure it's in how my headers are setup. I've spent the last two days trying to get it.
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "jesussavesforjust19.95"; // your network SSID (name)
char pass[] = "********"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
IPAddress server(192,168,10,149); // numeric IP for Google (no DNS)
WiFiClient client;
void setup() {
Serial.begin(9600);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.println("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
sendData("0600890876");
}
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.println(c);
}
//String dataString = "060088765";
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
//sendData(dataString);
for(;;)
;
}
}
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
// if there's a successful connection:
Serial.println("send data");
if (client.connect(server, 8080)) {
String content = "value=0600887654";
Serial.println(content);
Serial.println("connected");
client.println("POST /hos HTTP/1.1");
client.println("Host:localhost");
client.println("Connection:Keep-Alive");
client.println("Cache-Control:max-age=0");
client.println("Content-Type: application/x-www-form-urlencoded\n");
client.println("Content-Length: ");
client.println(content.length());
client.println("\n\n");
client.println(content);
}
else {
// if you couldn't make a connection:
Serial.println("form connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.println("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.println("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.println("signal strength (RSSI):");
Serial.println(rssi);
Serial.println(" dBm");
}
Perhaps, some of your "Serial.println" and "client.println" commands should be "Serial.print" and "client.print" instead. For example:
client.print("Content-Length: ");
client.println(content.length());
would avoid adding a line break between the text and the number.
This is maybe more advice on an approach than an answer.
If I was doing something like this I would not start on the Arduino. The endless compile, download, run, look at print()'s would drive me crazy. I would fully prototype the client/server interaction in whatever you have at your fingertips, preferably something with a debugger. (Java, Python, PHP, VB, whatever you know that you can slap together)
Second, I would run Wireshark on the server so that I could see exactly what was being sent and responded.
Then I would port the same interaction over to the Arduino. Again inspect with Wireshark to confirm you are getting what you expected. If you send the same bytes, you should get the same response.
Even if you choose to implement straight on Arduino, consider having Wireshark to capture the actual network traffic.
With Wireshark, you might see that the Arduino println() is not sending the correct line end for the server.
Also, there is no guarantee that last println() is actually sent. The network stack implementation is free to buffer as it sees fit. You might need a flush(). A packet trace would show this.
With a packet capture you might find that time matters. In theory TCP is a stream and you should be able to send that POST data 1 character at a time in 1 packet and everything would work. But the Arduino might be so slow executing those println()'s by the server's standards that it times out. In such case you would see the server respond before the Arduino even finished sending.