Cannot open SPIFFS on ESP32 (Arduino): Mounting SPIFFS failed! Error: -1 [closed] - arduino

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
I'm building a configuration handler class to ESP32 using Platform IO.
My class has two member functions, as follows:
void WiFiPortal::writeParams(String server, String port, String token)
{
Serial.println("Saving params to filesystem");
DynamicJsonDocument json(1024);
json["mqttServer"] = server;
json["mqttPort"] = port;
json["mqttApiToken"] = token;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile)
Serial.println("Failed to open config file for writing");
serializeJson(json, Serial);
serializeJson(json, configFile);
configFile.close();
// end save
}
void WiFiPortal::readParams()
{
// read configuration from FS json
Serial.println("Reading parameters");
if (SPIFFS.begin())
{
if (SPIFFS.exists("/config.json"))
{
// file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile)
{
Serial.println("opened config file");
DynamicJsonDocument json(1024);
DeserializationError error = deserializeJson(json, configFile);
if (!error)
{
Serial.println("\nParsed json");
String server = json["mqttServer"];
String port = json["mqttPort"];
String token = json["mqttApiToken"];
// Do some stuff with data here
}
else
{
Serial.println("Failed to load json config");
}
configFile.close();
}
}
else
{
Serial.println("Configuration file not found.");
}
}
else
{
Serial.println("Failed to mount filesystem");
}
}
When running, I'm getting the following error at the serial monitor:
Reading parameters
E (155) SPIFFS: mount failed, -10025
[ 161][E][SPIFFS.cpp:89] begin(): Mounting SPIFFS failed! Error: -1
Failed to mount filesystem
Any ideas of what is going on? I'm using a ESP32WROOM32 board.

Related

Firebase Remote Config throws fetch status 0 exception when user offline on Unity Editor

In my gaming Unity ( 2021.3.2f1 version) project, I'm using remote config SDK ( 9.5.0) for finetuning the game data. Players can play on offline mode, in order to do that I'm setting default values of each config key from json local path. Below code shows the implementation of config method. SetupRemoteConfig() is called when the firebase app is initiliazed.
public void SetupRemoteConfig()
{
var remoteConfig = FirebaseRemoteConfig.DefaultInstance;
Dictionary<string, object> configDefaults = new Dictionary<string, object>();
configDefaults.Add(ConfigKeys.adjust_testMode.ToString(), true);
configDefaults.Add(ConfigKeys.ShopPageCoinPackConfigs.ToString(), GetDefaultJsonString(ConfigKeys.ShopPageCoinPackConfigs));
var configSettings = new ConfigSettings();
if (Debug.isDebugBuild)
{
configSettings.MinimumFetchInternalInMilliseconds = 0;
configSettings.FetchTimeoutInMilliseconds = 0;
}
else
{
configSettings.MinimumFetchInternalInMilliseconds = 900000;
configSettings.FetchTimeoutInMilliseconds = 12000;
}
remoteConfig.SetConfigSettingsAsync(configSettings).ContinueWithOnMainThread(task =>
{
//Set Default Config Values
remoteConfig.SetDefaultsAsync(configDefaults).ContinueWithOnMainThread(task =>
{
remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task =>
{
var info = remoteConfig.Info;
if (task.IsCanceled)
{
Debug.Log("Fetch canceled.");
}
else if (task.IsFaulted)
{
Debug.Log("Fetch encountered an error.");
}
else if (task.IsCompletedSuccessfully)
{
Debug.Log(String.Format("Remote data loaded and ready (last fetch time {0}).", info.FetchTime));
}
switch (info.LastFetchStatus)
{
case LastFetchStatus.Failure:
switch (info.LastFetchFailureReason)
{
case FetchFailureReason.Error:
Debug.Log("Fetch failed for unknown reason");
break;
case FetchFailureReason.Throttled:
Debug.Log("Fetch throttled until " + info.ThrottledEndTime);
break;
}
break;
case LastFetchStatus.Pending:
Debug.Log("Latest Fetch call still pending.");
break;
}
IDictionary<string, ConfigValue> values = remoteConfig.AllValues;
Debug.Log("Fetching firebase remote config data successful.");
OnDataFetched?.Invoke(values);
});
});
});
}
It works perfectly when Unity editor connects to Internet. However, when I test the offline mode of my game on the Unity Editor, all the default config values are loaded perfectly but remote config SDK throws an exception like this:
fetching failure: http code 0
UnityEngine.Debug:LogError (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string)
Firebase.AppUtil:PollCallbacks ()
Firebase.Platform.FirebaseAppUtils:PollCallbacks ()
Firebase.Platform.FirebaseHandler:Update ()
Firebase.Platform.FirebaseMonoBehaviour:Update ()
I try to catch this exception and continue loading the game, because default config values are loaded perfectly. However I couldn't catch the exception, it throws anyway. And Editor only logged "task.IsFaulted" condition. How can I catch this exception or how should I handle this error when firebase offline?

ERROR_UNKNOWN downloading file from Firebase Storage

Im trying to download a file *.Apk from the storage and install when is completed.
i revised the rules from storage and the uses.
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read : if request.auth.uid != null;
}
}
}
on rules monitor all operations are accepted but the file can't be donwloaded
fragment of donwload code is:
public void downloadUpdate() {
StorageReference gsReference = FirebaseStorage.getInstance("filename.apk");
final String rutadestino = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
final String nombrearchivo = "LeaderBoard-Upd.apk";
final Uri archivodestino = Uri.parse("file://" + rutadestino+nombrearchivo);
File localFile = new File(rutadestino+nombrearchivo);
if (localFile.exists()) {
localFile.delete();
}
gsReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Local temp file has been created
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", new File(rutadestino+nombrearchivo));
Intent install = new Intent(Intent.ACTION_VIEW);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setData(contentUri);
startActivity(install);
//unregisterReceiver(this);
finish();
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(archivodestino,
"application/vnd.android.package-archive");
startActivity(install);
//unregisterReceiver(this);
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
int errorCode = ((StorageException) exception).getErrorCode();
String errorMessage = exception.getMessage();
Emergente.ErrorCode(1,getApplicationContext());
}
});
}
i received
errorcode "13000"
errorMessage "An unknown error occurred, please check the HTTP result code and inner exception for server response."
cause "open failed: EACCES (Permission denied)"
Maybe another code fragment is wrong, but in this momment im stucked on the OnFailureListener
The problem is on the app permissions, when app tries to download files and write it on a wrong directory/file without the required permission it will trow the "ERROR_UNKNOWN" message.
The solution is create the file on the same app directory, when doing so the permission is not required unles the API <= 18 then the permission will be necessary.
Solution:
File localFile = new File(getExternalFilesDir(null), "file.apk");

InputStream closed unexpectedly while using Jersey MultiPart file upload & Server-Sent Events (SSE)

I'm using Jersey Multipart for uploading file to the server via Rest API. In the resource method, I accessed the file content via InputStream. I want to return the uploaded file size to the client with EventOutput using SSE so the client easily get the uploaded file size directly from upload resource method.
I'm using Jersey as JAX-RS implementation in java with Grizzly Http server. Here is my code:
#POST
#Path("upload")
#Produces(SseFeature.SERVER_SENT_EVENTS)
#Consumes("multipart/form-data;charset=utf-8")
public EventOutput upload(#FormDataParam("file") InputStream file,
#FormDataParam("file") FormDataContentDisposition fileDisposition) {
final EventOutput eventOutput = new EventOutput();
try {
new Thread(new Runnable() {
#Override
public void run() {
try {
int read = -1;
byte[] buffer = new byte[1024];
OutboundEvent.Builder eventBuilder
= new OutboundEvent.Builder();
OutboundEvent event = null;
long totalRead = 0, lastReadMB = 0;
while ((read = file.read(buffer)) != -1) {
totalRead += read;
if (lastReadMB != (totalRead / (1024 * 1024))) {
lastReadMB = totalRead / (1024 * 1024);
event = eventBuilder.name("uploaded").data(Long.class, totalRead).build();
eventOutput.write(event);
}
}
event = eventBuilder.name("uploaded").data(Long.class, totalRead).build();
eventOutput.write(event);
} catch (Exception e) {
throw new RuntimeException(
"Error when writing the event.", e);
} finally {
try {
eventOutput.close();
} catch (Exception ioClose) {
throw new RuntimeException(
"Error when closing the event output.", ioClose);
}
}
}
}).start();
return eventOutput;
} catch (Exception e) {
logger.error(e.toString(), e);
}
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity("something happened").build());
}
​
The problem is when my resource method return EventOutput as a response and request processing thread back to the I/O container, the InputStream closed and the processing thread can't access to the uploaded file. Here is the exception:
Exception in thread "Thread-1" java.lang.RuntimeException: Error when writing the event.
at com.WebService.ContentService$1.run(ContentService.java:192)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.jvnet.mimepull.MIMEParsingException: java.io.IOException: Stream Closed
at org.jvnet.mimepull.WeakDataFile.read(WeakDataFile.java:115)
at org.jvnet.mimepull.DataFile.read(DataFile.java:77)
at org.jvnet.mimepull.FileData.read(FileData.java:69)
at org.jvnet.mimepull.DataHead$ReadMultiStream.fetch(DataHead.java:265)
at org.jvnet.mimepull.DataHead$ReadMultiStream.read(DataHead.java:219)
at java.io.InputStream.read(InputStream.java:101)
at com.WebService.ContentService$1.run(ContentService.java:181)
... 1 more
Caused by: java.io.IOException: Stream Closed
at java.io.RandomAccessFile.seek0(Native Method)
at java.io.RandomAccessFile.seek(RandomAccessFile.java:557)
at org.jvnet.mimepull.WeakDataFile.read(WeakDataFile.java:112)
... 7 more
​
1- What's the problem in the code? Why InputStream is closed in the middle of the file transfer?
2- Is there any alternative way to return the uploaded file size to the client in server side? (REQUIREMENT: the upload resource method must handle upload file asynchronously in different thread)

I am getting an System.IO.IOException while uploading a file to Amazon cloud server

I am getting
Error
{System.IO.IOException: Unable to write data to the transport
connection: An established connection was aborted by the software in
your host machine. ---> System.Net.Sockets.SocketException: An
established connection was aborted by the software in your host
machine
I am trying to upload a file to Amazon cloud server. It works smooth for small files, but throws this exception when I try to upload a file of about a GB.
Code
void writeStreamToService(S3Request request, long reqDataLen, Stream inputStream, Stream requestStream)
{
if (inputStream != null)
{
long current = 0;
// Reset the file stream's position to the starting point
inputStream.Position = 0;
byte[] buffer = new byte[this.config.BufferSize];
int bytesRead = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
current += bytesRead;
requestStream.Write(buffer, 0, bytesRead);
if (request != null)
{
request.OnRaiseProgressEvent(bytesRead, current, reqDataLen);
}
}
}
}
I found the problem. It was actually the anti Virus in my PC that was blocking the buffer memory Overflow, Disabling it got the job done :)
Thanks for your help #asawyer!

flex4 socket problem

I'm trying to communicate my flash application with my server. Either the problem is my code is working on Flash Professional, but I have prepared all my interface on Flash Builder which uses Flex 4 -SDK. My code does not work on Flex Project.
The problem is not security file. I can not solve the problem. What are the possible reasons?
Kind Regards.
If necessary my code is below [working on FlashPro but not on Flex ! ]
import flash.net.*;
import flash.events.Event;var host:String = new String("127.0.0.1");
var port:int = 8080;
var securityFile:String = "http://localhost:1755/.../..../s....xml";
var bagli:Boolean = false;
var socket:Socket = null;
var veri:String = new String("----");
btnGonder.addEventListener(MouseEvent.MOUSE_DOWN, tiklantiEvent);
function buildSocket():void
{
trace("beginning....");
socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(ErrorEvent.ERROR, onError);
socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
Security.allowDomain(host);
Security.loadPolicyFile(securityFile);
try {
socket.connect(host, port);
bagli = true;
trace("--- connection...");
} catch (error:Error) {
trace("--- connection failed...");
socket.close();
}
}
function send(string:String):void {
socket.writeUTFBytes(string);
socket.flush();
}
function onConnect(event:Event):void {
trace("connect");
}
function onClose(event:Event):void {
trace("closed");
}
function onError(event:IOErrorEvent):void {
trace("connection erron");
}
function onIOError(event:IOErrorEvent):void {
trace("data error");
}
function onResponse(event:ProgressEvent):void {
var string:String = socket.readUTFBytes(socket.bytesAvailable);
trace(string);
}
function (sender:Event):void {
trace("clicked button....");
buildSocket();
trace("------------------");
}
You are trying to authorize a socket connection by using a content-type policy file. You should use socket policy file instead. Policy file syntax is the same as far as I remember, but the url should begin with xmlsocket:// instead of http://. This file should not be served through http.
Furthermore, the host's domain and the domain from the policy file address should be exactly the same. Given that your host is specified as 127.0.0.1, change the policy file url to
xmlsocket://127.0.0.1:1755
For more details see Adobe's guidelines for policy files.

Resources