Can't publish data from CC3100 + MSP430F5529 on PUBNUB - pubnub

I followed the following tutorial: http://www.pubnub.com/blog/pubnub-streaming-texas-instruments-iot/
step by step and I managed to compile and code and connect to my Wi-Fi access point.
I think I managed to connect to PubNub (the code prints on the terminal screen "PubNub Set Up" but in the code there is no real verification that it was indeed set up.
I opened an account on PubNub and I named my channel "testing" (I named it the same in the code I uploaded - I checked that a million times) and when I go to the Dev Console and click on subscribe I can't see anything! I mean I can post messages through the Dev Console but what I really want to see are the messages from the CC3100.
I checked the UART terminal on my computer and I see the data being printed constantly so I know it is working.
I went over the tutorial again and again and I'm doing the same thing but it just doesn't work.
Any help would be appreciated!
What am I missing?
Thanks

First to verify your PubNub account is properly configured and your local Wi-Fi connectivity is working - are you able to publish messages from the dev console in one browser and receive them in the dev console on another browser? (both using the same channel name, of course). If that works, please send a message to help (at) pubnub (dot) com with your sub-key info and information about your project and we will try to assist you tracking down the issue.

This answer is posted really late. I admit I forgot about this post so I just decided to update it (a few years late though).
I started digging to try and see what was the problem and I think I found it. First of all, I saw that PubNub.publish() wasn't working properly with the json_String because the json_String was 90% gibrish. So I erased most of the code that constructed the json_String (the part that inserts the analog values) and made it simpler.
I then also added a part of code at the end which was needed for proper performance of the client variable which I got off of a part of code which was used for an arduino based project using the CC3100.
Anyway, the new code is the one below and now it works FINE! I finally see all the input streaming on PubNub! Thanks a lot! :D
/*PubNub sample JSON-parsing client with WiFi support
This combines two sketches: the PubNubJson example of PubNub library
and the WifiWebClientRepeating example of the WiFi library.
This sample client will properly parse JSON-encoded PubNub subscription
replies using the aJson library. It will send a simple message, then
properly parsing and inspecting a subscription message received back.
This is achieved by integration with the aJson library. You will need
a version featuring Wiring Stream integration, that can be found
at http://github.com/pasky/aJson as of 2013-05-30.
Please refer to the PubNubJson example description for some important
notes, especially regarding memory saving on Arduino Uno/Duemilanove.
You can also save some RAM by not using WiFi password protection.
created 30 May 2013
by Petr Baudis
https://github.com/pubnub/pubnub-api/tree/master/arduino
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
#include <PubNub.h>
#include <aJSON.h>
static char ssid[] = "NetSSID_Name"; // your network SSID (name)
static char pass[] = "NetworkdPassword"; // your network password
static int keyIndex = 0; // your network key Index number (needed only for WEP)
const static char pubkey[] = "pub-c-51eb45ec-b647-44da-b2aa-9bf6b0b98705";
const static char subkey[] = "sub-c-7e78ed9c-991d-11e4-9946-02ee2ddab7fe";
const static char channel[] = "testing";
#define NUM_CHANNELS 4 // How many analog channels do you want to read?
const static uint8_t analog_pins[] = {23, 24, 25, 26}; // which pins are you reading?
void setup()
{
Serial.begin(9600);
Serial.println("Start WiFi");
WiFi.begin(ssid, pass);
while(WiFi.localIP() == INADDR_NONE) {
Serial.print(".");
delay(300);
}
Serial.println("WiFi set up");
PubNub.begin(pubkey, subkey);
Serial.println("PubNub set up");
delay(5000);
}
void loop()
{
WiFiClient *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);
Serial.println(channel);
client = PubNub.publish(channel, json_String);
Serial.println(*client);
free(json_String);
if (!client) {
Serial.println("publishing error");
delay(1000);
return;
}
client->stop();
delay(500);
}
//- See more at: http://www.pubnub.com/blog/pubnub-streaming-texas-instruments-iot/#sthash.tbQXMIzw.dpuf

Related

Solana program to send multiple lamport transfers and emit event

I’m building a program intended to manage multiple payments with one call. The program needs to complete the following steps:
Accept a certain amount of lamports
Pay a portion of the received lamports to specified wallets, such that the amount received is exhausted
Emit an event containing the receipt
I’ve built this logic with an Ethereum smart contract and it works perfectly fine, however when attempting to write a Solana program with Solang and #solana/solidity, I’m running into a number of issues.
The first issue I encountered was simply that #solana/solidity seems to not be built for front end use (transactions required a private key as an argument, rather than being signed by a wallet like Phantom) so I built a fork of the repository that exposes the transaction object to be signed. I also found that the signer’s key needed to be manually added to the array of keys in the transaction instruction — see this Stack Overflow post for more information, including the front end code used to sign and send the transaction.
However, after this post I ran into more errors, take the following for example:
Transaction simulation failed: Attempt to debit an account but found no record of a prior credit.
Transaction simulation failed: Error processing Instruction 0: instruction changed the balance of a read-only account
Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N invoke [1]
Program data: PO+eZwYByRZpDC4BOjWoKPj20gquFc/JtyxU9NsuG/Y= DEjYtM7vwjNW3HPewJU3dvG4aiov5tUUlrD6Zz5ylBgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADppnQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATEtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVNC02S0gyMV9Sa3RZZVJIb3FKOFpFAAAAAAAAAAAAAAA=
Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N consumed 3850 of 200000 compute units
Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N success
failed to verify account 11111111111111111111111111111111: instruction changed the balance of a read-only account
The error messages seemed to be inconsistent, with some attempts throwing different errors despite the only changes in the code being a server restarting or a library being reinstalled.
Although solutions to the previous errors would be greatly appreciated, at this point I’m more inclined to ask more broadly if what I’m trying to do is possible, and, providing the source code, for help understanding what I need to do to make it work.
Below is the working source code for my Ethereum contract:
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
contract MyContract {
event Receipt(
address From,
address Token,
address[] Receivers,
uint256[] Amounts,
string Payment
);
function send(
address[] calldata _receivers,
uint256[] calldata _amounts,
string calldata _payment
) external payable {
require(
_receivers.length == _amounts.length,
"Receiver count does not match amount count."
);
uint256 total;
for (uint8 i; i < _receivers.length; i++) {
total += _amounts[i];
}
require(
total == msg.value,
"Total payment value does not match ether sent"
);
for (uint8 i; i < _receivers.length; i++) {
(bool sent, ) = _receivers[i].call{value: _amounts[i]}("");
require(sent, "Transfer failed.");
}
emit Receipt(
msg.sender,
0x0000000000000000000000000000000000000000,
_receivers,
_amounts,
_payment
);
}
}
The only differences between this code and my Solana program code are types and the method used to transfer lamports. All references to uint256 is replaced by uint64, the placeholder token address is changed from the null address to the system public key (address"11111111111111111111111111111111"), and the payment loop is changed to the following:
for (uint8 i = 0; i < _receivers.length; i++) {
payable(_receivers[i]).transfer(_amounts[i]); // Using .send() throws the same error
}
The code used to then deploy the program to the Solana test validator is as follows, only slightly modified from the example provided by #solana/solidity:
const { Connection, LAMPORTS_PER_SOL, Keypair, PublicKey } = require('#solana/web3.js');
const { Contract } = require('#solana/solidity');
const { readFileSync } = require('fs');
const PROGRAM_ABI = JSON.parse(readFileSync('./build/sol/MyProgram.abi', 'utf8'));
const BUNDLE_SO = readFileSync('./build/sol/bundle.so');
(async function () {
console.log('Connecting to your local Solana node');
const connection = new Connection('http://localhost:8899', 'confirmed');
const payer = Keypair.generate();
async function airdrop(pubkey, amnt) {
const sig = await connection.requestAirdrop(pubkey, amnt * LAMPORTS_PER_SOL);
return connection.confirmTransaction(sig);
}
console.log('Airdropping SOL to a new wallet');
await airdrop(payer.publicKey, 100);
const program = new Keypair({
publicKey: new Uint8Array([...]),
secretKey: new Uint8Array([...])
});
const storage = new Keypair({
publicKey: new Uint8Array([...]),
secretKey: new Uint8Array([...])
});
const contract = new Contract(connection, program.publicKey, storage.publicKey, PROGRAM_ABI, payer);
console.log('Loading the program');
await contract.load(program, BUNDLE_SO);
console.log('Deploying the program');
await contract.deploy('MyProgram', [], program, storage, 4096 * 8);
console.log('Program deployed!');
process.exit(0);
})();
Is there something I’m misunderstanding or misusing here? I find it hard to believe that such simple behavior on the Ethereum blockchain couldn’t be replicated on Solana — especially given the great lengths the community has gone to to make Solana programming accessible through Solidity. If there’s something I’m doing wrong with this code I’d love to learn. Thank you so much in advance.
Edit: After upgrading my solang version, the first error was fixed. However, I'm now getting another error:
Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: instruction changed the balance of a read-only account
I'm not sure which account is supposedly read-only, as it isn't listed in the error response, but I'm pretty sure the only read-only account involved is the program as it's executable. How can I avoid this error?
The error Attempt to debit an account but found no record of a prior credit happens when you attempt to airdrop more than 1 SOL. If you wish to have more than 1 SOL, then airdrop 1 SOL in a loop until you have enough.

UWP How to check incoming requests from BLE device?

How to check all incoming requests from paired BLE device to current device?
I think it possible with Events, maybe UWP have needle event, or i must implement custom event, but where is the right way?
Microsoft have explainations about GATT Server, i think it's not what i need, 'cause i don't need a server with services and characteristics, i need only check incoming request and parse passed data in my application.
I'm not found sure way for checking incoming requests, but i make some trick.
Application can subscribe for notifications from device (in my case it's Mi Band 2) and receive some data from this device across ValueChanged.
One time i call ValueChanged handler in App.xaml.cs after connecting and pairing device and this working on all application, i don't need call it again and again.
Here is App.xaml.cs part of code.
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
MiBand2SDK.MiBand2 band = new MiBand2SDK.MiBand2();
var page = typeof(Views.AuthPage);
// Checking for device availability and current session
if (_LocalSettings.Values["isAuthorized"] != null
&& await band.ConnectAsync())
{
if (e.PreviousExecutionState == ApplicationExecutionState.NotRunning && await band.Auth.AuthenticateAsync())
page = typeof(Views.MainPage);
else if (band.Auth.IsAuthenticated())
page = typeof(Views.MainPage);
// Here we are, this notification handler of responses from the band.
band.HeartRate.SetNotificationHandler();
}
else
{
System.Diagnostics.Debug.WriteLine("Not Authenticated...");
}
// other part of code...
Here is HeartRate.SetNotificationHandler() code:
public async void SetNotificationHandler()
{
_heartRateMeasurementCharacteristic = await Gatt.GetCharacteristicByServiceUuid(HEART_RATE_SERVICE, HEART_RATE_MEASUREMENT_CHARACTERISTIC);
Debug.WriteLine("Subscribe for HeartRate notifications from band...");
if (await _heartRateMeasurementCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify) == GattCommunicationStatus.Success)
// Just subscribe for notifications and set ValueChanged. It's all.
_heartRateMeasurementCharacteristic.ValueChanged += HeartRateMeasurementCharacteristicValueChanged;
}
Hope it helps someone...

LaunchUriAsync Windows calculator - first time

Perhaps this is expected behavior, but the programmatic launching of built-in applications in Windows 10 is scarce for anything aside from settings app, maps, and contacts, in my experience - and I could use some help on this.
I am launching the stock Windows Calculator from within the application. I took some guesses as the Uri and it appears to work - except on the first launch. When we get a new device, the first time the app is run and the calculator is attempted to be launched, it wants to get an app from the store (which the end users will not have access to) - it does not even offer the built-in calculator as a choice. If the calculator is opened manually, even once, it just works from that point on. Is there something else I could/should be doing? Any guidance or suggestions would be greatly appreciated.
I would like to have it work the first time (a setting on the device?), or at least offer the built-in calculator as a choice.
Here is the code I am using:
private async void LaunchCalculatorAsync(object sender, TappedRoutedEventArgs e)
{
var options = new Windows.System.LauncherOptions();
options.TreatAsUntrusted = false;
options.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseNone;
await Windows.System.Launcher.LaunchUriAsync(new Uri("calculator:"), options);
}
From running a list of installed apps on the device, I see the calculator listed: Microsoft.WindowsCalculator_8wekyb3d8bbwe. I have been unsuccessful with attempting to provide the PreferredApplicationPackageFamilyName using options.PreferredApplicationPackageFamilyName = "WindowsCalculator";
I have tried with/without the "Microsoft." as well as with/without the odd string of characters.
You may get the demo from Microsoft in GitHub,
Association launching sample
Hope this can help you.
private async void LaunchUriWithWarning()
{
// Create the URI to launch from a string.
var uri = new Uri(UriToLaunch.Text);
// Configure the warning prompt.
var options = new LauncherOptions() { TreatAsUntrusted = true };
// Launch the URI.
bool success = await Launcher.LaunchUriAsync(uri, options);
if (success)
{
rootPage.NotifyUser("URI launched: " + uri.AbsoluteUri, NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("URI launch failed.", NotifyType.ErrorMessage);
}
}

Java Me video player realize error with http - MediaException

I'm using the below code (references from, http://www.java-tips.org/java-me-tips/midp/playing-video-on-j2me-devices.html). It fails at 'realize()', with the javax.microedition.media.MediaException, "Unable to create native player". What is the problem here?
I tried this using both Eclipse and Netbeans. Am I missing some "internet" permissions or using any incorrect encoding, the video is an external 'mpg' test-resource and does work fine when downloaded through a desktop browser.
public void run()
{
String url = "http://www.fileformat.info/format/mpeg/sample/05e7e78068f44f0ea748855ef33c9f4a/MELT.MPG";
//Append the GUI to a form
Form form = new Form("Video on java mobile!");
Display display = Display.getDisplay(this);
display.setCurrent(form);
try
{
HttpConnection conn = (HttpConnection)Connector.open(url,
Connector.READ_WRITE);
InputStream is = conn.openInputStream();
Player p = Manager.createPlayer(is,"video/mpeg");
//I tried the below, but that didn't work either
//Player p = Manager.createPlayer(url);
p.realize();
//Get the video controller
VideoControl video = (VideoControl) p.getControl("VideoControl");
if(video != null)
{
//Get a GUI to display the video
Item videoItem = (Item)video.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null);
form.append(videoItem);
}
//Start the video
p.prefetch();
p.start();
}
catch(Exception e)
{
form.append(url + " Error:" + e.getMessage());
}
}
I've just started with Java, Eclipse, Netbeans. Since, there similar samples found everywhere, I believe I'm missing something very basic. Can someone please help?
The problem here was the video file. Although my source video seemed "mpeg", it wasn't acceptable to the emulator. After searching through a bit, I found a converter and I manually converted some sample mp4 to "mpeg". It finally worked with the same emulator, after I tried to download and play these manually converted files.
One piece of advise if you are new J2ME/JavaME apps (like me), keep playing with the input data sources/formats and the emulators. Switching emulators or the input data-formats is an easy way to identify the not-so-evident problems.

J2ME Audio Streaming through SIP Connection

I am creating a J2ME real time streaming audio player with RTP and through SIP connection. Also I am new for these things. I want to take look deeply those things. If any one know a good working sample code demonstrating an audio player streaming with RTP (That means how to send a REGISTER message to the server through SIP to get registered and send an INVITE message and get the response & play). Please let me know, highly appreciated.
Also I looked here
if
My server port is 6060
ip 111.111.111.1
id is myid password 123
Have I used the code correctly? If I am wrong, please make me correct.
public void doRegister(String username, String password, String realm) {
SipClientConnection scc = null;
SipConnectionNotifier scn = null;
String contact = null;
try {
scn = (SipConnectionNotifier) Connector.open("sip:5080");
contact = new String("sip:myid:123#"+scn.getLocalAddress()+":"+scn.getLocalPort());
scc = (SipClientConnection) Connector.open("sip:111.111.111.1+"transport=tcp") ;
scc.initRequest("REGISTER", scn);
scc.setHeader("From", "sip:myid:123#"+scn.getLocalAddress()+":5080");
scc.setHeader("To", "sip:myid:123#111.111.111.1");
scc.setHeader("Contact", contact);
scc.send();
boolean handled = false;
int scode = 0;
while(!handled) {
SipHeader sh;
scc.receive(30000);
scode = scc.getStatusCode();
switch(scode){
case 401:
sh = new SipHeader("WWW-Authenticate",
scc.getHeader("WWW-Authenticate"));
realm = sh.getParameter("realm");
scc.setCredentials(username, password, realm);
break;
case 407:
sh = new SipHeader("Proxy-Authenticate",
scc.getHeader("Proxy-Authenticate"));
realm = sh.getParameter("realm");
scc.setCredentials(username, password, realm);
break;
case 200:
handled = true;
break;
default:
handled = true;
}
}
scc.close();
} catch(Exception ex) {
// handle Exceptions
}
}
I got a respond with 180 Rigging message. Also let me know what is realm here. scc.setCredentials(username, password, realm);
As you see here in example 1 - you realize that when you make a fresh Reqeust to server, where as server expects authentication it first sends 401. By seeing this the client can then either search for a password or ask the user. When server sends the 401 response code, it specifies which security domain is applicable for the given requests. This is already what you have got in your code :
realm = sh.getParameter("realm");
Once, failed, you need to send() the request again with credentials here. I guess the setCredentials() function is only setting these parameters inside the scc object and they will be applied when send() is called again.
Some references that might be of interest: http://www.developer.nokia.com/Community/Discussion/showthread.php?126760-SIP-registration-401-Unauthorized-..
(here people had issues related port number, which i am not sure if this is bothering you)
Many functions and more things are available and wide answer can be found here Also Nokia JSR180 API has sample codes as well

Resources