How to send runicast message to itself? - contiki

I'm studying a wireless sensor network and I'm implementing a distributed algorithm. What I want that it sends a runicast message to itself.
I tried to send runicast message to '&rimeaddr_node_addr', but it timedout.
runicast_send(&runicast, &rimeaddr_node_addr, MAX_RETRANSMISSIONS);
runicast_open(&runicast, 144, &runicast_callbacks);
message *msg = malloc(sizeof(msg));
msg->type = DISCOVER;
msg->size = sizeof(*msg);
packetbuf_copyfrom(&msg, sizeof(msg));
runicast_send(&runicast, &rimeaddr_node_addr, MAX_RETRANSMISSIONS);
So, I couldn't send runicast to itself. Could you help me please?

Related

JMRI keeps repeating MQTT messages to my Pico Wifi via Hivemq. Is there a way to stop this or reduce the repeitition?

I borrowed code from Toms Hardware on how to use MQTT and subscribe. JRMI is the publisher of the messages and it keeps repeating them over and over again. Is there anyway to have the message sent only once? I dont have this problem when I subscribe to MQTT via http://www.hivemq.com/demos/websocket-client/ The MQTT service I'm using is broker.hivemq.com
For those not familiar with JRMI, it is the JAVA program that model railroads use to control tracks,lighting, DCC etc. Ref: https://www.jmri.org/
The link to Tom's is here https://www.tomshardware.com/how-to/send-and-receive-data-raspberry-pi-pico-w-mqtt
The code adapted from Tom's is
import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("whatever","pwd")
time.sleep(5)
print(wlan.isconnected())
mqtt_server = 'broker.hivemq.com'
client_id = 'bigles'
topic_sub = b'/trains/track/turnout/#'
def sub_cb(topic, msg):
print("New message on topic {}".format(topic.decode('utf-8')))
msg = msg.decode('utf-8')
print(msg)
def mqtt_connect():
client = MQTTClient(client_id, mqtt_server, keepalive=60)
client.set_callback(sub_cb)
client.connect()
print('Connected to %s MQTT Broker'%(mqtt_server))
return client
def reconnect():
print('Failed to connect to MQTT Broker. Reconnecting...')
time.sleep(5)
machine.reset()
try:
client = mqtt_connect()
except OSError as e:
reconnect()
while True:
client.subscribe(topic_sub)
time.sleep(1)
The setup inside JRMI for MQTT (edit->preferences) is as follows:
JMRI, by default, publishes with "the retain option on". When you subscribe to a topic the broker will send you the most recent (if any) retained message. This occurs even if you already had an identical subscription as per the MQTT Spec:
If a Server receives a SUBSCRIBE Packet containing a Topic Filter that is identical to an existing Subscription’s Topic Filter then it MUST completely replace that existing Subscription with a new Subscription. The Topic Filter in the new Subscription will be identical to that in the previous Subscription, although its maximum QoS value could be different. Any existing retained messages matching the Topic Filter MUST be re-sent, but the flow of publications MUST NOT be interrupted [MQTT-3.8.4-3].
In your code you are calling Subscribe in a loop:
while True:
client.subscribe(topic_sub)
time.sleep(1)
To avoid the repeated messages move the subscribe out of the loop (you only need to subscribe once!). Something like the following (simplified!) code:
client = mqtt_connect()
client.subscribe(topic_sub)
while True:
client.wait_msg() // Use client.check_msg() if you have other stuff to do

Tweepy bot to tweet DMs

I would like to make a bot on twitter to use with my friends, it would be like a spotted. The bot would need to tweet the messages they send on his dm. On the internet I found this function, but I don't know if it's right, nor how to close this puzzle, can someone help me?
api.list_direct_messages()
You can get the DM messages with
auth = tweepy.OAuthHandler('api_key', 'api_secret')
auth.set_access_token('access_token', 'token_secret')
api = tweepy.API(auth)
messages = get_api().list_direct_messages(count=5)
The code above would rin in a thread to fetch the messages every x minutes.
Once you have the messages you can process the list, send the tweet and delete the DMs (to avoid processing it again).
for message in messages:
text = message.message_create["message_data"]["text"]
api.update_status(f'Tweet DM content: {text}'
# remove DM
api.destroy_direct_message(message.id)

How to use twilio bi-directional stream feature to play raw audio data

I'm using Twilio Programmable Voice to process phone calls.
I want to use bi-directional stream feature to send some raw audio data to play by twilio, the initialization code looks like,
from twilio.twiml.voice_response import Connect, VoiceResponse, Stream
response = VoiceResponse()
connect = Connect()
connect.stream(url='wss://mystream.ngrok.io/audiostream')
response.append(connect)
Then when got wss connection from twilio, I start to send raw audio data to twilio, like this
async def send_raw_audio(self, ws, stream_sid):
print('send raw audio')
import base64
import json
with open('test.wav', 'rb') as wav:
while True:
frame_data = wav.read(1024)
if len(frame_data) == 0:
print('no more data')
break
base64_data = base64.b64encode(frame_data).decode('utf-8')
print('send base64 data')
media_data = {
"event": "media",
"streamSid": stream_sid,
"media": {
"playload": base64_data
}
}
media = json.dumps(media_data)
print(f"media: {media}")
await ws.send(media)
print('finished sending')
test.wav is a wav file encoded audio/x-mulaw with a sample rate of 8000.
But when run, I can't hear anything, and on twilio console, it said
31951 - Stream - Protocol - Invalid Message
Possible Causes
- Message does not have JSON format
- Unknown message type
- Missing or extra field in message
- Wrong Stream SID used in message
I have no idea which part is wrong. Does anyone know what's my problem? I can't find an example about this scenario, just follow instructions here, really appreciate it if someone knows there is an example about this, thanks.
Not sure if this will fix it but I use .decode("ascii"), not "utf-8"
Question is probably not relevant anymore, but I came across this while debugging my bi-directional stream, so it might be useful for someone:
Main reason why were you receiving this error because of the typo in json content. You are sending "playload" instead of "payload".
Another issue when sending data to twilio stream is that you should send mark message at the end of data stream to notify twilio that complete payload was sent. https://www.twilio.com/docs/voice/twiml/stream#message-mark-to-twilio
When sending data back to twilio stream, be aware that payload should not contain audio file type header bytes, so make sure you remove them from your recording or alternatively skip them while sending data to twilio.

LuaSocket - TCP 2nd message not sending

I've been searching Google for awhile and there seems to be no offers on fixing this problem I have here.
I am using LuaSocket as a simple way to connect to a external server I created, and I am able to connect to it successfully and send a signal.
However, when I try to send a second message later on, the external server does not seem to be receiving the message, even though I am still connected to the socket.
socket = require("socket")
host, port = ip, port
tcp = assert(socket.tcp())
tcp:settimeout( 0 )
tcp:connect(host, port);
msg = {
["status"]="connect",
["usrName"]=username
}
msg = Json.Encode(msg)
tcp:send(msg); -- This message, the server received this message.
-- Later in my code, I attempt to send another message.
msg = {
["status"]="anotherMessage",
["usrName"]=username
};
msg = Json.Encode(msg)
tcp:send(msg); -- This message is not sending, even though i'm still connected.
You need to show what happens on the other side as it may be simply not reading even though the connection may be open. You also don't say what exactly happens when "message is not sending"; do you get an error? the script finishes but the message is not sent?
There are several things you can try:
Switch to the (default) synchronous send until you get it working; remove tcp:settimeout(0), as your send may simply fail with "timeout" message if the other side is not ready to read the message.
Check the error message from :send call to see if it's timing out or not.
local ok, err = tcp:send(msg)
Use socket.select to check if the other side it ready to accept the message you are sending.
Try adding "\r\n" at the end of your serialized JSON.

how to share a link via sms in blackberry

I am building an application where I need the option to share via email and SMS.
I have done the share via Email, where when the user selects the image, the url is passed as the content of the email. But while sharing via SMS, I can't do something like setContent as I did for email and fetch the url in the SMS directly, instead of user typing the address manually.
I am using Message class in email and MessageConnection class for SMS, as shown in the blackberry community example.
The Message object you receive when calling MessageConnection.newMessage(TEXT_MESSAGE) is actually a TextMessage object (or a BinaryMessage object with BINARY_MESSAGE).
If you cast the received object to the proper class (TextMessage or BinaryMessage), you should be able to use its setPayloadText(String data) (or setPayloadData(byte[] data) for a BinaryMessage) to enter a value in the message before sending it.
Your code should look like this:
Message msg = myMessageConnection.newMessage(TEXT_MESSAGE, /* address */);
TextMessage txtMsg = (TextMessage)msg;
txtMsg.setPayloadText(/* Text to send */);
myMessageConnection.send(msg);
When you send an email, you can set the body of it and send it to the user from the Email native application. You cant do taht for SMSs. I worked on that issue and for BB Torch I was able to set the text of the SMS message but for other devices that was impossible. I always obtain an empty text message!!
So y suggestion to you is using the following code wich will send the SMS to a number without the interference of the user
MessageConnection conn = (MessageConnection) Connector.open("sms://" + userNumber);
TextMessage txtmessage = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
txtmessage.setPayloadText(text);
conn.send(txtmessage);

Resources