Android Things - Gpio.getValue() always returning true - raspberry-pi3

I have trying to set and get gpio value on Android Things, I am using raspberry pi 3 and have my connections at BCM26(output), BCM16(input).
I have also tried changing the pins and checked them using DMM as well, no matter what I do I am unable to set the output high. and even getValue gpio also return false.
mMotorGpio = service.openGpio(MOTOR_PIN_NAME);
mMotorGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
Log.i(TAG, "Output GPIO set");
.
.
.
try {
boolean newVal = !mMotorGpio.getValue();
Log.i(TAG,"setting port value as " + newVal);
mMotorGpio.setValue(newVal);
}catch (IOException e){
e.printStackTrace();
}

Seems like you are trying to read from the pin,which is configured for output:
mMotorGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
and also you didn't configured voltage signal to be returned as true (active), for example:
mMotorGpio.setActiveType(Gpio.ACTIVE_HIGH);
if you want high voltage as active as described in Official Documentation (section Reading from an input).
So,you will need 2 separate Gpio objects (one for Input, other for Output) to do, what you want. Something like this:
private static final String MOTOR_PIN_OUT_NAME = "BCM26";
private static final String MOTOR_PIN_IN_NAME = "BCM16";
private Gpio mMotorGpioIn;
private Gpio mMotorGpioOut;
...
mMotorGpioIn = service.openGpio(MOTOR_PIN_IN_NAME);
mMotorGpioIn.setDirection(Gpio.DIRECTION_IN);
mMotorGpioIn.setActiveType(Gpio.ACTIVE_HIGH);
mMotorGpioOut = service.openGpio(MOTOR_PIN_OUT_NAME);
mMotorGpioOut.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mMotorGpioOut.setActiveType(Gpio.ACTIVE_HIGH);
...
try {
boolean newVal = !mMotorGpioIn.getValue();
Log.i(TAG,"setting port value as " + newVal);
mMotorGpioOut.setValue(newVal);
} catch (IOException e){
e.printStackTrace();
}

You cannot reliably read the state value of a pin configured as an output. From the GPIO reference docs for getValue():
Get the current value of the GPIO pin (for GPIO pins configured as input only). Returns an unpredictable value when the GPIO is configured as output.

Related

How to use the writeback connector by the Linux DRM api /libdrm?

I recently start learning Direct Rendering Manager and tried to use the writeback connector and the libdrm.
There are some documents and codes of how the kernel implements it, but not enough of how the userspace uses the api, such as drmModeAtomicAddProperty and drmModeAtomicCommit of the writeback connector in libdrm.
I have referred to libdrm/tests/modetest; Linux API Reference; linux/v6.0-rc5/source/drivers/gpu/drm/drm_writeback.c and some patch imformation.
I used modetest to get some driver information and tried my code using the libdrm:
/* I previously get the value of writeback connector:wbc_conn_id
* and create an output framebuffer:fb_id
* and find the active crtc: crtc_id
* next to get writeback connector property*/
props = drmModeObjectGetProperties(fd, wbc_conn_id, DRM_MODE_OBJECT_CONNECTOR);
printf("the number of properties in connector %d : %d \n", wbc_conn_id, props->count_props);
writeback_fb_id_property = get_property_id(fd, props,"WRITEBACK_FB_ID");
writeback_crtc_id_property = get_property_id(fd, props,"CRTC_ID");
printf("writeback_fb_property: %d\n",writeback_fb_id_property);
printf("writeback_crtc_id_property: %d\n",writeback_crtc_id_property);
drmModeFreeObjectProperties(props);
/* atomic writeback connector update */
req = drmModeAtomicAlloc();
drmModeAtomicAddProperty(req, wbc_conn_id, writeback_crtc_id_property, crtc_id);
printf ("%d\n",ret);
drmModeAtomicAddProperty(req, wbc_conn_id, writeback_fb_id_property, buf.fb_id);
ret = drmModeAtomicCommit(fd, req, DRM_MODE_ATOMIC_ALLOW_MODESET, NULL);
if (ret) {
fprintf(stderr, "Atomic Commit failed [1]\n");
return 1;
}
drmModeAtomicFree(req);
printf("drmModeAtomicCommit Set Writeback\n");
getchar();
It turns out that the drmModeAtomicCommit failed. Was there any property set wrongly or missed? The value of two steps of addproperty is 1 and 2, and the atomic commit returned EINVAL -22 .
I've looked around but found no solution or similar question about the property set of writebackconnector.

Flowfiles stuck in queue (Apache NiFi)

I have following flow:
ListFTP -> RouteOnAttribute -> FetchFTP -> UnpackContent -> ExecuteScript.
Some of files are stuck in queue UnpackContent -> ExecuteScript.
ExecuteScript ate some flowfiles and they just disappeared: failure and success relationships are empty. It just showed some activity in Tasks/Time field. All of them stuck in queue before ExecuteScript. I tried to empty queue, but not all of flowfiles have been deleted from this queue. About 1/3 of them still stuck in queue. I tried to disable all processors and empty queue again but it returns: 0 FlowFiles (0 bytes) were removed from the queue.
When i'm trying to change Connection destionation it returns:
Cannot change destination of Connection because FlowFiles from this Connection are currently held by ExecuteScript[id=d33c9b73-0177-1000-5151-83b7b938de39]
ExecuScript from this answer (uses Python).
So, I can't empty queue because its always return message that there is no any flowfile, and i can't remove connection. This has been going on for several hours.
Connection configuration:
Scheduling is set to 0 sec, no penalties for flowfiles, etc.
Is it script problem?
UPDATE
Changed script to:
flowFile = session.get()
if (flowFile != None):
# All processing code starts at this indent
if errorOccurred:
session.transfer(flowFile, REL_FAILURE)
else:
session.transfer(flowFile, REL_SUCCESS)
# implicit return at the end
Same result.
UPDATE v2
I set concurent tasks to 50 and then ran ExecuteScript again and terminated it. I got this error:
UPDATE v3
I created additional ExecuteScript processor with same script and it works fine. But after i stopped this new processor and create new flowfiles, this processor now have same problems: it's just stuck.
Hilarious. Is ExecuteScript for single use?
You need to modify Your code in nifi-1.13.2 because NIFI-8080 caused these bugs. Or you just use nifi 1.12.1
JythonScriptEngineConfigurator:
#Override
public Object init(ScriptEngine engine, String scriptBody, String[] modulePaths) throws ScriptException {
// Always compile when first run
if (engine != null) {
// Add prefix for import sys and all jython modules
prefix = "import sys\n"
+ Arrays.stream(modulePaths).map((modulePath) -> "sys.path.append(" + PyString.encode_UnicodeEscape(modulePath, true) + ")")
.collect(Collectors.joining("\n"));
}
return null;
}
#Override
public Object eval(ScriptEngine engine, String scriptBody, String[] modulePaths) throws ScriptException {
Object returnValue = null;
if (engine != null) {
returnValue = ((Compilable) engine).compile(prefix + scriptBody).eval();
}
return returnValue;
}

Temboo call hangs Arduino

I am using an Arduino Uno with the Desloo W5100 Ethernet shield. Whenever I try to make calls to Parse using Temboo, the device just hangs. Sometimes for minutes...sometimes indefinitely. Here is what I run:
void updateParseDoorState() {
if (!ENABLE_DOOR_STATE_PUSHES) {
Serial.println("Door state pushing disabled. Skipping.");
return;
}
Serial.println("Pushing door state to database...");
TembooChoreo UpdateObjectChoreo(client);
// Invoke the Temboo client
UpdateObjectChoreo.begin();
// Set Temboo account credentials
UpdateObjectChoreo.setAccountName(TEMBOO_ACCOUNT);
UpdateObjectChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
UpdateObjectChoreo.setAppKey(TEMBOO_APP_KEY);
// Set profile to use for execution
UpdateObjectChoreo.setProfile("ParseAccount");
// Set Choreo inputs
String ObjectIDValue = "xxxxxxxxxx";
UpdateObjectChoreo.addInput("ObjectID", ObjectIDValue);
String ClassNameValue = "DoorState";
UpdateObjectChoreo.addInput("ClassName", ClassNameValue);
String ObjectContentsValue = (currentState == OPEN) ? "{\"isOpen\":true}" : "{\"isOpen\":false}";
UpdateObjectChoreo.addInput("ObjectContents", ObjectContentsValue);
// Identify the Choreo to run
UpdateObjectChoreo.setChoreo("/Library/Parse/Objects/UpdateObject");
// Run the Choreo; when results are available, print them to serial
int returnStatus = UpdateObjectChoreo.run();
if (returnStatus != 0){
setEthernetIndicator(EthernetStatus::SERVICES_DISCONNECTED);
Serial.print("Temboo error: "); Serial.println(returnStatus);
// read the name of the next output item
String returnResultName = UpdateObjectChoreo.readStringUntil('\x1F');
returnResultName.trim(); // use “trim” to get rid of newlines
Serial.print("Return result name: "); Serial.println(returnResultName);
// read the value of the next output item
String returnResultData = UpdateObjectChoreo.readStringUntil('\x1E');
returnResultData.trim(); // use “trim” to get rid of newlines
Serial.print("Return result data: "); Serial.println(returnResultData);
}
/*while(UpdateObjectChoreo.available()) {
char c = UpdateObjectChoreo.read();
Serial.print(c);
}*/
UpdateObjectChoreo.close();
Serial.println("Pushed door state to database!");
Serial.println("Waiting 30s to avoid overloading Temboo...");
delay(30000);
}
I get this in the serial monitor:
Current state:6666ÿ &‰ SP S P U WR SR R PR P 66Temboo error: 223
This indicates that there is some type of HTTP error, but I never get to print what the error is...because the serial monitor is stuck there forever. And eventually disconnects.
I work at Temboo.
It sounds like you might be running out of memory on your board (a common occurrence on resource-constrained hardware like Arduino). You can find our tutorial on how to conserve memory usage while using Temboo here:
https://temboo.com/hardware/profiles
Feel free to get in touch with Temboo Support at any time if you have further questions - we're always available and happy to help.

Serial Ports /dev/tty.* are not working when /dev/cu.* ports are accessed firstly

I am trying to create a Processing application connected with an Arduino.
Due to the fact that I want the connection between the two to be established automatically, meaning that I do not specify the name of the port, but I'm using Serial.list() to get the names of the ports available and then with a for loop I will check which one is printing the correct string.
The problem is that when I access firstly the /dev/cu.* then all the /dev/tty.* ports are busy and vice versa. This is quite strange and I do not want this to happen.
You should be able to use one(/dev/tty.*) or the other(/dev/cu.*), but not both at the same time as they might point to the same resource in different ways.
I recommend listing the ports, checking the port prefix (agains let's say /dev/tty.*, but not /dev/cu.*), initialising the Serial port, then exiting the loop that traverses the listed serial ports:
import processing.serial.*;
Serial arduino;
final int BAUD_RATE = 9600;
void setup(){
String[] ports = Serial.list();
for(int i = 0 ; i < ports.length; i++){//go through each port
if(ports[i].contains("tty.usbmodem")){//find one that looks like an Arduino on OSX
try{
arduino = new Serial(this,ports[i],BAUD_RATE);//initialize the connection
i = ports.length;//exit the loop, break; should also work
println("Arduino connection succesfully initialized");
}catch(Exception e){
System.err.println("Error opening Serial port!\nPlease check USB connection and ensure the port is not already open in another application.");
e.printStackTrace();
}
}
}
if(arduino == null) System.err.println("Serial connection to Arduino failed!");
}

How does send() work in omnet++

Does the send() in omnet++ set the source address of the packet to the current host address?
Why am I asking? because I'm trying to code a class for a malicious host "Eve" that performs a replay attack.
void MalAODVRouter::handleMessage(cMessage *msg)
{
cMessage *ReplayMsg = msg->dup();
AODVRouting::handleMessage(msg);
capturedMsgs++;
if (capturedMsgs==10) // One out of every 10 packets (frequency of replay)
{
//we can add a delay before sending the copy of the message again (1 time unit)
sendDelayed(ReplayMsg, 1,"ipOut");
ReplayedMsgs++;
std::cout<<"Launched Replay Packet!\n";
ev<<"Launched Replay Packet!\n";
this->capturedMsgs=0;
// }
}
}
You can see at the beginning of my code snippet I tried using the function dup() to duplicate a packet (msg) Eve's receives while its on it's on its way to the legitimate destination.
Now, can I send the duplicated packet later and it would be having the original source address OR should I dig deeper into layers to fake the source address to have Bob's address instead of Eve's? like below:
/*UDPPacket *udpPacket = dynamic_cast<UDPPacket *>(msg);
AODVControlPacket *ctrlPacket = check_and_cast<AODVControlPacket *>(udpPacket->decapsulate());
IPv4ControlInfo *udpProtocolCtrlInfo = dynamic_cast<IPv4ControlInfo *>(udpPacket->getControlInfo());
ASSERT(udpProtocolCtrlInfo != NULL);
IPv4Address sourceAddr = udpProtocolCtrlInfo->getSrcAddr(); //get Source Address
IPv4Address destinationAddr = udpProtocolCtrlInfo->getDestAddr(); //get Destination Address
IPv4Address addr = getSelfIPAddress();
if (addr != destinationAddr) // if it is not destined for "Eve"
{
UDPPacket *ReplayUDPPacket = udpPacket;
AODVControlPacket *ReplayCtrlPacket = check_and_cast<AODVControlPacket *>(ReplayUDPPacket->decapsulate());
IPv4ControlInfo *ReplayUDPProtocolCtrlInfo = dynamic_cast<IPv4ControlInfo *>(ReplayUDPPacket->getControlInfo());
ASSERT(ReplayUDPProtocolCtrlInfo != NULL);
ReplayUDPProtocolCtrlInfo->setSrcAddr(sourceAddr); //Forge Source
ReplayUDPProtocolCtrlInfo->setDestAddr(destinationAddr); //Keep Destination
*/
//we can add a delay before sending the copy of the message again (1 time unit)
sendDelayed(ReplayMsg, 1,"ipOut");
ReplayedMsgs++;
std::cout<<"Launched Replay Packet!\n";
ev<<"Launched Replay Packet!\n";
this->capturedMsgs=0;
Does the send() method automatically sets the source address of the outgoing packet to the current host address? If so, then my replay attempt is not working...
send() is an OMNeT++ API call. As OMNeT++ is just a generic discrete event simulation framework, it does not know anything about the model code (so it cannot and should not manipulate it). IP address is a defined in the INET framework so only code from the INET framework can change it.
On the other hand the modules in the standard host below you module can do whatever they want before the packet is sent out to the network. Now in this actual case, the source IP address is determined by the control info that is attached to the packet. dup()-ing the packet copies that information too, so the IP address will be the same.

Resources