How to fetch remaining energy of all neighbor nodes in Unetstack? - unetstack

I have developed an energy model that can be loaded for every node present in the network. This model calculates transmitting and receiving energy.
Now what I want to do is if a node request all it's neighboring nodes then those neighbor nodes should reply back by sending their remaining energy values so that the node can decide which neighbor has higher energy level.
How to implement this and how that requesting node will fetch all energy values received
from various neighbor nodes?
This is my energy model :
import org.arl.fjage.*
import org.arl.unet.*
import org.arl.unet.phy.*
import java.math.*
import Java.util.*
class EnergyModel extends UnetAgent {
int neighbor, addr
float neighbor_distance;
def ranging
def init_energy = 10
def dist
def data
def depth
def C = 1.3312e-9 // empirical constant
static def Tot_bits
def fr = 10 //carrier freq.(Khz)
def d = 0.036*Math.pow(fr,1.5) //Thorp's constant
static def source
static HashMap<Integer, Integer[]> map = new HashMap<>();
def sum=0.0,avg=0.0,count=0;
public void startup() {
AgentID phy = agentForService(Services.PHYSICAL);
subscribe (topic(phy));
ranging = agentForService Services.RANGING;
subscribe topic(ranging);
def nodeInfo = agentForService Services.NODE_INFO;
addr = nodeInfo.address;
depth = nodeInfo.location[2]
map.put(addr, nodeInfo.location);
}
public void processMessage(Message msg) {
if (msg instanceof DatagramFailureNtf){
System.out.println "\n\tDatagramFailureNtf occured!!\nt"+msg.toString()
println "\n\t BadFrameNtf occured !!!!\n\t"+msg.toString()
}
if (msg instanceof DatagramNtf && msg.protocol == Protocol.DATA) {
count++
neighbor = msg.from;
source = msg.from;
data = msg.getData()
int[] loc1 = map.get(source)
int[] loc2 = map.get(msg.getTo())
def x = loc1[0] - loc2[0]
def y = loc1[1] - loc2[1]
def distance = Math.sqrt((x)*(x) +(y)*(y));
def bits=32
Tot_bits = bits*data.size()
System.out.println "\n\tNumber of bits sent :"+Tot_bits
dist = distance/1000.0 // converting the distance in Km.
BigDecimal Tx_EG = new BigDecimal("1"); // Or BigInteger.ONE
Tx_EG = Tx_EG.multiply(BigDecimal.valueOf(Tot_bits*50e-9+ Tot_bits*
(0.001)*dist*(depth*-0.001)*C*Math.pow(Math.E,d*dist)));
init_energy = init_energy - Tx_EG ;
sum = sum + Tx_EG
avg = sum/count
String value = String.valueOf(Tx_EG.doubleValue());
System.out.println '\n\tTransmission Energy : '+value+" Joules";
System.out.println '\tRemaining Energy : '+(init_energy)
File file = new File("I:\\out.txt")
def text = file.getText()
System.out.println "ENERGY: -t "+text+" -i "+source+" -d
"+Tot_bits+" -e "+init_energy+" T"
println "ENERGY: -t "+text+" -i "+source+" -d "+Tot_bits+" -e
"+init_energy+" T"
}
if (msg instanceof RxFrameNtf && msg.protocol == Protocol.DATA){
data = msg.getData() // getting data
System.out.println "\tData is :"+data
def bits=32
Tot_bits = bits*data.size() //caculating total number of bits
System.out.println "\tNumber of bits received :"+Tot_bits
BigDecimal Rx_EG = new BigDecimal("1"); // Or BigInteger.ONE
Rx_EG = Rx_EG.multiply(BigDecimal.valueOf(Tot_bits*50e-9));
init_energy = init_energy - Rx_EG ;
String value = String.valueOf(Rx_EG.doubleValue());
System.out.println '\n\tReception Energy : '+value+" Joules";
System.out.println '\tRemaining Energy : '+(init_energy)
System.out.println '\tTime : '+msg.getRxTime()
System.out.println '\tNode ID : '+msg.getTo()
System.out.println "ENERGY: -t "+msg.getRxTime()+" -i
"+msg.getTo()+" -d "+Tot_bits+" -e "+init_energy+" R"
println "ENERGY: -t "+msg.getRxTime()+" -i "+msg.getTo()+" -d
"+Tot_bits+" -e "+init_energy+" R"
}
if (msg instanceof BadFrameNtf){
System.out.println "\n\tBadFrameNtf occured !!!!\n\t"+msg.toString()
println "\n\t BadFrameNtf occured !!!!\n\t"+msg.toString()
}
if (msg instanceof CollisionNtf){
System.out.println "\n\tCollision occured !!!!\n\t"+msg.toString()
println "\n\tCollision occured !!!!\n\t"+msg.toString()
}
}
void setup() {
}
}

You'll need to define application-specific PDUs to request this information and provide this information, and implement your own protocol to respond with appropriate response PDUs when a request PDU is received. See how to write your own application-specific protocols from the ping example (samples/ping folder in the simulator) in the developer's guide.
An alternative would be to expose the energy as an agent parameter for PHY, and request it using the remote access service to use the RemoteParamReq to ask for it.

Related

How to run multiple instances(datasets) from same CPLEX model?

I have a MIP model in CPLEX as a mod file. I have datasets in multiple '.txt' files. Is there a way to automate the process in CPLEX to solve the model for many instances. Currently, I run the model every single time for every instance. I have my instances as "M1_D1.txt", "M2_D1.txt",...."M100_D10.txt". However, the model to solve is the same.
In Matlab, it is easier to automate the process. But I could not find anywhere how to automate in CPLEX.
define variables
retrieve data from .dat file
define objective function
define constraints
you could use a main block (flow control)
Here is an example:
sub.mod
float maxOfx = ...;
dvar float x;
maximize x;
subject to {
x<=maxOfx;
}
execute
{
writeln("x= ",x);
}
try1.dat
maxOfx=1;
try2.dat
maxOfx=2;
and then
main.mod
{string} datFiles=...;
main {
var source = new IloOplModelSource("sub.mod");
var cplex = new IloCplex();
var def = new IloOplModelDefinition(source);
for(var datFile in thisOplModel.datFiles)
{
var opl = new IloOplModel(def,cplex);
var data2= new IloOplDataSource(datFile);
opl.addDataSource(data2);
opl.generate();
if (cplex.solve()) {
opl.postProcess();
var o=new IloOplOutputFile("res"+datFile+".txt");
o.writeln("OBJ = " + cplex.getObjValue());
o.close();
writeln("OBJ = " + cplex.getObjValue());
} else {
writeln("No solution");
}
opl.end();
}
}
main.dat
datFiles={"Try1.dat","try2.dat"};
In command line oplrun main.mod main.dat
In the IDE, you need to have main.mod and main.dat in a run configuration

Check if SSH Private Key is Encrypted

Key pairs generated with ssh-keygen on macOS can have different formats.
The standard PEM ASN.1 object which is readable by macOS' SecKey APIs
A PEM with textual headers
OpenSSH Keys
OpenSSH Encrypted Keys
OpenSSH/BSD uses this non-standardized format here.
Now I only need to be able to check if a private key has a passphrase set or not, so I can prompt the user to enter it, without having to deal with the complexities of different key formats.
Is there a quick way on macOS via Swift or C API, to check if a key has a passphrase set?
The difference between the unencrypted and encrypted private keys is the fact that the key blob is encrypted. You need to decrypt the private key blob data before you can use the private key blob. So once the encrypted private key data is decoded, you can treat it the same as the unencrypted private key data.
A unencrypted private key blob PEM file looks like this:
—–BEGIN PRIVATE KEY—–
{base64 private key blob)
—–END PRIVATE KEY—–
The encrypted RSA private key PEM file looks like this:
—–BEGIN RSA PRIVATE KEY—–
Proc-Type: 4,ENCRYPTED
DEK-Info: {encryption algorithm},{salt}
{base64 encrypted private key blob)
—–END RSA PRIVATE KEY—–
e.g.
—–BEGIN RSA PRIVATE KEY—–
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,AB8E2B5B2D989271273F6730B6F9C687
{base64 encrypted private key blob)
—–END RSA PRIVATE KEY—–
So to decode the private key data you need to:
Parse the DEK-Info encryption algorithm and the salt (good idea to confirm the first line is: "Proc-Type: 4,ENCRYPTED" as well).
Decode the base64 encrypted private key blob.
Generate the encryption algorithm "key" and "IV" based on the salt and the passphrase
Decode the encrypted private key blob.
Once you have done that the decrypted private key blob can be treated just like the unencoded private key blob.
The number of supported encryption algorithm's are rather large, so you may like to support a sub-set of algorithms. e.g. "DES-EDE3-CBC", "AES-xxx-CBC", etc
To generate the IV you need to convert salt string to binary. The salt string is a hex encoded string, so convert each two strings characters into a byte using a hex string character to byte converter.
For the generation of the encryption algorithm key you need the key size (e.g. DES-EDE3-CBC is 192bits, AES-256-CBC is 256bits). Build up the key "bits" with a loop appending MD5 hash results to the key until generate all the key bits required.
The MD5 HASH loop generation will consist of:
First MD5 Hash: MD5 hash of the first 8 bytes of the IV and the Passphrase
All other MD5 Hashes is the MD5 hash of the last MD5 hash result and the first 8 bytes of the IV and the Passphrase
See the openssl source for EVP_BytesToKey method for an example of the key bits generation.
The encrypted private key blob can now be decoded using the selected encryption algorithm using the IV and KEY build above.
There are two ways that I would suggest. Either reading the command line output using readLine() and checking if it asks for a password then do something accordingly.
import Foundation
func runCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {
var output : [String] = []
var error : [String] = []
let task = Process()
task.launchPath = cmd
task.arguments = args
let outpipe = Pipe()
task.standardOutput = outpipe
let errpipe = Pipe()
task.standardError = errpipe
task.launch()
let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: outdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
output = string.components(separatedBy: "\n")
}
let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: errdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
error = string.components(separatedBy: "\n")
}
task.waitUntilExit()
let status = task.terminationStatus
return (output, error, status)
}
//Sample usage
let (output, error, status) = runCommand(cmd: "/usr/local/bin/node", args: "--version")
print("program exited with status \(status)")
if output.count > 0 {
print("program output:")
print(output)
//HERE YOU CAN CHECK IF PASSWORD REQUEST HAS BEEN MADE
}
if error.count > 0 {
print("error output:")
print(error)
}
The example code will return your node version installed if there is one, but you could use it to check if a password prompt has been made by the system for the RSA Key.
The other way could be perhaps using a third-party library like SwiftyRSA or BlueRSA which might help with validation.
I implemented my own OpenSSH check for the 2 most common formats
For one I'm checking the PEM headers for DEK-Info for Linux-style SSH PEMs
For OpenSSH style keys I manually parse the format using the class below
import Foundation
private let opensshMagic = "openssh-key-v1"
public class SSHPrivateKey {
public struct OpenSSHKey {
let cipherName: String
let kdfName: String
let kdfOptions: Data
let numKeys: Int
var isEncrypted: Bool {
return cipherName != "none"
}
}
public let data: Data
public init(data: Data) {
self.data = data
}
public func openSSHKey() -> OpenSSHKey? {
// #define AUTH_MAGIC "openssh-key-v1"
//
// byte[] AUTH_MAGIC
// string ciphername
// string kdfname
// string kdfoptions
// int number of keys N
// string publickey1
// string publickey2
// ...
// string publickeyN
// string encrypted, padded list of private keys
guard let magic = opensshMagic.data(using: .utf8) else {
return nil
}
if data.prefix(magic.count) != magic {
return nil
}
var offset = magic.count + 1
guard let cipherName = data.consumeString(offset: &offset),
let kdfName = data.consumeString(offset: &offset) else {
return nil
}
let kdfOptions = data.consumeBytes(offset: &offset)
let numKeys = data.consumeUInt32(offset: &offset)
return OpenSSHKey(cipherName: cipherName,
kdfName: kdfName,
kdfOptions: kdfOptions,
numKeys: Int(numKeys))
}
}
private extension Data {
func consumeBytes(offset: inout Int) -> Data {
let n = Int(consumeUInt32(offset: &offset))
let b = Data(self[offset..<offset + n])
offset += n
return b
}
func consumeString(offset: inout Int) -> String? {
return consumeBytes(offset: &offset).utf8String
}
func consumeUInt8(offset: inout Int) -> UInt8 {
let v = self[offset] & 0xFF
offset += 1
return v
}
func consumeUInt32(offset: inout Int) -> UInt32 {
var i: UInt32 = 0
i = (i << 8) | UInt32(consumeUInt8(offset: &offset))
i = (i << 8) | UInt32(consumeUInt8(offset: &offset))
i = (i << 8) | UInt32(consumeUInt8(offset: &offset))
i = (i << 8) | UInt32(consumeUInt8(offset: &offset))
return i
}
}

Groovy render chunk file

I am using StreamingMarkupBuilder for generate very big xml file. File is so big, that i have set
JAVA_OPT="-XX:NewSize=2048m -XX:MaxNewSize=4096m -XX:SurvivorRatio=8 -Xms4096m -Xmx4096m -XX:MaxPermSize=4096m"
(2048m, 1024m not enough)
Without chunk i got file so far, response answer:
*0:0:0:0:0:0:0:1 - - [03/Jan/2018:17:15:37 +0200] "GET ... HTTP/1.1" 200 167467288*
Service:
def builder = new StreamingMarkupBuilder()
def Header = {
mkp.xmlDeclaration()
mkp.declareNamespace('': 'http://...')
...
...
Header{
SourceDocuments {
SalesInvoices {
// !!!big scope of data came in this loop!!!
for (row in data) {
Invoice {
...
...
}
}
}
}
}
XmlUtil.serialize(builder.bind(Header))
NOTE: Only builder.bind(Header) as last result line create file very slowly.
Controller:
response.contentType = grailsApplication.config.grails.mime.types[exportFormat]
response.setHeader("Content-disposition", "attachment; filename=" + reportName + "." + exportFormat)
response.outputStream << result
I am looking for chunk solution for response file and minimize JAVA_OPT environments heaps sizes. Actually to get a solution with DOM would be perfect because of performance, and I would like appreciate that, but will be nice if solution of chunk exists on different way that have groovy.
this answer is not about chunking but about performance
here are 4 examples of rendering xml with time result comparison
note that minimal memory consumption will be with StreamingMarkupBuilder because it renders xml directly to output (file) without building it in memory
in other cases we are building xml in memory and then rendering to output
the fastest one will be with CompileStatic annotation for the main loop
START: StreamingMarkupBuilder
END: 23946 sec
START: DOMBuilder
END: 8282 sec
START: NodeBuilder
END: 8778 sec
START: NodeBuilder+CompileStatic
END: 2978 sec
code:
import groovy.util.Node
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
class Const{
static long MAX_ITEMS=999999
}
//=============StreamingMarkupBuilder==========================
long t=System.currentTimeMillis()
println "START: StreamingMarkupBuilder"
def xdata = new groovy.xml.StreamingMarkupBuilder().bind{
root {
for(int i=0;i<Const.MAX_ITEMS;i++){
a('id':i,'123_'+i)
}
}
}
new File('c:/11/111.xml').withOutputStream{stream->
stream.withWriter("UTF-8"){ w-> xdata.writeTo( w ) }
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)
//=============DOMBuilder======================================
t=System.currentTimeMillis()
println "START: DOMBuilder"
DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
xdata = new groovy.xml.DOMBuilder(domBuilder).
root{
for(int i=0;i<Const.MAX_ITEMS;i++){
a('id':i,'123_'+i)
}
}
new File('c:/11/112.xml').withOutputStream{stream->
groovy.xml.XmlUtil.serialize(xdata, stream)
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)
//=============NodeBuilder=====================================
t=System.currentTimeMillis()
println "START: NodeBuilder"
xdata = new NodeBuilder().
root{
for(int i=0;i<Const.MAX_ITEMS;i++){
a('id':i,'123_'+i)
}
}
new File('c:/11/113.xml').withOutputStream{stream->
groovy.xml.XmlUtil.serialize(xdata, stream)
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)
//=============NodeBuilder+CompileStatic=======================
t=System.currentTimeMillis()
println "START: NodeBuilder+CompileStatic"
#groovy.transform.CompileStatic
def longLoopData(Node parent){
for(int i=0;i<Const.MAX_ITEMS;i++){
parent.appendNode('a', ['id':i], '123_'+i)
}
}
xdata = new NodeBuilder().
root{
longLoopData(current)
}
new File('c:/11/114.xml').withOutputStream{stream->
groovy.xml.XmlUtil.serialize(xdata, stream)
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)

Building a String array from a text file without collection classes

I am trying to build an array from a buffered in text file. This class is used by another class with a main method. What I have only prints the file... what I need is to have an array of strings, built line by line, mirroring the text file. I need to be able to then search against that array using a String from user input (that part will be in main method too) that will name a product, and find the corresponding price. I can't use things like ArrayList, Maps, Vectors, etc. This is in Java8.
/**
* A class that reads in inventory from vmMix1 text file using BufferedReader
* # author Michelle Merritt
*/
import java.io.*;
public class VendingMachine1
{
BufferedReader inInvFile1 = new BufferedReader(
new FileReader("vmMix1.txt"))
/**
* A method to print vending machine 1 inventory
*/
public void printVM1()
{
try
{
String vm1Line;
while((vm1Line = inInvFile1.readLine()) != null)
{
// This is what I was using for now to simply print my file
System.out.println(vm1Line);
}
}
catch(IOException e)
{
System.out.println("I/O Error: " + e);
}
}
}
This is the code that created my text file, since I can't seem to see how I attach the text file instead.
/**
* A class that creates the inventory found in vending machine #1, using
* a PrintWriter stream.
* # author Michelle Merritt
*/
import java.io.*;
public class VMMix1
{
public static void main(String[] args)
{
String [] product = {"Coke", "Dr. Pepper", "Sprite", "RedBull",
"Cool Ranch Doritos", "Lay's Potato Chips",
"Pretzels", "Almonds", "Snickers", "Gummi Bears",
"Milky Way", "KitKat"};
String [] packaging = {"bottle", "can", "can", "can", "bag", "bag",
"bag", "bag", "wrapper", "bag", "wrapper",
"wrapper"};
float [] price = {2.25f, 1.75f, 1.75f, 2.00f, 1.00f, 1.00f, 0.75f, 1.50f,
1.25f, 1.00f, 1.25f, 1.25f};
int [] quantity = {10, 10, 10, 12, 8, 10, 12, 9, 7, 11, 10, 8};
try(PrintWriter outFile = new PrintWriter("vmMix1.txt"))
{
for (int index = 0; index < product.length; index++)
{
outFile.printf("%-18s %-10s: $%.2f qty: %3d\n", product[index],
packaging[index], price[index], quantity[index]);
}
}
catch (IOException except)
{
System.out.println("IOException: " + except.getMessage());
}
}
}
I need for this thing to be dynamic. As the program runs, and something is purchased, I will have to account for losing inventory and changing the amount of money in the vending machine (there's another class for currency that houses quantities of denominations of money). I have to maintain the values in the array and reprint the updated array. Any help is much appreciated.
You may use Java8 stream API
String[] array = reader.lines().toArray(String[]::new);
You could even skip the buffer creation using
try (Stream<String> stream = Files.lines(Paths.get("vmMix1.txt"))) {
String [] array = stream.toArray(String[]::new);
}
Pre-Java8, probably one of the shortest way is to read the entire file into a string, and split it (ways to read a reader into string can be found here):
String[] array = fileAsString.split('\\n');
Of course you could also built the array in your loop and increase it for every line using System.arraycopy (which can be quite slow in that case).
String[] array = new String[0];
while((vm1Line = inInvFile1.readLine()) != null) {
String[] newArray = new String[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[array.length] = vm1Line;
array = newArray;
}
You may optimize this approach by creating a larger array first, fill in the lines, increase size of the array as needed (using arraycopy), and finally shrink the array to the number of written lines.
Thats more or less what an array list does. So in case you may use the collections api, you could simply do
List<String> list = new ArrayList<>();
while((vm1Line = inInvFile1.readLine()) != null) {
list.add(vm1Line);
}
String[] array = list.toArray(new String[list.size()]);
Hope it helps.
Stream<String> lines = Files.lines(Paths.get("C:/SelfStudy/Input.txt"));
String[] array = lines.toArray(String[]::new);

Generating Chrome Packaged App .crx header with Java

I"m trying to build the header in Java with no luck.
(here is the spec: https://developer.chrome.com/extensions/crx)
Any ideas?
protected void geneateCrxHeader (OutputStream ins,byte[] zipArchive) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, InvalidKeyException, SignatureException{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
byte[] key = pair.getPublic().getEncoded();
Signature instance = Signature.getInstance("SHA1withRSA");
instance.initSign(pair.getPrivate());
instance.update(zipArchive);
byte[] hash = instance.sign();
byte[] magic = {0x43,0x72,0x32,0x34,0x02,0x00,0x00,0x00,0x00,0x01,0x0E,0x0B,0x00,0x00,0x08,0x00};
ins.write(magic);
ins.write(key);
ins.write(hash);
}
and I get CRX_EXCESSIVELY_LARGE_KEY_OR_SIGNATURE..
I must be using wrong keygen.
in the docs they do say :
"..the contents of the author's RSA public key, formatted as an X509 SubjectPublicKeyInfo block. .."
i wonder if that is what i'm not doing correctly...
p.s Java crypto is a new frontier for me , so pls don't laugh if I did something totally dumb.
Here is some code that I whipped up and didn't test that illustrates producing just the header. I based this solely on reading the spec.
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Signature;
public static byte[] generateCrxHeader(byte[] extensionContents) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
Signature sigInstance = Signature.getInstance("SHA1withRSA");
sigInstance.initSign(pair.getPrivate());
sigInstance.update(extensionContents);
byte [] signature = sigInstance.sign();
byte [] subjectPublicKeyInfo = pair.getPublic().getEncoded();
final int headerLength = 4 + 4 + 4 + 4 + subjectPublicKeyInfo.length + signature.length;
ByteBuffer headerBuf = ByteBuffer.allocate(headerLength);
headerBuf.order(ByteOrder.LITTLE_ENDIAN);
headerBuf.put(new byte[]{0x43,0x72,0x32,0x34}); // Magic number
headerBuf.putInt(2); // Version
headerBuf.putInt(subjectPublicKeyInfo.length); // public key length
headerBuf.putInt(signature.length); // signature length
headerBuf.put(subjectPublicKeyInfo);
headerBuf.put(signature);
final byte [] header = headerBuf.array();
return header;
}

Resources