Search This Blog

Tuesday, March 04, 2025

Import multiple CSV files into separate Excel worksheets

 #import multiple CSV files into separate Excel worksheets
$wrkfldr='C:\temp'

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$wb = $excel.Workbooks.Add()

Get-ChildItem $wrkfldr\*.csv | ForEach-Object {
    if ((Import-Csv $_.FullName).Length -gt 0) {
        $csvBook = $excel.Workbooks.Open($_.FullName)
        $csvBook.ActiveSheet.Copy($wb.Worksheets($wb.Worksheets.Count))
        $csvBook.Close()
    }
}

Wednesday, February 05, 2025

RPI network reconnect

to be run */10 * * * * from cron

#!/bin/bash

wlan='wlan0'
gateway='192.168.1.1'

ping -c2 $gateway 2>&1 >/dev/null; rc=$?
if [[ $rc -eq 0 ]] ; then
        echo `date +"%b %d %T "`$0": The network is up."
else
        echo `date +"%b %d %T "`$0": Network down! Attempting reconnection."
        if [ -f /storage/.cache/nonet ]; then
                rm -f /storage/.cache/nonet
                reboot
        fi
        ifdown $wlan
        rmmod brcmfmac
        sleep 2
        modprobe brcmfmac brcmfmac_wcc
        ifup --force $wlan
        sleep 2
        connmanctl connect wifi_dc345a1743d_6e6545675289d3567_managed_psk &>/dev/null
        sleep 10
        ping -c2 $gateway 2>&1 >/dev/null; rc=$?
        if [[ $rc -ne 0 ]] ; then
                echo "1" > /storage/.cache/nonet
        fi
fi
exit 0

 

Friday, January 03, 2025

Deploy port forward script on multiple computers

# deploy-cond_portforward.ps1
# a stand-alone script that deploys the port-forward to a list of target computers
# v1.0 - 2024-10-08 s.t. - initial release


# EDIT THIS - create a temporary list of all computer on which we want to deploy
$complstfileToAdd = @'
AH00001
RA00003
BM0001-W10
'@
Set-Content "$env:TEMP\comps.txt" $complstfileToAdd

# create the .ps1 file that will execute the portforward - this file must be tailored to each host after deployment
$psfileToAdd = @'
# condprtforward.ps1
# a powershell script to check the portforwading on iBox and re-add if not present
# To be run by powershell from Task Scheduler */10min with SYSTEM rights and arguments "-noprofile -executionpolicy bypass -file C:\WINDOWS\cond_portfwd.ps1"
# Version 1.0 - 2024 s.t.

# EDIT THIS - define IP and ports
$lclip = "127.0.0.1"
$lclport = "65535"
$2ndlclprt = ""
$rmtip = "127.0.0.2"
$rmtport = "65535"
$2ndrmtprt = ""

# check if run with admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))  
{  
  $arguments = "& '" +$myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

#test if the portforward is already active
if (Test-NetConnection $lclip -Port $lclport -WarningAction SilentlyContinue -InformationLevel Quiet) {
 Write-Host "got_response, $lclport is open"
} else {
#add rules
 Write-Host "add_rules $lclip : $lclport $rmtip : $rmtport"
 netsh interface portproxy reset
 netsh advfirewall firewall add rule name="PortProxy Custom 1" dir=in action=allow protocol=TCP localport=$lclport
 netsh interface portproxy add v4tov4 listenport=$lclport listenaddress=$lclip connectport=$rmtport connectaddress=$rmtip
 
 if($2ndrmtprt) {
  Write-Host "2nd port is defined, adding 2nd rule"
  netsh advfirewall firewall add rule name="PortProxy Custom 2" dir=in action=allow protocol=TCP localport=$2ndlclprt
  netsh interface portproxy add v4tov4 listenport=$2ndlclprt listenaddress=$lclip connectport=$2ndrmtport connectaddress=$rmtip
  }
}
##Write-Host "end"
##Start-Sleep 5
'@
Set-Content "$env:TEMP\cond_portfwd.ps1" $psfileToAdd

# create the scheduled task .xml file that will be "imported" in order to create the task
$xmlfileToAdd = @'
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2024-10-08T00:00:00.0000000</Date>
    <Author>Administrator</Author>
    <Description>Launch and maintain Port Forward</Description>
    <URI>\PortForward</URI>
  </RegistrationInfo>
  <Triggers>
    <BootTrigger>
      <Repetition>
        <Interval>PT10M</Interval>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <Enabled>true</Enabled>
    </BootTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-18</UserId>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
    <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Command>
      <Arguments>-noprofile -executionpolicy bypass -file C:\WINDOWS\cond_portfwd.ps1</Arguments>
    </Exec>
  </Actions>
</Task>
'@
Set-Content "$env:TEMP\PortForward.xml" $xmlfileToAdd

# start the deployment. first ask for some admin credentials valid on targets
$cred = Get-Credential -Message "Please enter admin credentials valid on target computers";
if($cred -isnot [PSCredential]) {Write-Host -ForegroundColor Red -BackgroundColor DarkBlue "No valid credentials provided. Exiting!" ; exit 1}
# copy the files to each target computer. no need to see the errors, we have our own errorreporting
$ErrorActionPreference= 'silentlycontinue'
foreach($line in Get-Content $env:TEMP\comps.txt) {
Write-Host -ForegroundColor Gray "`nStart running on $line"
$comp = New-PSSession -Credential $cred $line
if ($?) { Write-Host -ForegroundColor Green "Session to $comp established" }else{ Write-Host -ForegroundColor Red "Unable to connect to $line" }
Copy-Item -ToSession $comp $env:TEMP\cond_portfwd.ps1 -Destination C:\WINDOWS\cond_portfwd.ps1 -Force
if ($?) {  Write-Host -ForegroundColor Green ".ps1 file copied" }else{ Write-Host -ForegroundColor Red ".ps1 file NOT copied on $line" }
Copy-Item -ToSession $comp "$env:TEMP\PortForward.xml" -Destination "C:\WINDOWS\TEMP\PortForward.xml" -Force
if ($?) {  Write-Host -ForegroundColor Green ".xml file copied" }else{ Write-Host -ForegroundColor Red ".xml file NOT copied on $line" }
# create the scheduled task from the .xml file
Invoke-Command -ComputerName $line -Credential $cred { $Task = Get-Content "C:\WINDOWS\TEMP\PortForward.xml" -raw ; Register-ScheduledTask -Xml $Task -TaskName 'PortForward' -User SYSTEM -Force }
if ($?) {  Write-Host -ForegroundColor Green "Scheduledtask created"}else{ Write-Host -ForegroundColor Red "Scheduledtask NOT created on $line" }
}

# local cleanup
Remove-Item "$env:TEMP\comps.txt"
Remove-Item "$env:TEMP\PortForward.xml"
Remove-Item "$env:TEMP\cond_portfwd.ps1"

# reminder
Write-Host -ForegroundColor Yellow -BackgroundColor DarkBlue "`nOn each of the target computers please edit C:\WINDOWS\cond_portfwd.ps1"

exit

Saturday, November 16, 2024

Disable windows update

 @echo off
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v DoNotConnectToWindowsUpdateInternetLocations /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v AcceptTrustedPublisherCerts /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v DisableDualScan /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetProxyBehaviorForUpdateDetection /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v WUServer /t REG_MULTI_SZ /d https://localhost:8531 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v WUStatusServer /t REG_MULTI_SZ /d https://localhost:8531 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v UpdateServiceUrlAlternate /t REG_MULTI_SZ /d http://localhost:8005 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v FillEmptyContentUrls /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForDriverUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForFeatureUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForOtherUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForQualityUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v DoNotEnforceEnterpriseTLSCertPinningForUpdateDetection /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v ElevateNonAdmins /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v UseWUServer /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v NoAutoUpdate /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v AutoInstallMinorUpdates /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v DetectionFrequencyEnabled /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v RebootWarningTimeoutEnabled /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v RescheduleWaitTimeEnabled /t REG_DWORD /d 0 /f >NUL
sc config "UsoSvc" start= disabled >NUL
sc stop "UsoSvc" >NUL
sc config "WaaSMedicSvc" start= disabled >NUL
sc stop "WaaSMedicSvc" >NUL
sc config "wuauserv" start= demand >NUL
sc stop "wuauserv" >NUL
taskkill /IM wusa.exe >NUL
move /y C:\WINDOWS\system32\wusa.exe C:\WINDOWS\system32\wusa.org >NUL
copy /y true.exe C:\WINDOWS\system32\wusa.exe >NUL

Wednesday, October 16, 2024

Monday, July 15, 2024

ESP32-CAM serve video to multiple http clients

 // Multicam v.2.19

// ESP32 has two cores, APPlication and PROcess

#define APP_CPU 1
#define PRO_CPU 0

#include "src/OV2640.h"
#include <WiFi.h>
#include <WebServer.h>
#include <WiFiClient.h>
// we should disable bt
//#include <esp_bt.h>
#include <esp_wifi.h>
#include <esp_sleep.h>
#include <driver/rtc_io.h>
//disable brownout problems
#include "soc/soc.h"           
#include "soc/rtc_cntl_reg.h"

#define CAMERA_MODEL_AI_THINKER
//those are the GPIO pins for AI_THINKER - find yours if you have a different SOC
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
// wifi, because I'm too lazy to put it in a different file
#define SSID1 "my_WiFi"
#define PWD1 "myp455w0rd"

//init camera
OV2640 cam;

//init webserver
WebServer server(80);


// ===== rtos task handles =====
// Streaming is implemented with 3 tasks:
// handle client connections to the webserver
TaskHandle_t tMjpeg;
// handle getting picture frames from the camera and storing them locally
TaskHandle_t tCam;
// actually streaming frames to all connected clients
TaskHandle_t tStream;

// frameSync semaphore is used to prevent streaming buffer while is replaced with the next frame
SemaphoreHandle_t frameSync = NULL;

// Queue stores currently connected clients to whom we are streaming
QueueHandle_t streamingClients;

// We will try to achieve 15 FPS frame rate - for surveilllance, it is ok-ish...
const int FPS = 15;

// We will handle web client requests every 100 ms (10 Hz) - web can wait a bit
const int WSINTERVAL = 100;


// ======== Server Connection Handler Task ==========
void mjpegCB(void* pvParameters) {
  TickType_t xLastWakeTime;
  const TickType_t xFrequency = pdMS_TO_TICKS(WSINTERVAL);

  // Creating frame synchronization semaphore and initializing it
  frameSync = xSemaphoreCreateBinary();
  xSemaphoreGive(frameSync);

  // Creating a queue to track all connected clients
  streamingClients = xQueueCreate(10, sizeof(WiFiClient*));

  //=== Setup section  ===

  //  Creating RTOS task for grabbing frames from the camera
  xTaskCreatePinnedToCore(
    camCB,     // callback
    "cam",     // name
    4096,      // stacj size
    NULL,      // parameters
    2,         // priority
    &tCam,     // RTOS task handle
    APP_CPU);  // core

  //  Creating task to push the stream to all connected clients
  xTaskCreatePinnedToCore(
    streamCB,
    "strmCB",
    4 * 1024,
    NULL,  //(void*) handler,
    2,
    &tStream,
    APP_CPU);

  //  Registering webserver handling routines
  server.on("/mjpeg", HTTP_GET, handleJPGSstream);
  server.on("/jpeg", HTTP_GET, handleJPG);
  server.onNotFound(handleNotFound);

  //  Starting webserver
  server.begin();

  //=== loop() section  ====
  xLastWakeTime = xTaskGetTickCount();
  for (;;) {
    server.handleClient();

   // After every server client handling request, we let other tasks run and then pause
    taskYIELD();
    vTaskDelayUntil(&xLastWakeTime, xFrequency);
  }
}


// Commonly used variables:
volatile size_t camSize;  // size of the current frame, byte
volatile char* camBuf;    // pointer to the current frame


// ==== RTOS task to grab frames from the camera ====
void camCB(void* pvParameters) {

  TickType_t xLastWakeTime;

  //  A running interval associated with currently desired frame rate
  const TickType_t xFrequency = pdMS_TO_TICKS(1000 / FPS);

  // Mutex for the critical section of swithing the active frames around
  portMUX_TYPE xSemaphore = portMUX_INITIALIZER_UNLOCKED;

  //  Pointers to the 2 frames, their respective sizes and index of the current frame
  char* fbs[2] = { NULL, NULL };
  size_t fSize[2] = { 0, 0 };
  int ifb = 0;

  //=== loop() section  ===
  xLastWakeTime = xTaskGetTickCount();

  for (;;) {

    //  Grab a frame from the camera and query its size
    cam.run();
    size_t s = cam.getSize();

    //  If frame size is more that we have previously allocated - request  125% of the current frame space
    if (s > fSize[ifb]) {
      fSize[ifb] = s * 4 / 3;
      fbs[ifb] = allocateMemory(fbs[ifb], fSize[ifb]);
    }

    //  Copy current frame into local buffer
    char* b = (char*)cam.getfb();
    memcpy(fbs[ifb], b, s);

    //  Let other tasks run and wait until the end of the current frame rate interval (if any time left)
    taskYIELD();
    vTaskDelayUntil(&xLastWakeTime, xFrequency);

    //  Only switch frames around if no frame is currently being streamed to a client
    //  Wait on a semaphore until client operation completes
    xSemaphoreTake(frameSync, portMAX_DELAY);

    //  Do not allow interrupts while switching the current frame
    portENTER_CRITICAL(&xSemaphore);
    camBuf = fbs[ifb];
    camSize = s;
    ifb++;
    ifb &= 1;  // this should produce a 1, 0, 1, 0, 1 ... sequence
    portEXIT_CRITICAL(&xSemaphore);

    //  Let anyone waiting for a frame know that the frame is ready
    xSemaphoreGive(frameSync);

    //  Technically only needed once: let the streaming task know that we have at least one frame
    //  and it could start sending frames to the clients, if any
    xTaskNotifyGive(tStream);

    //  Immediately let other (streaming) tasks run
    taskYIELD();

    //  If streaming task has suspended itself (no active clients to stream to) there is no need to grab frames from the camera. We can save some power by suspending the tasks
    if (eTaskGetState(tStream) == eSuspended) {
      vTaskSuspend(NULL);  //NULL means "suspend yourself"
    }
  }
}


// ==== Memory allocator uses of PSRAM if present ====
char* allocateMemory(char* aPtr, size_t aSize) {

  //  Since current buffer is too small, free it
  if (aPtr != NULL) free(aPtr);

  size_t freeHeap = ESP.getFreeHeap();
  char* ptr = NULL;

  // If memory requested is more than 2/3 of the currently free heap, try PSRAM immediately
  if (aSize > freeHeap * 2 / 3) {
    if (psramFound() && ESP.getFreePsram() > aSize) {
      ptr = (char*)ps_malloc(aSize);
    }
  } else {
    //  Enough free heap - let's try allocating fast RAM as a buffer
    ptr = (char*)malloc(aSize);

    //  If allocation on the heap failed, let's give PSRAM one more chance:
    if (ptr == NULL && psramFound() && ESP.getFreePsram() > aSize) {
      ptr = (char*)ps_malloc(aSize);
    }
  }

  // Well, if the memory pointer is NULL, we were not able to allocate any memory, and that is the end. RESTART.
  if (ptr == NULL) {
    ESP.restart();
  }
  return ptr;
}


// ==== STREAMING ======
const char HEADER[] = "HTTP/1.1 200 OK\r\n"
                      "Access-Control-Allow-Origin: *\r\n"
                      "Content-Type: multipart/x-mixed-replace; boundary=123456789000000000000987654321\r\n";
const char BOUNDARY[] = "\r\n--123456789000000000000987654321\r\n";
const char CTNTTYPE[] = "Content-Type: image/jpeg\r\nContent-Length: ";
const int hdrLen = strlen(HEADER);
const int bdrLen = strlen(BOUNDARY);
const int cntLen = strlen(CTNTTYPE);


// ==== Handle connection request from clients ======
void handleJPGSstream(void) {
  //  Can only acommodate 10 clients. The limit is a default for WiFi connections
  if (!uxQueueSpacesAvailable(streamingClients)) return;


  //  Create a new WiFi Client object to keep track of this one
  WiFiClient* client = new WiFiClient();
  *client = server.client();

  //  Immediately send this client a header
  client->write(HEADER, hdrLen);
  client->write(BOUNDARY, bdrLen);

  // Push the client to the streaming queue
  xQueueSend(streamingClients, (void*)&client, 0);

  // Wake up streaming tasks if they were previously suspended:
  if (eTaskGetState(tCam) == eSuspended) vTaskResume(tCam);
  if (eTaskGetState(tStream) == eSuspended) vTaskResume(tStream);
}


// ==== Actually stream content to all connected clients ====
void streamCB(void* pvParameters) {
  char buf[16];
  TickType_t xLastWakeTime;
  TickType_t xFrequency;

  //  Wait until the first frame is captured - only after we have something to send
  ulTaskNotifyTake(pdTRUE,         /* Clear the notification value before exiting. */
                   portMAX_DELAY); /* Block indefinitely. */

  xLastWakeTime = xTaskGetTickCount();
  for (;;) {
    // Default assumption: we are running according to the FPS
    xFrequency = pdMS_TO_TICKS(1000 / FPS);

    //  Only send anything if there is someone watching
    UBaseType_t activeClients = uxQueueMessagesWaiting(streamingClients);
    if (activeClients) {
      // Adjust the period to the number of connected clients
      xFrequency /= activeClients;

      //  Since we are sending the same frame to everyone,
      //  pop a client from the the front of the queue
      WiFiClient* client;
      xQueueReceive(streamingClients, (void*)&client, 0);

      //  Check if this client is still connected.

      if (!client->connected()) {
        //  delete this client reference if it has disconnected
        //  and don't put it back on the queue anymore.
        delete client;
      } else {

        //  OK, this is an actively connected client.
        //  Let's grab a semaphore to prevent frame changes while we are serving the current
        xSemaphoreTake(frameSync, portMAX_DELAY);

        client->write(CTNTTYPE, cntLen);
        sprintf(buf, "%d\r\n\r\n", camSize);
        client->write(buf, strlen(buf));
        client->write((char*)camBuf, (size_t)camSize);
        client->write(BOUNDARY, bdrLen);

        // Since this client is still connected, push it to the end
        // of the queue for further processing
        xQueueSend(streamingClients, (void*)&client, 0);

        //  The frame has been served. Release the semaphore and let other tasks run.
        //  If there is a frame switch ready, it will happen now in between frames
        xSemaphoreGive(frameSync);
        taskYIELD();
      }
    } else {
      //  Since there are no connected clients, there is no reason to waste power running
      vTaskSuspend(NULL);
    }
    //  Let other tasks run after serving every client
    taskYIELD();
    vTaskDelayUntil(&xLastWakeTime, xFrequency);
  }
}


const char JHEADER[] = "HTTP/1.1 200 OK\r\n"
                       "Content-disposition: inline; filename=capture.jpg\r\n"
                       "Content-type: image/jpeg\r\n\r\n";
const int jhdLen = strlen(JHEADER);


// ==== Serve up one JPEG frame =========
void handleJPG(void) {
  WiFiClient client = server.client();

  if (!client.connected()) return;
  cam.run();
  client.write(JHEADER, jhdLen);
  client.write((char*)cam.getfb(), cam.getSize());
}


// ==== Handle invalid URL requests =====
void handleNotFound() {
  String message = "This camera runs fine, you are asking the wrong question!\n

you should only ask for /mjpeg or /jpeg here\n\n";
  message += "URL: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  server.send(200, "text / plain", message);
}


// we're at the classic setup function


void setup() {
  //disable brownout detector
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);  

  // Configure the camera
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;

  // Frame parameters: UXGA is ok if we only want a decent framerate of 15fps
    config.frame_size = FRAMESIZE_UXGA;
  //  config.frame_size = FRAMESIZE_SVGA;
  //  config.frame_size = FRAMESIZE_VGA;
  //  config.frame_size = FRAMESIZE_QVGA;
  config.jpeg_quality = 12;
  config.fb_count = 2;

  if (cam.init(config) != ESP_OK) {
    delay(10000);
    ESP.restart();
  }


  //  Configure and connect to WiFi
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID1, PWD1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  // Start main streaming RTOS task
  xTaskCreatePinnedToCore(
    mjpegCB,
    "mjpeg",
    4 * 1024,
    NULL,
    2,
    &tMjpeg,
    APP_CPU);
}


// variables for wifi reconnect
unsigned long previousMillis = 0;
unsigned long interval = 30000;

void loop() {
  vTaskDelay(1000);
  //Check Wifi status
  unsigned long currentMillis = millis();
  // if WiFi is down, try reconnecting every interval mseconds
  if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >= interval)) {
    WiFi.disconnect();
    vTaskDelay(1000);
    WiFi.reconnect();
    previousMillis = currentMillis;
  }
}

Saturday, March 23, 2024

Create a task that removes "shutdown task if running longer than" from other tasks

$batchfileToAdd = @'
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set srvlist=UDP_SERVER_CHAN0,UDP_CANBUS_SERVER,UDP_UART_SERVER_CHAN0
for %%i in (%srvlist%) do (
powershell "$task = get-ScheduledTask -taskname %%i ; $Task.Settings.ExecutionTimeLimit = 'PT0H' ; set-ScheduledTask $task"
)
ENDLOCAL
exit /B
'@
Add-Content "C:\CAB\chgtskshtdn.bat" $batchfileToAdd

$xmlfileToAdd = @'
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2024-02-20T09:21:14.0904858</Date>
    <Author>myself</Author>
    <Description>Uncheck "shutdown task is running longer than" for the tasks UDP_SERVER_CHAN0,UDP_CANBUS_SERVER,UDP_UART_SERVER_CHAN0</Description>
    <URI>\Keep Tasks running</URI>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT60M</Interval>
        <Duration>P1D</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2024-02-20T09:15:39</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>false</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\CAB\chgtskshtdn.bat</Command>
    </Exec>
  </Actions>
</Task>
'@
Add-Content "C:\CAB\KeepTasksRunning.xml" $xmlfileToAdd

$complstfileToAdd = @'

cmp1
cmp2
cmp3
cmp4

'@
Add-Content "C:\tmp\complst.txt" $complstfileToAdd

$cred = Get-Credential;
foreach($line in Get-Content C:\tmp\complst.txt) {
Write-Host "Running on $line"
$comp = New-PSSession -Credential $cred $line
Write-Host "Session to $comp established"
Copy-Item -ToSession $comp C:\CAB\chgtskshtdn.bat -Destination C:\CAB\chgtskshtdn.bat
Write-Host "bat file copied"
Copy-Item -ToSession $comp "C:\CAB\KeepTasksRunning.xml" -Destination "C:\CAB\KeepTasksRunning.xml"
Write-Host "xml file copied"
Invoke-Command -ComputerName $line -Credential $cred { $Task = Get-Content "C:\CAB\KeepTasksRunning.xml" -raw ; Register-ScheduledTask -Xml $Task -TaskName 'Keep Tasks Running' -User adminuser -Password "som3p455wrd" -Force }
Write-Host "task created"
}

Remove-Item "C:\tmp\complst.txt"
Remove-Item "C:\CAB\KeepTasksRunning.xml"
Remove-Item "C:\CAB\chgtskshtdn.bat"

exit