repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
alexandergr/INFView | INFViewExample/AppDelegate.h | <reponame>alexandergr/INFView
//
// AppDelegate.h
// INFViewExample
//
// Created by Alexander on 2/1/18.
// Copyright © 2018 Alexander. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
alexandergr/INFView | INFViewExample/ViewController.h | //
// ViewController.h
// INFViewExample
//
// Created by Alexander on 2/1/18.
// Copyright © 2018 Alexander. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
wangxinzhi0/stream-engine-docs | samples/timesync_thread.h | <filename>samples/timesync_thread.h
#ifndef sample_timesync_thread_h
#define sample_timesync_thread_h
typedef struct thread_context_t thread_context_t;
typedef struct tobii_device_t tobii_device_t;
thread_context_t* timesync_thread_create( tobii_device_t* device );
void timesync_thread_destroy( thread_context_t* context );
#endif // sample_timesync_thread_h
|
wangxinzhi0/stream-engine-docs | samples/main_loop_linux.h | #ifndef sample_main_loop_linux_h
#define sample_main_loop_linux_h
typedef struct tobii_device_t tobii_device_t;
void main_loop( tobii_device_t* device, void ( *action )( void* context ), void* context );
#endif // sample_main_loop_linux_h
|
wangxinzhi0/stream-engine-docs | samples/wearable_game_loop_sample_windows.c | #include <tobii/tobii.h>
#include <tobii/tobii_wearable.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#pragma warning( push )
#pragma warning( disable: 4255 4668 )
#include <windows.h>
#pragma warning( pop )
static void wearable_callback( tobii_wearable_consumer_data_t const* wearable_data, void* user_data )
{
// Store the latest wearable data in the supplied storage
tobii_wearable_consumer_data_t* wearable_data_storage = (tobii_wearable_consumer_data_t*) user_data;
*wearable_data_storage = *wearable_data;
}
struct url_receiver_context_t
{
char** urls;
int capacity;
int count;
};
static void url_receiver( char const* url, void* user_data )
{
// The memory context is passed through the user_data void pointer
struct url_receiver_context_t* context = (struct url_receiver_context_t*) user_data;
// Allocate more memory if maximum capacity has been reached
if( context->count >= context->capacity )
{
context->capacity *= 2;
char** urls = (char**) realloc( context->urls, sizeof( char* ) * context->capacity );
if( !urls )
{
fprintf( stderr, "Allocation failed\n" );
return;
}
context->urls = urls;
}
// Copy the url string input parameter to allocated memory
size_t url_length = strlen( url ) + 1;
context->urls[ context->count ] = malloc( url_length );
if( !context->urls[ context->count ] )
{
fprintf( stderr, "Allocation failed\n" );
return;
}
memcpy( context->urls[ context->count++ ], url, url_length );
}
struct device_list_t
{
char** urls;
int count;
};
static struct device_list_t list_devices( tobii_api_t* api )
{
struct device_list_t list = { NULL, 0 };
// Create a memory context that can be used by the url receiver callback
struct url_receiver_context_t url_receiver_context;
url_receiver_context.count = 0;
url_receiver_context.capacity = 16;
url_receiver_context.urls = (char**) malloc( sizeof( char* ) * url_receiver_context.capacity );
if( !url_receiver_context.urls )
{
fprintf( stderr, "Allocation failed\n" );
return list;
}
// Enumerate the connected devices, connected devices will be stored in the supplied memory context
tobii_error_t error = tobii_enumerate_local_device_urls( api, url_receiver, &url_receiver_context );
if( error != TOBII_ERROR_NO_ERROR ) fprintf( stderr, "Failed to enumerate devices.\n" );
list.urls = url_receiver_context.urls;
list.count = url_receiver_context.count;
return list;
}
static void free_device_list( struct device_list_t* list )
{
for( int i = 0; i < list->count; ++i )
free( list->urls[ i ] );
free( list->urls );
}
static char const* select_device( struct device_list_t* devices )
{
int tmp = 0, selection = 0;
// Present the available devices and loop until user has selected a valid device
while( selection < 1 || selection > devices->count)
{
printf( "\nSelect a device\n\n" );
for( int i = 0; i < devices->count; ++i ) printf( "%d. %s\n", i + 1, devices->urls[ i ] ) ;
if( scanf( "%d", &selection ) <= 0 ) while( ( tmp = getchar() ) != '\n' && tmp != EOF );
}
return devices->urls[ selection - 1 ];
}
struct thread_context_t
{
tobii_device_t* device;
HANDLE reconnect_event; // Used to signal that a reconnect is needed
HANDLE timesync_event; // Timer event used to signal that time synchronization is needed
HANDLE exit_event; // Used to signal that the background thead should exit
volatile LONG is_reconnecting;
};
static DWORD WINAPI reconnect_and_timesync_thread( LPVOID param )
{
struct thread_context_t* context = (struct thread_context_t*) param;
HANDLE objects[ 3 ];
objects[ 0 ] = context->reconnect_event;
objects[ 1 ] = context->timesync_event;
objects[ 2 ] = context->exit_event;
for( ; ; )
{
// Block here, waiting for one of the three events.
DWORD result = WaitForMultipleObjects( 3, objects, FALSE, INFINITE );
if( result == WAIT_OBJECT_0 ) // Handle reconnect event
{
tobii_error_t error;
// Run reconnect loop until connection succeeds or the exit event occurs
while( ( error = tobii_device_reconnect( context->device ) ) != TOBII_ERROR_NO_ERROR )
{
if( error != TOBII_ERROR_CONNECTION_FAILED )
fprintf( stderr, "Reconnection failed: %s.\n", tobii_error_message( error ) );
// Blocking waiting for exit event, timeout after 250 ms and retry reconnect
result = WaitForSingleObject( context->exit_event, 250 ); // Retry every quarter of a second
if( result == WAIT_OBJECT_0 )
return 0; // exit thread
}
InterlockedExchange( &context->is_reconnecting, 0L );
}
else if( result == WAIT_OBJECT_0 + 1 ) // Handle timesync event
{
tobii_error_t error = tobii_update_timesync( context->device );
LARGE_INTEGER due_time;
LONGLONG const timesync_update_interval = 300000000LL; // Time sync every 30 s
LONGLONG const timesync_retry_interval = 1000000LL; // Retry time sync every 100 ms
due_time.QuadPart = ( error == TOBII_ERROR_NO_ERROR ) ? -timesync_update_interval : -timesync_retry_interval;
// Re-schedule timesync event
SetWaitableTimer( context->timesync_event, &due_time, 0, NULL, NULL, FALSE );
}
else if( result == WAIT_OBJECT_0 + 2 ) // Handle exit event
{
// Exit requested, exiting the thread
return 0;
}
}
}
static void log_func( void* log_context, tobii_log_level_t level, char const* text )
{
CRITICAL_SECTION* log_mutex = (CRITICAL_SECTION*)log_context;
EnterCriticalSection( log_mutex );
if( level == TOBII_LOG_LEVEL_ERROR )
fprintf( stderr, "Logged error: %s\n", text );
LeaveCriticalSection( log_mutex );
}
int wearable_game_loop_sample_main( void )
{
// Initialize critical section, used for thread synchronization in the log function
static CRITICAL_SECTION log_mutex;
InitializeCriticalSection( &log_mutex );
tobii_custom_log_t custom_log = { &log_mutex, log_func };
tobii_api_t* api;
tobii_error_t error = tobii_api_create( &api, NULL, &custom_log );
if( error != TOBII_ERROR_NO_ERROR )
{
fprintf( stderr, "Failed to initialize the Tobii Stream Engine API.\n" );
DeleteCriticalSection( &log_mutex );
return 1;
}
struct device_list_t devices = list_devices( api );
if( devices.count == 0 )
{
fprintf( stderr, "No stream engine compatible device(s) found.\n" );
free_device_list( &devices );
tobii_api_destroy( api );
DeleteCriticalSection( &log_mutex );
return 1;
}
char const* selected_device = devices.count == 1 ? devices.urls[ 0 ] : select_device( &devices );
printf( "Connecting to %s.\n", selected_device );
tobii_device_t* device;
error = tobii_device_create( api, selected_device, TOBII_FIELD_OF_USE_INTERACTIVE, &device );
free_device_list( &devices );
if( error != TOBII_ERROR_NO_ERROR )
{
fprintf( stderr, "Failed to initialize the device with url %s.\n", selected_device );
tobii_api_destroy( api );
DeleteCriticalSection( &log_mutex );
return 1;
}
tobii_wearable_consumer_data_t latest_wearable_data;
latest_wearable_data.timestamp_us = 0LL;
latest_wearable_data.gaze_direction_combined_validity = TOBII_VALIDITY_INVALID;
latest_wearable_data.gaze_origin_combined_validity = TOBII_VALIDITY_INVALID;
// Start subscribing to wearable data, in this sample we supply a tobii_wearable_data_t variable to store
// latest value.
error = tobii_wearable_consumer_data_subscribe( device, wearable_callback, &latest_wearable_data );
if( error != TOBII_ERROR_NO_ERROR )
{
fprintf( stderr, "Failed to subscribe to gaze stream.\n" );
tobii_device_destroy( device );
tobii_api_destroy( api );
DeleteCriticalSection( &log_mutex );
return 1;
}
// Create event objects used for inter thread signaling
HANDLE reconnect_event = CreateEvent( NULL, FALSE, FALSE, NULL );
HANDLE timesync_event = CreateWaitableTimer( NULL, TRUE, NULL );
HANDLE exit_event = CreateEvent( NULL, FALSE, FALSE, NULL );
if( reconnect_event == NULL || timesync_event == NULL || exit_event == NULL )
{
fprintf( stderr, "Failed to create event objects.\n" );
tobii_device_destroy( device );
tobii_api_destroy( api );
DeleteCriticalSection( &log_mutex );
return 1;
}
struct thread_context_t thread_context;
thread_context.device = device;
thread_context.reconnect_event = reconnect_event;
thread_context.timesync_event = timesync_event;
thread_context.exit_event = exit_event;
thread_context.is_reconnecting = 0;
// Create and run the reconnect and timesync thread
HANDLE thread_handle = CreateThread( NULL, 0U, reconnect_and_timesync_thread, &thread_context, 0U, NULL );
if( thread_handle == NULL )
{
fprintf( stderr, "Failed to create reconnect_and_timesync thread.\n" );
tobii_device_destroy( device );
tobii_api_destroy( api );
DeleteCriticalSection( &log_mutex );
return 1;
}
LARGE_INTEGER due_time;
LONGLONG const timesync_update_interval = 300000000LL; // time sync every 30 s
due_time.QuadPart = -timesync_update_interval;
// Schedule the time synchronization event
BOOL timer_error = SetWaitableTimer( thread_context.timesync_event, &due_time, 0, NULL, NULL, FALSE );
if( timer_error == FALSE )
{
fprintf( stderr, "Failed to schedule timer event.\n" );
tobii_device_destroy( device );
tobii_api_destroy( api );
DeleteCriticalSection( &log_mutex );
return 1;
}
// Main loop
while( GetAsyncKeyState( VK_ESCAPE ) == 0 )
{
Sleep( 10 ); // Perform work i.e game loop code here - let's emulate it with a sleep
// Only enter the next code section if not in reconnecting state
if( !InterlockedCompareExchange( &thread_context.is_reconnecting, 0L, 0L ) )
{
error = tobii_device_process_callbacks( device );
// TODO: Handle device_error
if( error == TOBII_ERROR_CONNECTION_FAILED )
{
// Change state and signal that reconnect is needed.
InterlockedExchange( &thread_context.is_reconnecting, 1L );
SetEvent( thread_context.reconnect_event );
}
else if( error != TOBII_ERROR_NO_ERROR )
{
fprintf( stderr, "tobii_device_process_callbacks failed: %s.\n", tobii_error_message( error ) );
break;
}
printf( "Gaze Direction: T %" PRIu64, latest_wearable_data.timestamp_us );
if( latest_wearable_data.gaze_direction_combined_validity == TOBII_VALIDITY_VALID )
{
printf( "\tCombined {x:% 2.2f, y:% 2.2f, z:% 2.2f} ",
latest_wearable_data.gaze_direction_combined_normalized_xyz[ 0 ],
latest_wearable_data.gaze_direction_combined_normalized_xyz[ 1 ],
latest_wearable_data.gaze_direction_combined_normalized_xyz[ 2 ] );
}
else
{
printf( "\tCombined INVALID\t\t\t" );
}
printf( "\n" );
}
Sleep( 6 ); // Perform work which needs eye tracking data and the rest of the game loop
}
// Signal reconnect and timesync thread to exit and clean up event objects.
SetEvent( thread_context.exit_event );
WaitForSingleObject( thread_handle, INFINITE );
CloseHandle( thread_handle );
CloseHandle( timesync_event );
CloseHandle( exit_event );
CloseHandle( reconnect_event );
error = tobii_wearable_consumer_data_unsubscribe( device );
if( error != TOBII_ERROR_NO_ERROR )
fprintf( stderr, "Failed to unsubscribe from wearable data stream.\n" );
error = tobii_device_destroy( device );
if( error != TOBII_ERROR_NO_ERROR )
fprintf( stderr, "Failed to destroy device.\n" );
error = tobii_api_destroy( api );
if( error != TOBII_ERROR_NO_ERROR )
fprintf( stderr, "Failed to destroy API.\n" );
DeleteCriticalSection( &log_mutex );
return 0;
}
|
n-t-roff/ex-3.2 | popen.c | /* Copyright (c) 1979 Regents of the University of California */
#include "stdio.h"
#define tst(a,b) (*mode == 'r' ? (b) : (a))
FILE *
popen(cmd,mode)
char *cmd;
char *mode;
{
register i;
FILE *fptr;
struct pstruct {
int reader;
int writer;
} str;
if (pipe(&str)<0) return NULL;
if ((i=fork())==0) {
close(tst(str.writer,str.reader));
close(tst(0,1));
dup(tst(str.reader,str.writer));
close(tst(str.reader,str.writer));
execl("/bin/sh","sh","-c",cmd,0);
exit(1);
}
if (i== -1) return NULL;
close(tst(str.reader,str.writer));
fptr=fopen("/dev/null",tst("w","r"));
setbuf(fptr,NULL);
fptr->_file=tst(str.writer,str.reader);
return fptr;
}
pclose(ptr)
FILE *ptr;
{
int st;
fclose(ptr);
wait(&st);
return st;
}
|
n-t-roff/ex-3.2 | ex_cmds2.c | <reponame>n-t-roff/ex-3.2
/* Copyright (c) 1979 Regents of the University of California */
#include "ex.h"
#include "ex_argv.h"
#include "ex_temp.h"
#include "ex_tty.h"
#include "ex_vis.h"
extern bool pflag, nflag;
extern int poffset;
static void error0(void);
static void setflav(void);
/*
* Subroutines for major command loop.
*/
/*
* Is there a single letter indicating a named buffer next?
*/
int
cmdreg(void)
{
register int c = 0;
register int wh = skipwh();
if (wh && isalpha(peekchar()))
c = ex_getchar();
return (c);
}
/*
* Tell whether the character ends a command
*/
int
endcmd(int ch)
{
switch (ch) {
case '\n':
case EOF:
endline = 1;
return (1);
case '|':
endline = 0;
return (1);
}
return (0);
}
/*
* Insist on the end of the command.
*/
void
eol(void)
{
if (!skipend())
error("Extra chars|Extra characters at end of command");
ignnEOF();
}
void
error(char *s) {
ierror(s, 0);
}
/*
* Print out the message in the error message file at str,
* with i an integer argument to printf.
*/
/*VARARGS2*/
void
ierror(char *str, int i)
{
error0();
imerror(str, i);
error1(str);
}
/*
* Rewind the argument list.
*/
void
erewind(void)
{
argc = argc0;
argv = argv0;
args = args0;
if (argc > 1 && !hush) {
ex_printf(mesg("%d files@to edit"), argc);
if (inopen)
ex_putchar(' ');
else
putNFL();
}
}
/*
* Guts of the pre-printing error processing.
* If in visual and catching errors, then we dont mung up the internals,
* just fixing up the echo area for the print.
* Otherwise we reset a number of externals, and discard unused input.
*/
static void
error0(void)
{
if (vcatch) {
if (splitw == 0)
fixech();
if (!SO || !SE)
dingdong();
return;
}
if (input) {
input = strend(input) - 1;
if (*input == '\n')
setlastchar('\n');
input = 0;
}
setoutt();
flush();
resetflav();
if (laste) {
laste = 0;
ex_sync();
}
if (!SO || !SE)
dingdong();
if (inopen) {
/*
* We are coming out of open/visual ungracefully.
* Restore COLUMNS, undo, and fix tty mode.
*/
COLUMNS = OCOLUMNS;
undvis();
ostop(normf);
putpad(VE);
putpad(KE);
putnl();
}
inopen = 0;
holdcm = 0;
}
/*
* Post error printing processing.
* Close the i/o file if left open.
* If catching in visual then throw to the visual catch,
* else if a child after a fork, then exit.
* Otherwise, in the normal command mode error case,
* finish state reset, and throw to top.
*/
void
error1(char *str)
{
bool die;
if (io > 0) {
close(io);
io = -1;
}
die = (getpid() != ppid); /* Only children die */
if (vcatch && !die) {
inglobal = 0;
vglobp = vmacp = 0;
inopen = 1;
vcatch = 0;
fixol();
longjmp(vreslab,1);
}
if (str && !vcatch)
putNFL();
if (die)
exit(1);
lseek(0, 0L, SEEK_END);
if (inglobal)
setlastchar('\n');
inglobal = 0;
globp = 0;
while (lastchar() != '\n' && lastchar() != EOF)
ignchar();
ungetchar(0);
endline = 1;
reset();
}
void
fixol(void)
{
if (Outchar != vputchar) {
flush();
if (state == ONEOPEN || state == HARDOPEN)
outline = destline = 0;
Outchar = vputchar;
vcontin(1);
} else {
if (destcol)
vclreol();
vclean();
}
}
/*
* Does an ! character follow in the command stream?
*/
int
exclam(void)
{
if (peekchar() == '!') {
ignchar();
return (1);
}
return (0);
}
/*
* Make an argument list for e.g. next.
*/
void
makargs(void)
{
glob(&frob);
argc0 = frob.argc0;
argv0 = frob.argv;
args0 = argv0[0];
erewind();
}
/*
* Advance to next file in argument list.
*/
void
next(void)
{
if (argc == 0)
error("No more files@to edit");
morargc = argc;
if (savedfile[0])
CP(altfile, savedfile);
CP(savedfile, args);
argc--;
args = argv ? *++argv : strend(args) + 1;
}
/*
* Eat trailing flags and offsets after a command,
* saving for possible later post-command prints.
*/
void
ex_newline(void)
{
register int c;
resetflav();
for (;;) {
c = ex_getchar();
switch (c) {
case '^':
case '-':
poffset--;
break;
case '+':
poffset++;
break;
case 'l':
listf++;
break;
case '#':
nflag++;
break;
case 'p':
listf = 0;
break;
case ' ':
case '\t':
continue;
default:
if (!endcmd(c))
serror("Extra chars|Extra characters at end of \"%s\" command", Command);
if (c == EOF)
ungetchar(c);
setflav();
return;
}
pflag++;
}
}
/*
* Before quit or respec of arg list, check that there are
* no more files in the arg list.
*/
void
nomore(void)
{
if (argc == 0 || morargc == argc)
return;
morargc = argc;
imerror("%d more file", argc);
serror("%s@to edit", plural((long) argc));
}
/*
* Before edit of new file check that either an ! follows
* or the file has not been changed.
*/
int
quickly(void)
{
if (exclam())
return (1);
if (chng && dol > zero) {
/*
chng = 0;
*/
xchng = 0;
serror("No write@since last change (:%s! overrides)", Command);
}
return (0);
}
/*
* Reset the flavor of the output to print mode with no numbering.
*/
void
resetflav(void)
{
if (inopen)
return;
listf = 0;
nflag = 0;
pflag = 0;
poffset = 0;
setflav();
}
/*
* Print an error message with a %s type argument to printf.
* Message text comes from error message file.
*/
void
serror(char *str, char *cp)
{
error0();
smerror(str, cp);
error1(str);
}
/*
* Set the flavor of the output based on the flags given
* and the number and list options to either number or not number lines
* and either use normally decoded (ARPAnet standard) characters or list mode,
* where end of lines are marked and tabs print as ^I.
*/
static void
setflav(void)
{
if (inopen)
return;
setnumb(nflag || value(NUMBER));
setlist(listf || value(LIST));
setoutt();
}
/*
* Skip white space and tell whether command ends then.
*/
int
skipend(void)
{
pastwh();
return (endcmd(peekchar()));
}
/*
* Set the command name for non-word commands.
*/
void
tailspec(int c)
{
static char foocmd[2];
foocmd[0] = c;
Command = foocmd;
}
/*
* Try to read off the rest of the command word.
* If alphabetics follow, then this is not the command we seek.
*/
void
tail(char *comm)
{
tailprim(comm, 1, 0);
}
void
tail2of(char *comm)
{
tailprim(comm, 2, 0);
}
char tcommand[20];
void
tailprim(char *comm, int i, bool notinvis)
{
register char *cp;
register int c;
Command = comm;
for (cp = tcommand; i > 0; i--)
*cp++ = *comm++;
while (*comm && peekchar() == *comm)
*cp++ = ex_getchar(), comm++;
c = peekchar();
if (notinvis || isalpha(c)) {
/*
* Of the trailing lp funny business, only dl and dp
* survive the move from ed to ex.
*/
if (tcommand[0] == 'd' && any(c, "lp"))
goto ret;
if (tcommand[0] == 's' && any(c, "gcr"))
goto ret;
while (cp < &tcommand[19] && isalpha(peekchar()))
*cp++ = ex_getchar();
*cp = 0;
if (notinvis)
serror("What?|%s: No such command from open/visual", tcommand);
else
serror("What?|%s: Not an editor command", tcommand);
}
ret:
*cp = 0;
}
/*
* Continue after a shell escape from open/visual.
*/
void
vcontin(bool ask)
{
if (vcnt > 0)
vcnt = -vcnt;
if (inopen) {
if (state != VISUAL) {
/*
vtube[WECHO][0] = '*';
vnfl();
*/
return;
}
if (ask) {
merror("[Hit return to continue] ");
flush();
}
#ifndef CBREAK
vraw();
#endif
if (ask) {
/*
* Gobble ^Q/^S since the tty driver should be eating
* them (as far as the user can see)
*/
while (peekkey() == CTRL('Q') || peekkey() == CTRL('S'))
ignore(getkey());
if(getkey() == ':')
ungetkey(':');
}
putpad(VS);
putpad(KS);
}
}
/*
* Put out a newline (before a shell escape)
* if in open/visual.
*/
void
vnfl(void)
{
if (inopen) {
if (state != VISUAL && state != CRTOPEN && destline <= WECHO)
vclean();
else
vmoveitup(1, 0);
vgoto(WECHO, 0);
vclrbyte(vtube[WECHO], WCOLS);
putpad(VE);
putpad(KE);
}
flush();
}
|
n-t-roff/ex-3.2 | ex_vars.h | <reponame>n-t-roff/ex-3.2
#define AUTOINDENT 0
#define AUTOPRINT 1
#define AUTOWRITE 2
#define BEAUTIFY 3
#define DIRECTORY 4
#define EDCOMPATIBLE 5
#define ERRORBELLS 6
#define HARDTABS 7
#define IGNORECASE 8
#define LISP 9
#define LIST 10
#define MAGIC 11
#define MAPINPUT 12
#define NUMBER 13
#define OPEN 14
#define OPTIMIZE 15
#define PARAGRAPHS 16
#define PROMPT 17
#define REDRAW 18
#define REPORT 19
#define SCROLL 20
#define SECTIONS 21
#define SHELL 22
#define SHIFTWIDTH 23
#define SHOWMATCH 24
#define SLOWOPEN 25
#define TABSTOP 26
#define TTYTYPE 27
#define TERM 28
#define TERSE 29
#define WARN 30
#define WINDOW 31
#define WRAPSCAN 32
#define WRAPMARGIN 33
#define WRITEANY 34
#define NOPTS 35
|
n-t-roff/ex-3.2 | ex_tty.c | /* Copyright (c) 1979 Regents of the University of California */
#include "ex.h"
#include "ex_tty.h"
/*
* Terminal type initialization routines,
* and calculation of flags at entry or after
* a shell escape which may change them.
*/
/* short ospeed = -1; */
static void zap(void);
void
gettmode(void)
{
if (tcgetattr(1, &tty) < 0)
return;
ex_ospeed = cfgetospeed(&tty);
value(SLOWOPEN) = ex_ospeed < B1200;
normf = tty;
#ifdef IUCLC
UPPERCASE = (tty.c_iflag & IUCLC) != 0;
#endif
#ifdef TAB3
GT = (tty.c_oflag & TABDLY) != TAB3 && !XT;
#endif
NONL = (tty.c_oflag & ONLCR) == 0;
}
char *xPC;
char **sstrs[] = {
&AL, &BC, &BT, &CD, &CE, &CL, &CM, &DC, &DL, &DM, &DO, &ED, &EI,
&F0, &F1, &F2, &F3, &F4, &F5, &F6, &F7, &F8, &F9,
&HO, &IC, &IM, &IP, &KD, &KE, &KH, &KL, &KR, &KS, &KU, &LL,
&ND, &xPC, &SE, &SF, &SO, &SR, &TA, &TE, &TI, &UP, &VB, &VS, &VE
};
bool *sflags[] = {
&AM, &BS, &DA, &DB, &EO, &HC, &HZ, &IN, &MI, &NC, &OS, &UL, &XN, &XT
};
char **fkeys[10] = {
&F0, &F1, &F2, &F3, &F4, &F5, &F6, &F7, &F8, &F9
};
void
setterm(char *type)
{
char *cgoto();
register int unknown, i;
register int l;
char ltcbuf[TCBUFSIZE];
if (type[0] == 0)
type = "xx";
unknown = 0;
putpad(TE);
if (tgetent(ltcbuf, type) != 1) {
unknown++;
CP(genbuf, "xx|dumb:");
}
i = EX_LINES = tgetnum("li");
if (EX_LINES <= 5)
EX_LINES = 24;
l = EX_LINES;
if (ex_ospeed < B1200)
l /= 2;
else if (ex_ospeed < B2400)
l = (l * 2) / 3;
aoftspace = tspace;
zap();
/*
* Initialize keypad arrow keys.
*/
arrows[0].cap = KU; arrows[0].mapto = "k"; arrows[0].descr = "up";
arrows[1].cap = KD; arrows[1].mapto = "j"; arrows[1].descr = "down";
arrows[2].cap = KL; arrows[2].mapto = "h"; arrows[2].descr = "left";
arrows[3].cap = KR; arrows[3].mapto = "l"; arrows[3].descr = "right";
arrows[4].cap = KH; arrows[4].mapto = "H"; arrows[4].descr = "home";
options[WINDOW].ovalue = options[WINDOW].odefault = l - 1;
if (defwind) options[WINDOW].ovalue = defwind;
options[SCROLL].ovalue = options[SCROLL].odefault = HC ? 11 : ((l-1) / 2);
COLUMNS = tgetnum("co");
if (COLUMNS <= 20)
COLUMNS = 1000;
if (!CM || cgoto()[0] == 'O') /* OOPS */
CA = 0, CM = 0;
else
CA = 1, costCM = strlen(tgoto(CM, 8, 10));
PC = xPC ? xPC[0] : 0;
aoftspace = tspace;
CP(ttytype, longname(genbuf, type));
if (i <= 0)
EX_LINES = 2;
/* proper strings to change tty type */
#ifdef notdef
/* Taken out because we don't allow it. See ex_set.c for reasons. */
if (inopen)
putpad(VE);
#endif
termreset();
gettmode();
value(REDRAW) = AL && DL;
value(OPTIMIZE) = !CA && !GT;
if (unknown)
serror("%s: Unknown terminal type", type);
}
static void
zap(void)
{
register char *namp;
register bool **fp;
register char ***sp;
namp = "ambsdadbeohchzinmincosulxnxt";
fp = sflags;
do {
*(*fp++) = tgetflag(namp);
namp += 2;
} while (*namp);
namp = "albcbtcdceclcmdcdldmdoedeik0k1k2k3k4k5k6k7k8k9hoicimipkdkekhklkrkskullndpcsesfsosrtatetiupvbvsve";
sp = sstrs;
do {
*(*sp++) = tgetstr(namp, &aoftspace);
namp += 2;
} while (*namp);
}
char *
longname(char *bp, char *def)
{
register char *cp;
while (*bp && *bp != ':' && *bp != '|')
bp++;
if (*bp == '|') {
bp++;
cp = bp;
while (*cp && *cp != ':' && *cp != '|')
cp++;
*cp = 0;
return (bp);
}
return (def);
}
char *
fkey(int i)
{
if (0 <= i && i <= 9)
return(*fkeys[i]);
else
return(NOSTR);
}
|
n-t-roff/ex-3.2 | ex_vput.c | /* Copyright (c) 1979 Regents of the University of California */
#include "ex.h"
#include "ex_tty.h"
#include "ex_vis.h"
/*
* Deal with the screen, clearing, cursor positioning, putting characters
* into the screen image, and deleting characters.
* Really hard stuff here is utilizing insert character operations
* on intelligent terminals which differs widely from terminal to terminal.
*/
static void vmaktop(int, char *);
static void vneedpos(int);
static void vnpins(int);
static void godm(void);
static void enddm(void);
static void vgotab(void);
static void vishft(void);
static void viin(int);
void
vclear(void)
{
#ifdef ADEBUG
if (trace)
tfixnl(), fprintf(trace, "------\nvclear\n");
#endif
tputs(CL, EX_LINES, putch);
destcol = 0;
outcol = 0;
destline = 0;
outline = 0;
if (inopen)
vclrbyte(vtube0, WCOLS * (WECHO - ZERO + 1));
}
/*
* Clear memory.
*/
void
vclrbyte(char *cp, int i)
{
if (i > 0)
do
*cp++ = 0;
while (--i != 0);
}
/*
* Clear a physical display line, high level.
*/
void
vclrlin(int l, line *tp)
{
vigoto(l, 0);
if ((hold & HOLDAT) == 0)
ex_putchar(tp > dol ? ((UPPERCASE || HZ) ? '^' : '~') : '@');
if (state == HARDOPEN)
sethard();
vclreol();
}
/*
* Clear to the end of the current physical line
*/
void
vclreol(void)
{
register int i, j;
register char *tp;
if (destcol == WCOLS)
return;
destline += destcol / WCOLS;
destcol %= WCOLS;
if (destline < 0 || destline > WECHO)
error("Internal error: vclreol");
i = WCOLS - destcol;
tp = vtube[destline] + destcol;
if (CE) {
if ((IN && *tp) || !ateopr()) {
vcsync();
vputp(CE, 1);
}
vclrbyte(tp, i);
return;
}
if (*tp == 0)
return;
while (i > 0 && (j = *tp & (QUOTE|TRIM))) {
if (j != ' ' && (j & QUOTE) == 0) {
destcol = WCOLS - i;
vputchar(' ');
}
--i, *tp++ = 0;
}
}
/*
* Clear the echo line.
* If didphys then its been cleared physically (as
* a side effect of a clear to end of display, e.g.)
* so just do it logically.
* If work here is being held off, just remember, in
* heldech, if work needs to be done, don't do anything.
*/
void
vclrech(bool didphys)
{
if (Peekkey == ATTN)
return;
if (hold & HOLDECH) {
heldech = !didphys;
return;
}
if (!didphys && (CD || CE)) {
splitw++;
/*
* If display is retained below, then MUST use CD or CE
* since we don't really know whats out there.
* Vigoto might decide (incorrectly) to do nothing.
*/
if (DB)
vgoto(WECHO, 0), vputp(CD ? CD : CE, 1);
else
vigoto(WECHO, 0), vclreol();
splitw = 0;
didphys = 1;
}
if (didphys)
vclrbyte(vtube[WECHO], WCOLS);
heldech = 0;
}
/*
* Fix the echo area for use, setting
* the state variable splitw so we wont rollup
* when we move the cursor there.
*/
void
fixech(void)
{
splitw++;
if (state != VISUAL && state != CRTOPEN) {
vclean();
vcnt = 0;
}
vgoto(WECHO, 0); flusho();
}
/*
* Put the cursor ``before'' cp.
*/
void
vcursbef(char *cp)
{
if (cp <= linebuf)
vgotoCL(value(NUMBER) << 3);
else
vgotoCL(column(cp - 1) - 1);
}
/*
* Put the cursor ``at'' cp.
*/
void
vcursat(char *cp)
{
if (cp <= linebuf && linebuf[0] == 0)
vgotoCL(value(NUMBER) << 3);
else
vgotoCL(column(cp - 1));
}
/*
* Put the cursor ``after'' cp.
*/
void
vcursaft(char *cp)
{
vgotoCL(column(cp));
}
/*
* Fix the cursor to be positioned in the correct place
* to accept a command.
*/
void
vfixcurs(void)
{
vsetcurs(cursor);
}
/*
* Compute the column position implied by the cursor at ``nc'',
* and move the cursor there.
*/
void
vsetcurs(char *nc)
{
register int col;
col = column(nc);
if (linebuf[0])
col--;
vgotoCL(col);
cursor = nc;
}
/*
* Move the cursor invisibly, i.e. only remember to do it.
*/
void
vigoto(int y, int x)
{
destline = y;
destcol = x;
}
/*
* Move the cursor to the position implied by any previous
* vigoto (or low level hacking with destcol/destline as in readecho).
*/
void
vcsync(void)
{
vgoto(destline, destcol);
}
/*
* Goto column x of the current line.
*/
void
vgotoCL(int x)
{
if (splitw)
vgoto(WECHO, x);
else
vgoto(LINE(vcline), x);
}
/*
* Invisible goto column x of current line.
*/
void
vigotoCL(int x)
{
if (splitw)
vigoto(WECHO, x);
else
vigoto(LINE(vcline), x);
}
/*
* Move cursor to line y, column x, handling wraparound and scrolling.
*/
void
vgoto(int y, int x)
{
register char *tp;
register int c;
/*
* Fold the possibly too large value of x.
*/
if (x >= WCOLS) {
y += x / WCOLS;
x %= WCOLS;
}
if (y < 0)
error("Internal error: vgoto");
if (outcol >= WCOLS) {
if (AM) {
outline += outcol / WCOLS;
outcol %= WCOLS;
} else
outcol = WCOLS - 1;
}
/*
* In a hardcopy or glass crt open, print the stuff
* implied by a motion, or backspace.
*/
if (state == HARDOPEN || state == ONEOPEN) {
if (y != outline)
error("Line too long for open");
if (x + 1 < outcol - x || (outcol > x && !BS))
destcol = 0, fgoto();
tp = vtube[WBOT] + outcol;
while (outcol != x)
if (outcol < x) {
if (*tp == 0)
*tp = ' ';
c = *tp++ & TRIM;
vputc(c && (!OS || EO) ? c : ' '), outcol++;
} else {
if (BC)
vputp(BC, 0);
else
vputc('\b');
outcol--;
}
destcol = outcol = x;
destline = outline;
return;
}
/*
* If the destination position implies a scroll, do it.
*/
destline = y;
if (destline > WBOT && (!splitw || destline > WECHO)) {
endim();
vrollup(destline);
}
/*
* If there really is a motion involved, do it.
* The check here is an optimization based on profiling.
*/
destcol = x;
if ((destline - outline) * WCOLS != destcol - outcol) {
if (!MI)
endim();
fgoto();
}
}
/*
* This is the hardest code in the editor, and deals with insert modes
* on different kinds of intelligent terminals. The complexity is due
* to the cross product of three factors:
*
* 1. Lines may display as more than one segment on the screen.
* 2. There are 2 kinds of intelligent terminal insert modes.
* 3. Tabs squash when you insert characters in front of them,
* in a way in which current intelligent terminals don't handle.
*
* The two kinds of terminals are typified by the DM2500 or HP2645 for
* one and the CONCEPT-100 or the FOX for the other.
*
* The first (HP2645) kind has an insert mode where the characters
* fall off the end of the line and the screen is shifted rigidly
* no matter how the display came about.
*
* The second (CONCEPT-100) kind comes from terminals which are designed
* for forms editing and which distinguish between blanks and ``spaces''
* on the screen, spaces being like blank, but never having had
* and data typed into that screen position (since, e.g. a clear operation
* like clear screen). On these terminals, when you insert a character,
* the characters from where you are to the end of the screen shift
* over till a ``space'' is found, and the null character there gets
* eaten up.
*
*
* The code here considers the line as consisting of several parts
* the first part is the ``doomed'' part, i.e. a part of the line
* which is being typed over. Next comes some text up to the first
* following tab. The tab is the next segment of the line, and finally
* text after the tab.
*
* We have to consider each of these segments and the effect of the
* insertion of a character on them. On terminals like HP2645's we
* must simulate a multi-line insert mode using the primitive one
* line insert mode. If we are inserting in front of a tab, we have
* to either delete characters from the tab or insert white space
* (when the tab reaches a new spot where it gets larger) before we
* insert the new character.
*
* On a terminal like a CONCEPT our strategy is to make all
* blanks be displayed, while trying to keep the screen having ``spaces''
* for portions of tabs. In this way the terminal hardward does some
* of the hacking for compression of tabs, although this tends to
* disappear as you work on the line and spaces change into blanks.
*
* There are a number of boundary conditions (like typing just before
* the first following tab) where we can avoid a lot of work. Most
* of them have to be dealt with explicitly because performance is
* much, much worse if we don't.
*
* A final thing which is hacked here is two flavors of insert mode.
* Datamedia's do this by an insert mode which you enter and leave
* and by having normal motion character operate differently in this
* mode, notably by having a newline insert a line on the screen in
* this mode. This generally means it is unsafe to move around
* the screen ignoring the fact that we are in this mode.
* This is possible on some terminals, and wins big (e.g. HP), so
* we encode this as a ``can move in insert capability'' mi,
* and terminals which have it can do insert mode with much less
* work when tabs are present following the cursor on the current line.
*/
/*
* Routine to expand a tab, calling the normal Outchar routine
* to put out each implied character. Note that we call outchar
* with a QUOTE. We use QUOTE internally to represent a position
* which is part of the expansion of a tab.
*/
static void
vgotab(void)
{
register int i = (LINE(vcline) - destline) * WCOLS + destcol;
do
(*Outchar)(QUOTE);
while (++i % value(TABSTOP));
}
/*
* Variables for insert mode.
*/
int linend; /* The column position of end of line */
int tabstart; /* Column of start of first following tab */
int tabend; /* Column of end of following tabs */
int tabsize; /* Size of the following tabs */
int tabslack; /* Number of ``spaces'' in following tabs */
int inssiz; /* Number of characters to be inserted */
int inscol; /* Column where insertion is taking place */
int shft; /* Amount tab expansion shifted rest of line */
int slakused; /* This much of tabslack will be used up */
/*
* This routine MUST be called before insert mode is run,
* and brings all segments of the current line to the top
* of the screen image buffer so it is easier for us to
* maniuplate them.
*/
void
vprepins(void)
{
register int i;
register char *cp = vtube0;
for (i = 0; i < DEPTH(vcline); i++) {
vmaktop(LINE(vcline) + i, cp);
cp += WCOLS;
}
}
static void
vmaktop(int p, char *cp)
{
register int i;
char temp[TUBECOLS];
if (vtube[p] == cp)
return;
for (i = ZERO; i <= WECHO; i++)
if (vtube[i] == cp) {
copy(temp, vtube[i], WCOLS);
copy(vtube[i], vtube[p], WCOLS);
copy(vtube[p], temp, WCOLS);
vtube[i] = vtube[p];
vtube[p] = cp;
return;
}
error("Line too long");
}
/*
* Insert character c at current cursor position.
* Multi-character inserts occur only as a result
* of expansion of tabs (i.e. inssize == 1 except
* for tabs) and code assumes this in several place
* to make life simpler.
*/
void
vinschar(int c)
{
register int i;
register char *tp;
if ((!IM || !EI) && ((hold & HOLDQIK) || !value(REDRAW) || value(SLOWOPEN))) {
/*
* Don't want to try to use terminal
* insert mode, or to try to fake it.
* Just put the character out; the screen
* will probably be wrong but we will fix it later.
*/
if (c == '\t') {
vgotab();
return;
}
vputchar(c);
if (DEPTH(vcline) * WCOLS + !value(REDRAW) >
(destline - LINE(vcline)) * WCOLS + destcol)
return;
/*
* The next line is about to be clobbered
* make space for another segment of this line
* (on an intelligent terminal) or just remember
* that next line was clobbered (on a dumb one
* if we don't care to redraw the tail.
*/
if (AL) {
vnpins(0);
} else {
c = LINE(vcline) + DEPTH(vcline);
if (c < LINE(vcline + 1) || c > WBOT)
return;
i = destcol;
vinslin(c, 1, vcline);
DEPTH(vcline)++;
vigoto(c, i);
vprepins();
}
return;
}
/*
* Compute the number of positions in the line image of the
* current line. This is done from the physical image
* since that is faster. Note that we have no memory
* from insertion to insertion so that routines which use
* us don't have to worry about moving the cursor around.
*/
if (*vtube0 == 0)
linend = 0;
else {
/*
* Search backwards for a non-null character
* from the end of the displayed line.
*/
i = WCOLS * DEPTH(vcline);
if (i == 0)
i = WCOLS;
tp = vtube0 + i;
while (*--tp == 0)
if (--i == 0)
break;
linend = i;
}
/*
* We insert at a position based on the physical location
* of the output cursor.
*/
inscol = destcol + (destline - LINE(vcline)) * WCOLS;
if (c == '\t') {
/*
* Characters inserted from a tab must be
* remembered as being part of a tab, but we can't
* use QUOTE here since we really need to print blanks.
* QUOTE|' ' is the representation of this.
*/
inssiz = value(TABSTOP) - inscol % value(TABSTOP);
c = ' ' | QUOTE;
} else
inssiz = 1;
/*
* If the text to be inserted is less than the number
* of doomed positions, then we don't need insert mode,
* rather we can just typeover.
*/
if (inssiz <= doomed) {
endim();
if (inscol != linend)
doomed -= inssiz;
do
vputchar(c);
while (--inssiz);
return;
}
/*
* Have to really do some insertion, thus
* stake out the bounds of the first following
* group of tabs, computing starting position,
* ending position, and the number of ``spaces'' therein
* so we can tell how much it will squish.
*/
tp = vtube0 + inscol;
for (i = inscol; i < linend; i++)
if (*tp++ & QUOTE) {
--tp;
break;
}
tabstart = tabend = i;
tabslack = 0;
while (tabend < linend) {
i = *tp++;
if ((i & QUOTE) == 0)
break;
if ((i & TRIM) == 0)
tabslack++;
tabsize++;
tabend++;
}
tabsize = tabend - tabstart;
/*
* For HP's and DM's, e.g. tabslack has no meaning.
*/
if (!IN)
tabslack = 0;
#ifdef IDEBUG
if (trace) {
fprintf(trace, "inscol %d, inssiz %d, tabstart %d, ",
inscol, inssiz, tabstart);
fprintf(trace, "tabend %d, tabslack %d, linend %d\n",
tabend, tabslack, linend);
}
#endif
/*
* The real work begins.
*/
slakused = 0;
shft = 0;
if (tabsize) {
/*
* There are tabs on this line.
* If they need to expand, then the rest of the line
* will have to be shifted over. In this case,
* we will need to make sure there are no ``spaces''
* in the rest of the line (on e.g. CONCEPT-100)
* and then grab another segment on the screen if this
* line is now deeper. We then do the shift
* implied by the insertion.
*/
if (inssiz >= doomed + value(TABSTOP) - tabstart % value(TABSTOP)) {
if (IN)
vrigid();
vneedpos(value(TABSTOP));
vishft();
}
} else if (inssiz > doomed)
/*
* No tabs, but line may still get deeper.
*/
vneedpos(inssiz - doomed);
/*
* Now put in the inserted characters.
*/
viin(c);
/*
* Now put the cursor in its final resting place.
*/
destline = LINE(vcline);
destcol = inscol + inssiz;
vcsync();
}
/*
* Rigidify the rest of the line after the first
* group of following tabs, typing blanks over ``spaces''.
*/
void
vrigid(void)
{
register int col;
register char *tp = vtube0 + tabend;
for (col = tabend; col < linend; col++)
if ((*tp++ & TRIM) == 0) {
endim();
vgotoCL(col);
vputchar(' ' | QUOTE);
}
}
/*
* We need cnt more positions on this line.
* Open up new space on the screen (this may in fact be a
* screen rollup).
*
* On a dumb terminal we may infact redisplay the rest of the
* screen here brute force to keep it pretty.
*/
static void
vneedpos(int cnt)
{
register int d = DEPTH(vcline);
register int rmdr = d * WCOLS - linend;
if (cnt <= rmdr - IN)
return;
endim();
vnpins(1);
}
static void
vnpins(int dosync)
{
register int d = DEPTH(vcline);
register int e;
e = LINE(vcline) + DEPTH(vcline);
if (e < LINE(vcline + 1)) {
vigoto(e, 0);
vclreol();
return;
}
DEPTH(vcline)++;
if (e < WECHO) {
e = vglitchup(vcline, d);
vigoto(e, 0); vclreol();
if (dosync) {
Outchar = vputchar;
vsync(e + 1);
Outchar = vinschar;
}
} else {
vup1();
vigoto(WBOT, 0);
vclreol();
}
vprepins();
}
/*
* Do the shift of the next tabstop implied by
* insertion so it expands.
*/
static void
vishft(void)
{
int tshft = 0;
int j;
register int i;
register char *tp = vtube0;
register char *up;
short oldhold = hold;
shft = value(TABSTOP);
hold |= HOLDPUPD;
if (!IM && !EI) {
/*
* Dumb terminals are easy, we just have
* to retype the text.
*/
vigotoCL(tabend + shft);
up = tp + tabend;
for (i = tabend; i < linend; i++)
vputchar(*up++);
} else if (IN) {
/*
* CONCEPT-like terminals do most of the work for us,
* we don't have to muck with simulation of multi-line
* insert mode. Some of the shifting may come for free
* also if the tabs don't have enough slack to take up
* all the inserted characters.
*/
i = shft;
slakused = inssiz - doomed;
if (slakused > tabslack) {
i -= slakused - tabslack;
slakused -= tabslack;
}
if (i > 0 && tabend != linend) {
tshft = i;
vgotoCL(tabend);
goim();
do
vputchar(' ' | QUOTE);
while (--i);
}
} else {
/*
* HP and Datamedia type terminals have to have multi-line
* insert faked. Hack each segment after where we are
* (going backwards to where we are.) We then can
* hack the segment where the end of the first following
* tab group is.
*/
for (j = DEPTH(vcline) - 1; j > (tabend + shft) / WCOLS; j--) {
vgotoCL(j * WCOLS);
goim();
up = tp + j * WCOLS - shft;
i = shft;
do
vputchar(*up++);
while (--i);
}
vigotoCL(tabstart);
i = shft - (inssiz - doomed);
if (i > 0) {
tabslack = inssiz - doomed;
vcsync();
goim();
do
vputchar(' ');
while (--i);
}
}
/*
* Now do the data moving in the internal screen
* image which is common to all three cases.
*/
tp += linend;
up = tp + shft;
i = linend - tabend;
if (i > 0)
do
*--up = *--tp;
while (--i);
if (IN && tshft) {
i = tshft;
do
#ifdef BIT8
*--up = ' ';
#else
*--up = ' ' | QUOTE;
#endif
while (--i);
}
hold = oldhold;
}
/*
* Now do the insert of the characters (finally).
*/
static void
viin(int c)
{
register char *tp, *up;
register int i, j;
register bool noim = 0;
int remdoom;
short oldhold = hold;
hold |= HOLDPUPD;
if (tabsize && (IM && EI) && inssiz - doomed > tabslack) {
/*
* There is a tab out there which will be affected
* by the insertion since there aren't enough doomed
* characters to take up all the insertion and we do
* have insert mode capability.
*/
if (inscol + doomed == tabstart) {
/*
* The end of the doomed characters sits right at the
* start of the tabs, then we don't need to use insert
* mode; unless the tab has already been expanded
* in which case we MUST use insert mode.
*/
slakused = 0;
noim = !shft;
} else {
/*
* The last really special case to handle is case
* where the tab is just sitting there and doesn't
* have enough slack to let the insertion take
* place without shifting the rest of the line
* over. In this case we have to go out and
* delete some characters of the tab before we start
* or the answer will be wrong, as the rest of the
* line will have been shifted. This code means
* that terminals with only insert chracter (no
* delete character) won't work correctly.
*/
i = inssiz - doomed - tabslack - slakused;
i %= value(TABSTOP);
if (i > 0) {
vgotoCL(tabstart);
godm();
for (i = inssiz - doomed - tabslack; i > 0; i--)
vputp(DC, DEPTH(vcline));
enddm();
}
}
}
/*
* Now put out the characters of the actual insertion.
*/
vigotoCL(inscol);
remdoom = doomed;
for (i = inssiz; i > 0; i--) {
if (remdoom > 0) {
remdoom--;
endim();
} else if (noim)
endim();
else if (IM && EI) {
vcsync();
goim();
}
vputchar(c);
}
if (!IM || !EI) {
/*
* We are a dumb terminal; brute force update
* the rest of the line; this is very much an n^^2 process,
* and totally unreasonable at low speed.
*
* You asked for it, you get it.
*/
tp = vtube0 + inscol + doomed;
for (i = inscol + doomed; i < tabstart; i++)
vputchar(*tp++);
hold = oldhold;
vigotoCL(tabstart + inssiz - doomed);
for (i = tabsize - (inssiz - doomed) + shft; i > 0; i--)
vputchar(' ' | QUOTE);
} else {
if (!IN) {
/*
* On terminals without multi-line
* insert in the hardware, we must go fix the segments
* between the inserted text and the following
* tabs, if they are on different lines.
*
* Aaargh.
*/
tp = vtube0;
for (j = (inscol + inssiz - 1) / WCOLS + 1;
j <= (tabstart + inssiz - doomed - 1) / WCOLS; j++) {
vgotoCL(j * WCOLS);
i = inssiz - doomed;
up = tp + j * WCOLS - i;
goim();
do
vputchar(*up++);
while (--i && *up);
}
} else {
/*
* On terminals with multi line inserts,
* life is simpler, just reflect eating of
* the slack.
*/
tp = vtube0 + tabend;
for (i = tabsize - (inssiz - doomed); i >= 0; i--) {
if ((*--tp & (QUOTE|TRIM)) == QUOTE) {
--tabslack;
if (tabslack >= slakused)
continue;
}
#ifdef BIT8
*tp = ' ';
#else
*tp = ' ' | QUOTE;
#endif
}
}
/*
* Blank out the shifted positions to be tab positions.
*/
#ifndef BIT8
if (shft) {
tp = vtube0 + tabend + shft;
for (i = tabsize - (inssiz - doomed) + shft; i > 0; i--)
if ((*--tp & QUOTE) == 0)
*tp = ' ' | QUOTE;
}
#endif
}
/*
* Finally, complete the screen image update
* to reflect the insertion.
*/
hold = oldhold;
tp = vtube0 + tabstart; up = tp + inssiz - doomed;
for (i = tabstart; i > inscol + doomed; i--)
*--up = *--tp;
for (i = inssiz; i > 0; i--)
*--up = c;
doomed = 0;
}
/*
* Go into ``delete mode''. If the
* sequence which goes into delete mode
* is the same as that which goes into insert
* mode, then we are in delete mode already.
*/
static void
godm(void)
{
if (insmode) {
if (eq(DM, IM))
return;
endim();
}
vputp(DM, 0);
}
/*
* If we are coming out of delete mode, but
* delete and insert mode end with the same sequence,
* it wins to pretend we are now in insert mode,
* since we will likely want to be there again soon
* if we just moved over to delete space from part of
* a tab (above).
*/
static void
enddm(void)
{
if (eq(DM, IM)) {
insmode = 1;
return;
}
vputp(ED, 0);
}
/*
* In and out of insert mode.
* Note that the code here demands that there be
* a string for insert mode (the null string) even
* if the terminal does all insertions a single character
* at a time, since it branches based on whether IM is null.
*/
void
goim(void)
{
if (!insmode)
vputp(IM, 0);
insmode = 1;
}
void
endim(void)
{
if (insmode) {
vputp(EI, 0);
insmode = 0;
}
}
/*
* Put the character c on the screen at the current cursor position.
* This routine handles wraparound and scrolling and understands not
* to roll when splitw is set, i.e. we are working in the echo area.
* There is a bunch of hacking here dealing with the difference between
* QUOTE, QUOTE|' ', and ' ' for CONCEPT-100 like terminals, and also
* code to deal with terminals which overstrike, including CRT's where
* you can erase overstrikes with some work. CRT's which do underlining
* implicitly which has to be erased (like CONCEPTS) are also handled.
*/
void
vputchar(int c)
{
register char *tp;
register int d;
c &= (QUOTE|TRIM);
#ifdef TRACE
if (trace)
tracec(c);
#endif
/* Patch to fix problem of >79 chars on echo line: don't echo extras */
if (destcol >= WCOLS-1 && splitw && destline == WECHO)
return;
if (destcol >= WCOLS) {
destline += destcol / WCOLS;
destcol %= WCOLS;
}
if (destline > WBOT && (!splitw || destline > WECHO))
vrollup(destline);
tp = vtube[destline] + destcol;
switch (c) {
case '\t':
vgotab();
return;
case ' ':
/*
* We can get away without printing a space in a number
* of cases, but not always. We get away with doing nothing
* if we are not in insert mode, and not on a CONCEPT-100
* like terminal, and either not in hardcopy open or in hardcopy
* open on a terminal with no overstriking, provided,
* in all cases, that nothing has ever been displayed
* at this position. Ugh.
*/
if (!insmode && !IN && (state != HARDOPEN || OS) && (*tp&TRIM) == 0) {
*tp = ' ';
destcol++;
return;
}
goto def;
case QUOTE:
if (insmode) {
/*
* When in insert mode, tabs have to expand
* to real, printed blanks.
*/
c = ' ' | QUOTE;
goto def;
}
if (*tp == 0) {
/*
* A ``space''.
*/
if ((hold & HOLDPUPD) == 0)
#ifdef BIT8
*tp = ' ';
#else
*tp = QUOTE;
#endif
destcol++;
return;
}
/*
* A ``space'' ontop of a part of a tab.
*/
if (*tp & QUOTE) {
destcol++;
return;
}
c = ' ' | QUOTE;
/* fall into ... */
def:
default:
d = *tp & TRIM;
/*
* Now get away with doing nothing if the characters
* are the same, provided we are not in insert mode
* and if we are in hardopen, that the terminal has overstrike.
*/
if (d == (c & TRIM) && !insmode && (state != HARDOPEN || OS)) {
if ((hold & HOLDPUPD) == 0)
*tp = c;
destcol++;
return;
}
/*
* Backwards looking optimization.
* The low level cursor motion routines will use
* a cursor motion right sequence to step 1 character
* right. On, e.g., a DM3025A this is 2 characters
* and printing is noticeably slower at 300 baud.
* Since the low level routines are not allowed to use
* spaces for positioning, we discover the common
* case of a single space here and force a space
* to be printed.
*/
if (destcol == outcol + 1 && tp[-1] == ' ' && outline == destline) {
vputc(' ');
outcol++;
}
/*
* This is an inline expansion a call to vcsync() dictated
* by high frequency in a profile.
*/
if (outcol != destcol || outline != destline)
vgoto(destline, destcol);
/*
* Deal with terminals which have overstrike.
* We handle erasing general overstrikes, erasing
* underlines on terminals (such as CONCEPTS) which
* do underlining correctly automatically (e.g. on nroff
* output), and remembering, in hardcopy mode,
* that we have overstruct something.
*/
if (!insmode && d && d != ' ' && d != (c & TRIM)) {
if (EO && (OS || (UL && (c == '_' || d == '_')))) {
vputc(' ');
outcol++, destcol++;
back1();
} else
rubble = 1;
}
/*
* Unless we are just bashing characters around for
* inner working of insert mode, update the display.
*/
if ((hold & HOLDPUPD) == 0)
*tp = c;
/*
* In insert mode, put out the IC sequence, padded
* based on the depth of the current line.
* A terminal which had no real insert mode, rather
* opening a character position at a time could do this.
* Actually should use depth to end of current line
* but this rarely matters.
*/
if (insmode)
vputp(IC, DEPTH(vcline));
vputc(c & TRIM);
/*
* In insert mode, IP is a post insert pad.
*/
if (insmode)
vputp(IP, DEPTH(vcline));
destcol++, outcol++;
/*
* CONCEPT braindamage in early models: after a wraparound
* the next newline is eaten. It's hungry so we just
* feed it now rather than worrying about it.
*/
if (XN && outcol % WCOLS == 0)
vputc('\n');
}
}
/*
* Delete display positions stcol through endcol.
* Amount of use of special terminal features here is limited.
*/
void
physdc(int stcol, int endcol)
{
register char *tp, *up;
char *tpe = NULL;
register int i;
register int nc = endcol - stcol;
#ifdef IDEBUG
if (trace)
tfixnl(), fprintf(trace, "physdc(%d, %d)\n", stcol, endcol);
#endif
if (!DC || nc <= 0)
return;
if (IN) {
/*
* CONCEPT-100 like terminal.
* If there are any ``spaces'' in the material to be
* deleted, then this is too hard, just retype.
*/
vprepins();
up = vtube0 + stcol;
i = nc;
do
if ((*up++ & (QUOTE|TRIM)) == QUOTE)
return;
while (--i);
i = 2 * nc;
do
if (*up == 0 || (*up++ & QUOTE) == QUOTE)
return;
while (--i);
vgotoCL(stcol);
} else {
/*
* HP like delete mode.
* Compute how much text we are moving over by deleting.
* If it appears to be faster to just retype
* the line, do nothing and that will be done later.
* We are assuming 2 output characters per deleted
* characters and that clear to end of line is available.
*/
i = stcol / WCOLS;
if (i != endcol / WCOLS)
return;
i += LINE(vcline);
stcol %= WCOLS;
endcol %= WCOLS;
up = vtube[i]; tp = up + endcol; tpe = up + WCOLS;
while (tp < tpe && *tp)
tp++;
if (tp - (up + stcol) < 2 * nc)
return;
vgoto(i, stcol);
}
/*
* Go into delete mode and do the actual delete.
* Padding is on DC itself.
*/
godm();
for (i = nc; i > 0; i--)
vputp(DC, DEPTH(vcline));
vputp(ED, 0);
/*
* Straighten up.
* With CONCEPT like terminals, characters are pulled left
* from first following null. HP like terminals shift rest of
* this (single physical) line rigidly.
*/
if (IN) {
up = vtube0 + stcol;
tp = vtube0 + endcol;
while ((i = *tp++)) {
if ((i & (QUOTE|TRIM)) == QUOTE)
break;
*up++ = i;
}
do
*up++ = i;
while (--nc);
} else {
copy(up + stcol, up + endcol, WCOLS - endcol);
vclrbyte(tpe - nc, nc);
}
}
#ifdef TRACE
tfixnl()
{
if (trubble || techoin)
fprintf(trace, "\n");
trubble = 0, techoin = 0;
}
tvliny()
{
register int i;
if (!trace)
return;
tfixnl();
fprintf(trace, "vcnt = %d, vcline = %d, vliny = ", vcnt, vcline);
for (i = 0; i <= vcnt; i++) {
fprintf(trace, "%d", LINE(i));
if (FLAGS(i) & VDIRT)
fprintf(trace, "*");
if (DEPTH(i) != 1)
fprintf(trace, "<%d>", DEPTH(i));
if (i < vcnt)
fprintf(trace, " ");
}
fprintf(trace, "\n");
}
tracec(c)
int c;
{
if (!techoin)
trubble = 1;
if (c == ESCAPE)
fprintf(trace, "$");
else if (c < ' ' || c == DELETE)
fprintf(trace, "^%c", ctlof(c));
else
fprintf(trace, "%c", c);
}
#endif
/*
* Put a character with possible tracing.
*/
int
vputch(int c)
{
#ifdef TRACE
if (trace)
tracec(c);
#endif
return vputc(c);
}
|
n-t-roff/ex-3.2 | ex_data.c | <gh_stars>1-10
/* Copyright (c) 1979 Regents of the University of California */
#include "ex.h"
#include "ex_tty.h"
/*
* Initialization of option values.
* The option #defines in ex_vars.h are made
* from this file by the script makeoptions.
*/
char direct[ONMSZ] =
{ '/', 't', 'm', 'p' };
char sections[ONMSZ] = {
'N', 'H', 'S', 'H', /* -ms macros */
'H', ' ', 'H', 'U' /* -mm macros */
};
char paragraphs[ONMSZ] = {
'I', 'P', 'L', 'P', 'P', 'P', 'Q', 'P', /* -ms macros */
'P', ' ', 'L', 'I', /* -mm macros */
'b', 'p' /* bare nroff */
};
char shell[ONMSZ] =
{ '/', 'b', 'i', 'n', '/', 's', 'h' };
char ttytype[ONMSZ] =
{ 'd', 'u', 'm', 'b' };
short COLUMNS = 80;
short EX_LINES = 24;
struct option options[NOPTS + 1] = {
{ "autoindent", "ai", ONOFF, 0, 0, 0 },
{ "autoprint", "ap", ONOFF, 1, 1, 0 },
{ "autowrite", "aw", ONOFF, 0, 0, 0 },
{ "beautify", "bf", ONOFF, 0, 0, 0 },
{ "directory", "dir", STRING, 0, 0, direct },
{ "edcompatible", "ed", ONOFF, 0, 0, 0 },
{ "errorbells", "eb", ONOFF, 0, 0, 0 },
{ "hardtabs", "ht", NUMERIC, 8, 8, 0 },
{ "ignorecase", "ic", ONOFF, 0, 0, 0 },
{ "lisp", 0, ONOFF, 0, 0, 0 },
{ "list", 0, ONOFF, 0, 0, 0 },
{ "magic", 0, ONOFF, 1, 1, 0 },
{ "mapinput", "mi", ONOFF, 0, 0, 0 },
{ "number", "nu", ONOFF, 0, 0, 0 },
{ "open", 0, ONOFF, 1, 1, 0 },
{ "optimize", "opt", ONOFF, 0, 0, 0 },
{ "paragraphs", "para", STRING, 0, 0, paragraphs },
{ "prompt", 0, ONOFF, 1, 1, 0 },
{ "redraw", 0, ONOFF, 0, 0, 0 },
{ "report", 0, NUMERIC, 5, 5, 0 },
{ "scroll", "scr", NUMERIC, 12, 12, 0 },
{ "sections", "sect", STRING, 0, 0, sections },
{ "shell", "sh", STRING, 0, 0, shell },
{ "shiftwidth", "sw", NUMERIC, TABS, TABS, 0 },
{ "showmatch", "sm", ONOFF, 0, 0, 0 },
{ "slowopen", "slow", ONOFF, 0, 0, 0 },
{ "tabstop", "ts", NUMERIC, TABS, TABS, 0 },
{ "ttytype", "tty", OTERM, 0, 0, ttytype },
{ "term", 0, OTERM, 0, 0, ttytype },
{ "terse", 0, ONOFF, 0, 0, 0 },
{ "warn", 0, ONOFF, 1, 1, 0 },
{ "window", "wi", NUMERIC, 23, 23, 0 },
{ "wrapscan", "ws", ONOFF, 1, 1, 0 },
{ "wrapmargin", "wm", NUMERIC, 0, 0, 0 },
{ "writeany", "wa", ONOFF, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 }
};
|
n-t-roff/ex-3.2 | ex_vops3.c | <gh_stars>1-10
/* Copyright (c) 1979 Regents of the University of California */
#include "ex.h"
#include "ex_tty.h"
#include "ex_vis.h"
/*
* Routines to handle structure.
* Operations supported are:
* ( ) { } [ ]
*
* These cover: LISP TEXT
* ( ) s-exprs sentences
* { } list at same paragraphs
* [ ] defuns sections
*
* { and } for C used to attempt to do something with matching {}'s, but
* I couldn't find definitions which worked intuitively very well, so I
* scrapped this.
*
* The code here is very hard to understand.
*/
static int endsent(bool);
static int endPS(void);
static int ltosolid(void);
static int ltosol1(char *);
static int lskipbal(char *);
static int lskipatom(void);
static int lskipa1(char *);
static int isa(char *);
line *llimit;
void (*lf)();
bool wasend;
/*
* Find over structure, repeated count times.
* Don't go past line limit. F is the operation to
* be performed eventually. If pastatom then the user said {}
* rather than (), implying past atoms in a list (or a paragraph
* rather than a sentence.
*/
int
lfind(bool pastatom, int cnt, void (*f)(), line *limit)
{
register int c;
register int rc = 0;
char save[LBSIZE];
/*
* Initialize, saving the current line buffer state
* and computing the limit; a 0 argument means
* directional end of file.
*/
wasend = 0;
lf = f;
strcpy(save, linebuf);
if (limit == 0)
limit = dir < 0 ? one : dol;
llimit = limit;
wdot = dot;
wcursor = cursor;
if (pastatom >= 2) {
while (cnt > 0 && word(f, cnt))
cnt--;
if (pastatom == 3)
eend(f);
if (dot == wdot) {
wdot = 0;
if (cursor == wcursor)
rc = -1;
}
}
#ifdef LISPCODE
else if (!value(LISP)) {
#else
else {
#endif
char *icurs;
line *idot;
if (linebuf[0] == 0) {
do
if (!lnext())
goto ret;
while (linebuf[0] == 0);
if (dir > 0) {
wdot--;
linebuf[0] = 0;
wcursor = linebuf;
/*
* If looking for sentence, next line
* starts one.
*/
if (!pastatom) {
icurs = wcursor;
idot = wdot;
goto begin;
}
}
}
icurs = wcursor;
idot = wdot;
/*
* Advance so as to not find same thing again.
*/
if (dir > 0) {
if (!lnext()) {
rc = -1;
goto ret;
}
} else
ignore(lskipa1(""));
/*
* Count times find end of sentence/paragraph.
*/
begin:
for (;;) {
while (!endsent(pastatom))
if (!lnext())
goto ret;
if (!pastatom || (wcursor == linebuf && endPS()))
if (--cnt <= 0)
break;
if (linebuf[0] == 0) {
do
if (!lnext())
goto ret;
while (linebuf[0] == 0);
} else
if (!lnext())
goto ret;
}
/*
* If going backwards, and didn't hit the end of the buffer,
* then reverse direction.
*/
if (dir < 0 && (wdot != llimit || wcursor != linebuf)) {
dir = 1;
llimit = dot;
/*
* Empty line needs special treatement.
* If moved to it from other than begining of next line,
* then a sentence starts on next line.
*/
if (linebuf[0] == 0 && !pastatom &&
(wdot != dot - 1 || cursor != linebuf)) {
lnext();
goto ret;
}
}
/*
* If we are not at a section/paragraph division,
* advance to next.
*/
if ((wcursor == icurs && wdot == idot) || wcursor != linebuf || !endPS())
ignore(lskipa1(""));
}
#ifdef LISPCODE
else {
c = *wcursor;
/*
* Startup by skipping if at a ( going left or a ) going
* right to keep from getting stuck immediately.
*/
if ((dir < 0 && c == '(') || (dir > 0 && c == ')')) {
if (!lnext()) {
rc = -1;
goto ret;
}
}
/*
* Now chew up repitition count. Each time around
* if at the beginning of an s-exp (going forwards)
* or the end of an s-exp (going backwards)
* skip the s-exp. If not at beg/end resp, then stop
* if we hit a higher level paren, else skip an atom,
* counting it unless pastatom.
*/
while (cnt > 0) {
c = *wcursor;
if ((dir < 0 && c == ')') || (dir > 0 && c == '(')) {
if (!lskipbal("()"))
goto ret;
/*
* Unless this is the last time going
* backwards, skip past the matching paren
* so we don't think it is a higher level paren.
*/
if (dir < 0 && cnt == 1)
goto ret;
if (!lnext() || !ltosolid())
goto ret;
--cnt;
} else if ((dir < 0 && c == '(') || (dir > 0 && c == ')'))
/* Found a higher level paren */
goto ret;
else {
if (!lskipatom())
goto ret;
if (!pastatom)
--cnt;
}
}
}
#endif
ret:
strcLIN(save);
return (rc);
}
/*
* Is this the end of a sentence?
*/
static int
endsent(bool pastatom)
{
register char *cp = wcursor;
register int c, d;
(void)pastatom;
/*
* If this is the beginning of a line, then
* check for the end of a paragraph or section.
*/
if (cp == linebuf)
return (endPS());
/*
* Sentences end with . ! ? not at the beginning
* of the line, and must be either at the end of the line,
* or followed by 2 spaces. Any number of intervening ) ] ' "
* characters are allowed.
*/
if (!any(c = *cp, ".!?"))
goto tryps;
do
if ((d = *++cp) == 0)
return (1);
while (any(d, ")]'"));
if (*cp == 0 || (*cp++ == ' ' && *cp == ' '))
return (1);
tryps:
if (cp[1] == 0)
return (endPS());
return (0);
}
/*
* End of paragraphs/sections are respective
* macros as well as blank lines and form feeds.
*/
static int
endPS(void)
{
return (linebuf[0] == 0 ||
isa(svalue(PARAGRAPHS)) || isa(svalue(SECTIONS)));
}
#ifdef LISPCODE
int
lindent(line *addr)
{
register int i;
char *swcurs = wcursor;
line *swdot = wdot;
again:
if (addr > one) {
register char *cp;
register int cnt = 0;
addr--;
ex_getline(*addr);
for (cp = linebuf; *cp; cp++)
if (*cp == '(')
cnt++;
else if (*cp == ')')
cnt--;
cp = vpastwh(linebuf);
if (*cp == 0)
goto again;
if (cnt == 0)
return (whitecnt(linebuf));
addr++;
}
wcursor = linebuf;
linebuf[0] = 0;
wdot = addr;
dir = -1;
llimit = one;
lf = (void (*)())lindent;
if (!lskipbal("()"))
i = 0;
else if (wcursor == linebuf)
i = 2;
else {
register char *wp = wcursor;
dir = 1;
llimit = wdot;
if (!lnext() || !ltosolid() || !lskipatom()) {
wcursor = wp;
i = 1;
} else
i = 0;
i += column(wcursor) - 1;
if (!inopen)
i--;
}
wdot = swdot;
wcursor = swcurs;
return (i);
}
#endif
int
lmatchp(line *addr)
{
register int i;
register char *parens, *cp;
for (cp = cursor; !any(*cp, "({)}");)
if (*cp++ == 0)
return (0);
lf = 0;
parens = any(*cp, "()") ? "()" : "{}";
if (*cp == parens[1]) {
dir = -1;
llimit = one;
} else {
dir = 1;
llimit = dol;
}
if (addr)
llimit = addr;
if (splitw)
llimit = dot;
wcursor = cp;
wdot = dot;
i = lskipbal(parens);
return (i);
}
void
lsmatch(char *cp)
{
char save[LBSIZE];
register char *sp = save;
register char *scurs = cursor;
wcursor = cp;
strcpy(sp, linebuf);
*wcursor = 0;
strcpy(cursor, genbuf);
cursor = strend(linebuf) - 1;
if (lmatchp(dot - vcline)) {
register int i = insmode;
register int c = outcol;
register int l = outline;
if (!MI)
endim();
vgoto(splitw ? WECHO : LINE(wdot - llimit), column(wcursor) - 1);
flush();
sleep(1);
vgoto(l, c);
if (i)
goim();
}
strcLIN(sp);
wdot = 0;
wcursor = 0;
cursor = scurs;
}
static int
ltosolid(void)
{
return (ltosol1("()"));
}
static int
ltosol1(char *parens)
{
register char *cp;
if (*parens && !*wcursor && !lnext())
return (0);
while (isspace((int)*wcursor) || (*wcursor == 0 && *parens))
if (!lnext())
return (0);
if (any(*wcursor, parens) || dir > 0)
return (1);
for (cp = wcursor; cp > linebuf; cp--)
if (isspace((int)cp[-1]) || any(cp[-1], parens))
break;
wcursor = cp;
return (1);
}
static int
lskipbal(char *parens)
{
register int level = dir;
register int c;
do {
if (!lnext())
return (0);
c = *wcursor;
if (c == parens[1])
level--;
else if (c == parens[0])
level++;
} while (level);
return (1);
}
static int
lskipatom(void)
{
return (lskipa1("()"));
}
static int
lskipa1(char *parens)
{
register int c;
for (;;) {
if (dir < 0 && wcursor == linebuf) {
if (!lnext())
return (0);
break;
}
c = *wcursor;
if (c && (isspace(c) || any(c, parens)))
break;
if (!lnext())
return (0);
if (dir > 0 && wcursor == linebuf)
break;
}
return (ltosol1(parens));
}
int
lnext(void)
{
if (dir > 0) {
if (*wcursor)
wcursor++;
if (*wcursor)
return (1);
if (wdot >= llimit) {
if (wcursor > linebuf)
wcursor--;
return (0);
}
wdot++;
ex_getline(*wdot);
wcursor = linebuf;
return (1);
} else {
--wcursor;
if (wcursor >= linebuf)
return (1);
#ifdef LISPCODE
if (lf == (void (*)())lindent && linebuf[0] == '(')
llimit = wdot;
#endif
if (wdot <= llimit) {
wcursor = linebuf;
return (0);
}
wdot--;
ex_getline(*wdot);
wcursor = linebuf[0] == 0 ? linebuf : strend(linebuf) - 1;
return (1);
}
}
int
lbrack(int c, void (*f)())
{
register line *addr;
addr = dot;
for (;;) {
addr += dir;
if (addr < one || addr > dol) {
addr -= dir;
break;
}
ex_getline(*addr);
if (linebuf[0] == '{' ||
#ifdef LISPCODE
(value(LISP) && linebuf[0] == '(') ||
#endif
isa(svalue(SECTIONS))) {
if (c == ']' && f != vmove) {
addr--;
ex_getline(*addr);
}
break;
}
if (c == ']' && f != vmove && linebuf[0] == '}')
break;
}
if (addr == dot)
return (0);
if (f != vmove)
wcursor = c == ']' ? strend(linebuf) : linebuf;
else
wcursor = 0;
wdot = addr;
vmoving = 0;
return (1);
}
static int
isa(char *cp)
{
if (linebuf[0] != '.')
return (0);
for (; cp[0] && cp[1]; cp += 2)
if (linebuf[1] == cp[0]) {
if (linebuf[2] == cp[1])
return (1);
if (linebuf[2] == 0 && cp[1] == ' ')
return (1);
}
return (0);
}
|
ingoha/TTGO-T-Wristband | include/fonts/Orbitron_Light_7.h | <gh_stars>0
const uint8_t orbitron_light7pt7bBitmaps[] PROGMEM = {
0x00, 0xFE, 0x40, 0xB4, 0x0C, 0x41, 0x09, 0xFF, 0x88, 0x41, 0x08, 0x23,
0x08, 0x47, 0xFE, 0x23, 0x08, 0x40, 0x08, 0x02, 0x0F, 0xFA, 0x21, 0x88,
0x22, 0x0F, 0xF8, 0x21, 0x08, 0x42, 0x18, 0x87, 0xFE, 0x08, 0x02, 0x00,
0xF0, 0x29, 0x06, 0x90, 0xC9, 0x18, 0xF3, 0x00, 0x4E, 0x09, 0x13, 0x11,
0x61, 0x14, 0x0E, 0x7F, 0x84, 0x04, 0x40, 0x04, 0x00, 0x70, 0x09, 0xC4,
0x87, 0x48, 0x1C, 0x80, 0x6F, 0xF9, 0xC0, 0xEA, 0xAA, 0xB0, 0xD5, 0x55,
0x70, 0x21, 0x3E, 0x45, 0x6C, 0x21, 0x3E, 0x42, 0x10, 0xE0, 0xF8, 0x80,
0x02, 0x04, 0x10, 0x41, 0x82, 0x08, 0x20, 0x81, 0x00, 0xFF, 0xE0, 0x38,
0x1E, 0x0D, 0x86, 0x66, 0x1B, 0x07, 0x81, 0xC0, 0x7F, 0xF0, 0x37, 0xD1,
0x11, 0x11, 0x11, 0xFF, 0xA0, 0x10, 0x04, 0x01, 0x00, 0x7F, 0xE8, 0x02,
0x00, 0x80, 0x3F, 0xF0, 0xFF, 0xC0, 0x40, 0x20, 0x17, 0xF8, 0x04, 0x02,
0x01, 0x80, 0xFF, 0xC0, 0x03, 0x01, 0xC0, 0xD0, 0x64, 0x21, 0x30, 0x4F,
0xFC, 0x04, 0x01, 0x00, 0x40, 0xFF, 0xE0, 0x08, 0x02, 0x00, 0xFF, 0x80,
0x10, 0x04, 0x01, 0x80, 0x7F, 0xE0, 0xFF, 0x20, 0x08, 0x02, 0x00, 0xFF,
0xA0, 0x18, 0x06, 0x01, 0x80, 0x7F, 0xE0, 0xFF, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0xFF, 0xA0, 0x18, 0x06, 0x01, 0xFF, 0xE0,
0x18, 0x06, 0x01, 0x80, 0x7F, 0xF0, 0x7F, 0xE0, 0x18, 0x06, 0x01, 0x80,
0x5F, 0xF0, 0x04, 0x01, 0x00, 0x7F, 0xF0, 0x81, 0x81, 0xC0, 0x04, 0x67,
0x30, 0xC1, 0xC1, 0x81, 0xFE, 0x00, 0x07, 0xF0, 0x86, 0x0C, 0x31, 0x9B,
0x10, 0xFF, 0x80, 0x40, 0x20, 0x10, 0x09, 0xFC, 0x80, 0x00, 0x00, 0x10,
0x00, 0xFF, 0xE0, 0x18, 0x06, 0xF9, 0xA2, 0x68, 0x9B, 0xFE, 0x00, 0x80,
0x3F, 0xF0, 0xFF, 0xE0, 0x18, 0x06, 0x01, 0x80, 0x7F, 0xF8, 0x06, 0x01,
0x80, 0x60, 0x10, 0xFF, 0xC0, 0x60, 0x30, 0x1F, 0xFC, 0x06, 0x03, 0x01,
0x80, 0xFF, 0xC0, 0xFF, 0xE0, 0x08, 0x02, 0x00, 0x80, 0x20, 0x08, 0x02,
0x00, 0x80, 0x3F, 0xF0, 0xFF, 0xE0, 0x18, 0x06, 0x01, 0x80, 0x60, 0x18,
0x06, 0x01, 0x80, 0x7F, 0xF0, 0xFF, 0xC0, 0x20, 0x10, 0x0F, 0xE4, 0x02,
0x01, 0x00, 0x80, 0x7F, 0xC0, 0xFF, 0xC0, 0x20, 0x10, 0x0F, 0xE4, 0x02,
0x01, 0x00, 0x80, 0x40, 0x00, 0xFF, 0xE0, 0x18, 0x02, 0x00, 0x80, 0x20,
0xF8, 0x06, 0x01, 0x80, 0x7F, 0xF0, 0x80, 0x60, 0x18, 0x06, 0x01, 0xFF,
0xE0, 0x18, 0x06, 0x01, 0x80, 0x60, 0x10, 0xFF, 0xC0, 0x00, 0x40, 0x10,
0x04, 0x01, 0x00, 0x40, 0x10, 0x04, 0x01, 0x80, 0x7F, 0xF0, 0x80, 0xC0,
0xA0, 0x90, 0xCF, 0xC4, 0x22, 0x19, 0x04, 0x81, 0x40, 0x40, 0x80, 0x20,
0x08, 0x02, 0x00, 0x80, 0x20, 0x08, 0x02, 0x00, 0x80, 0x3F, 0xF0, 0xC0,
0x7C, 0x1E, 0x82, 0xC8, 0x98, 0xA3, 0x1C, 0x61, 0x0C, 0x01, 0x80, 0x30,
0x04, 0xC0, 0x78, 0x1B, 0x06, 0x61, 0x88, 0x61, 0x18, 0x66, 0x0D, 0x81,
0xE0, 0x30, 0xFF, 0xE0, 0x18, 0x06, 0x01, 0x80, 0x60, 0x18, 0x06, 0x01,
0x80, 0x7F, 0xF0, 0xFF, 0xE0, 0x18, 0x06, 0x01, 0x80, 0x7F, 0xF8, 0x02,
0x00, 0x80, 0x20, 0x00, 0xFF, 0xD0, 0x0A, 0x01, 0x40, 0x28, 0x05, 0x00,
0xA0, 0x14, 0x02, 0x80, 0x5F, 0xFC, 0xFF, 0xE0, 0x18, 0x06, 0x01, 0x80,
0x7F, 0xF8, 0x22, 0x0C, 0x81, 0xA0, 0x30, 0xFF, 0xE0, 0x18, 0x02, 0x00,
0xFF, 0x80, 0x10, 0x04, 0x01, 0x80, 0x7F, 0xE0, 0xFF, 0x84, 0x02, 0x01,
0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x00, 0x80, 0x60, 0x18, 0x06,
0x01, 0x80, 0x60, 0x18, 0x06, 0x01, 0x80, 0x7F, 0xF0, 0xC0, 0x0B, 0x00,
0xC8, 0x04, 0x20, 0x41, 0x02, 0x04, 0x20, 0x33, 0x00, 0x90, 0x07, 0x80,
0x18, 0x00, 0xC1, 0x81, 0x41, 0xC3, 0x61, 0x42, 0x23, 0x42, 0x22, 0x64,
0x12, 0x24, 0x14, 0x2C, 0x14, 0x38, 0x0C, 0x18, 0x08, 0x18, 0xC0, 0xD0,
0x42, 0x20, 0x58, 0x1C, 0x07, 0x01, 0x60, 0x88, 0x41, 0x30, 0x30, 0xC0,
0x6C, 0x18, 0xC6, 0x08, 0x80, 0xA0, 0x1C, 0x01, 0x00, 0x20, 0x04, 0x00,
0x80, 0xFF, 0xC0, 0x30, 0x18, 0x0C, 0x0C, 0x06, 0x03, 0x01, 0x80, 0xC0,
0x3F, 0xF0, 0xEA, 0xAA, 0xB0, 0x81, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02,
0x02, 0x04, 0xD5, 0x55, 0x70, 0x00, 0xFF, 0xC0, 0xD0, 0xFF, 0x01, 0x01,
0xFF, 0x81, 0x81, 0x81, 0x7F, 0x80, 0x80, 0x80, 0xFF, 0x81, 0x81, 0x81,
0x81, 0x81, 0x81, 0xFF, 0xFF, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xFF,
0x01, 0x01, 0x01, 0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF, 0xFF,
0x81, 0x81, 0xFF, 0x80, 0x80, 0x80, 0xFF, 0xFC, 0x21, 0xF8, 0x42, 0x10,
0x84, 0x20, 0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF, 0x01, 0x01,
0x7F, 0x80, 0x80, 0x80, 0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81,
0x9F, 0xE0, 0x08, 0x00, 0x10, 0x84, 0x21, 0x08, 0x42, 0x10, 0xFC, 0x80,
0x80, 0x80, 0x83, 0x84, 0x88, 0xF8, 0x88, 0x8C, 0x86, 0x83, 0x92, 0x49,
0x24, 0x93, 0x80, 0xFF, 0xF8, 0x41, 0x84, 0x18, 0x41, 0x84, 0x18, 0x41,
0x84, 0x18, 0x41, 0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF,
0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0x81,
0x81, 0x81, 0xFF, 0x80, 0x80, 0x80, 0xFF, 0x81, 0x81, 0x81, 0x81, 0x81,
0x81, 0xFF, 0x01, 0x01, 0x01, 0xFE, 0x08, 0x20, 0x82, 0x08, 0x20, 0xFE,
0x81, 0x80, 0xFE, 0x01, 0x01, 0x81, 0x7E, 0x84, 0x21, 0xF8, 0x42, 0x10,
0x84, 0x3E, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF, 0xC0, 0x68,
0x18, 0x82, 0x18, 0xC1, 0x10, 0x36, 0x02, 0x80, 0x20, 0xC1, 0x86, 0x87,
0x09, 0x8A, 0x31, 0x32, 0x43, 0x44, 0x83, 0x8F, 0x06, 0x0C, 0x0C, 0x18,
0xC3, 0x46, 0x2C, 0x18, 0x18, 0x2C, 0x46, 0xC3, 0x81, 0x81, 0x81, 0x81,
0x81, 0x81, 0x81, 0xFF, 0x01, 0x01, 0x7F, 0xFF, 0x03, 0x06, 0x0C, 0x30,
0x60, 0xC0, 0xFF, 0x69, 0x29, 0x12, 0x4C, 0xFF, 0xFC, 0xC9, 0x22, 0x52,
0x58, 0xE0, 0xC0 };
const GFXglyph orbitron_light7pt7bGlyphs[] PROGMEM = {
{ 0, 1, 1, 4, 0, 0 }, // 0x20 ' '
{ 1, 1, 10, 3, 1, -9 }, // 0x21 '!'
{ 3, 3, 2, 5, 1, -9 }, // 0x22 '"'
{ 4, 11, 10, 11, 0, -9 }, // 0x23 '#'
{ 18, 10, 14, 11, 1, -11 }, // 0x24 '$'
{ 36, 12, 10, 14, 1, -9 }, // 0x25 '%'
{ 51, 12, 10, 13, 1, -9 }, // 0x26 '&'
{ 66, 1, 2, 3, 1, -9 }, // 0x27 '''
{ 67, 2, 10, 4, 1, -9 }, // 0x28 '('
{ 70, 2, 10, 4, 1, -9 }, // 0x29 ')'
{ 73, 5, 6, 7, 1, -9 }, // 0x2A '*'
{ 77, 5, 6, 6, 0, -6 }, // 0x2B '+'
{ 81, 1, 3, 3, 1, 0 }, // 0x2C ','
{ 82, 5, 1, 7, 1, -4 }, // 0x2D '-'
{ 83, 1, 1, 3, 1, 0 }, // 0x2E '.'
{ 84, 7, 10, 7, 0, -9 }, // 0x2F '/'
{ 93, 10, 10, 12, 1, -9 }, // 0x30 '0'
{ 106, 4, 10, 5, 0, -9 }, // 0x31 '1'
{ 111, 10, 10, 12, 1, -9 }, // 0x32 '2'
{ 124, 9, 10, 11, 1, -9 }, // 0x33 '3'
{ 136, 10, 10, 10, 0, -9 }, // 0x34 '4'
{ 149, 10, 10, 12, 1, -9 }, // 0x35 '5'
{ 162, 10, 10, 12, 1, -9 }, // 0x36 '6'
{ 175, 8, 10, 9, 0, -9 }, // 0x37 '7'
{ 185, 10, 10, 12, 1, -9 }, // 0x38 '8'
{ 198, 10, 10, 12, 1, -9 }, // 0x39 '9'
{ 211, 1, 8, 3, 1, -7 }, // 0x3A ':'
{ 212, 1, 10, 3, 1, -7 }, // 0x3B ';'
{ 214, 6, 8, 7, 0, -7 }, // 0x3C '<'
{ 220, 7, 4, 9, 1, -5 }, // 0x3D '='
{ 224, 5, 8, 7, 1, -7 }, // 0x3E '>'
{ 229, 9, 10, 10, 0, -9 }, // 0x3F '?'
{ 241, 10, 10, 12, 1, -9 }, // 0x40 '@'
{ 254, 10, 10, 12, 1, -9 }, // 0x41 'A'
{ 267, 9, 10, 11, 1, -9 }, // 0x42 'B'
{ 279, 10, 10, 12, 1, -9 }, // 0x43 'C'
{ 292, 10, 10, 12, 1, -9 }, // 0x44 'D'
{ 305, 9, 10, 11, 1, -9 }, // 0x45 'E'
{ 317, 9, 10, 10, 1, -9 }, // 0x46 'F'
{ 329, 10, 10, 12, 1, -9 }, // 0x47 'G'
{ 342, 10, 10, 12, 1, -9 }, // 0x48 'H'
{ 355, 1, 10, 3, 1, -9 }, // 0x49 'I'
{ 357, 10, 10, 11, 0, -9 }, // 0x4A 'J'
{ 370, 9, 10, 11, 1, -9 }, // 0x4B 'K'
{ 382, 10, 10, 11, 1, -9 }, // 0x4C 'L'
{ 395, 11, 10, 13, 1, -9 }, // 0x4D 'M'
{ 409, 10, 10, 12, 1, -9 }, // 0x4E 'N'
{ 422, 10, 10, 12, 1, -9 }, // 0x4F 'O'
{ 435, 10, 10, 12, 1, -9 }, // 0x50 'P'
{ 448, 11, 10, 13, 1, -9 }, // 0x51 'Q'
{ 462, 10, 10, 12, 1, -9 }, // 0x52 'R'
{ 475, 10, 10, 12, 1, -9 }, // 0x53 'S'
{ 488, 9, 10, 11, 1, -9 }, // 0x54 'T'
{ 500, 10, 10, 12, 1, -9 }, // 0x55 'U'
{ 513, 13, 10, 14, 0, -9 }, // 0x56 'V'
{ 530, 16, 10, 17, 0, -9 }, // 0x57 'W'
{ 550, 10, 10, 11, 1, -9 }, // 0x58 'X'
{ 563, 11, 10, 11, 0, -9 }, // 0x59 'Y'
{ 577, 10, 10, 12, 1, -9 }, // 0x5A 'Z'
{ 590, 2, 10, 4, 1, -9 }, // 0x5B '['
{ 593, 7, 10, 7, 0, -9 }, // 0x5C '\'
{ 602, 2, 10, 4, 1, -9 }, // 0x5D ']'
{ 605, 1, 1, 0, 0, 0 }, // 0x5E '^'
{ 606, 10, 1, 12, 1, 1 }, // 0x5F '_'
{ 608, 2, 2, 3, 0, -13 }, // 0x60 '`'
{ 609, 8, 8, 10, 1, -7 }, // 0x61 'a'
{ 617, 8, 11, 10, 1, -10 }, // 0x62 'b'
{ 628, 8, 8, 10, 1, -7 }, // 0x63 'c'
{ 636, 8, 11, 9, 0, -10 }, // 0x64 'd'
{ 647, 8, 8, 10, 1, -7 }, // 0x65 'e'
{ 655, 5, 11, 6, 1, -10 }, // 0x66 'f'
{ 662, 8, 11, 10, 1, -7 }, // 0x67 'g'
{ 673, 8, 11, 10, 1, -10 }, // 0x68 'h'
{ 684, 1, 11, 3, 1, -10 }, // 0x69 'i'
{ 686, 5, 14, 3, -3, -10 }, // 0x6A 'j'
{ 695, 8, 11, 9, 1, -10 }, // 0x6B 'k'
{ 706, 3, 11, 4, 1, -10 }, // 0x6C 'l'
{ 711, 12, 8, 14, 1, -7 }, // 0x6D 'm'
{ 723, 8, 8, 10, 1, -7 }, // 0x6E 'n'
{ 731, 8, 8, 10, 1, -7 }, // 0x6F 'o'
{ 739, 8, 11, 10, 1, -7 }, // 0x70 'p'
{ 750, 8, 11, 9, 0, -7 }, // 0x71 'q'
{ 761, 6, 8, 7, 1, -7 }, // 0x72 'r'
{ 767, 8, 8, 10, 1, -7 }, // 0x73 's'
{ 775, 5, 11, 6, 1, -10 }, // 0x74 't'
{ 782, 8, 8, 10, 1, -7 }, // 0x75 'u'
{ 790, 11, 8, 11, 0, -7 }, // 0x76 'v'
{ 801, 15, 8, 15, 0, -7 }, // 0x77 'w'
{ 816, 8, 8, 10, 1, -7 }, // 0x78 'x'
{ 824, 8, 11, 10, 1, -7 }, // 0x79 'y'
{ 835, 8, 8, 10, 1, -7 }, // 0x7A 'z'
{ 843, 3, 10, 4, 0, -9 }, // 0x7B '{'
{ 847, 1, 14, 3, 1, -11 }, // 0x7C '|'
{ 849, 3, 10, 4, 1, -9 }, // 0x7D '}'
{ 853, 5, 2, 6, 0, -4 } }; // 0x7E '~'
const GFXfont orbitron_light7pt7b PROGMEM = {
(uint8_t *)orbitron_light7pt7bBitmaps,
(GFXglyph *)orbitron_light7pt7bGlyphs,
0x20, 0x7E, 14 };
// Approx. 1527 bytes
|
ingoha/TTGO-T-Wristband | include/fonts/Orbitron_Light_5.h | <reponame>ingoha/TTGO-T-Wristband
const uint8_t Orbitron_Light5pt7bBitmaps[] PROGMEM = {
0x00, 0xFA, 0xC0, 0x12, 0x7F, 0x24, 0x24, 0xDE, 0x68, 0x48, 0x10, 0xFF,
0x91, 0x90, 0xFF, 0x11, 0x91, 0xFF, 0x10, 0xF0, 0xA4, 0x4F, 0x20, 0x30,
0x13, 0xC8, 0x94, 0x3C, 0x7E, 0x20, 0x90, 0x16, 0x08, 0xD4, 0x1B, 0xFE,
0x80, 0xEA, 0xAC, 0xD5, 0x5C, 0x27, 0xC8, 0xA0, 0x21, 0x3E, 0x40, 0xC0,
0xE0, 0x80, 0x08, 0x44, 0x44, 0x42, 0x00, 0xFF, 0x06, 0x3C, 0x9A, 0x38,
0x7F, 0x80, 0x74, 0x92, 0x48, 0xFF, 0x04, 0x0F, 0xF8, 0x10, 0x3F, 0x80,
0xFF, 0x01, 0x01, 0x3F, 0x01, 0x01, 0xFF, 0x0C, 0x38, 0x92, 0x2F, 0xE0,
0x81, 0x00, 0xFF, 0x02, 0x07, 0xF0, 0x30, 0x7F, 0x80, 0xFD, 0x02, 0x07,
0xF8, 0x30, 0x7F, 0x80, 0xFC, 0x10, 0x41, 0x04, 0x10, 0x40, 0xFF, 0x06,
0x0F, 0xF8, 0x30, 0x7F, 0x80, 0xFF, 0x06, 0x0F, 0xF0, 0x20, 0x7F, 0x80,
0x84, 0x86, 0x12, 0xCC, 0x21, 0xF8, 0x3E, 0x8C, 0x33, 0xC8, 0xFE, 0x04,
0x09, 0xF2, 0x00, 0x08, 0x00, 0xFF, 0x81, 0xBD, 0xA5, 0xBF, 0x80, 0xFF,
0xFF, 0x06, 0x0F, 0xF8, 0x30, 0x60, 0x80, 0xFF, 0x06, 0x0F, 0xF8, 0x30,
0x7F, 0x80, 0xFF, 0x02, 0x04, 0x08, 0x10, 0x3F, 0x80, 0xFF, 0x06, 0x0C,
0x18, 0x30, 0x7F, 0x80, 0xFF, 0x02, 0x07, 0xE8, 0x10, 0x3F, 0x80, 0xFF,
0x02, 0x07, 0xE8, 0x10, 0x20, 0x00, 0xFF, 0x02, 0x04, 0x78, 0x30, 0x7F,
0x80, 0x83, 0x06, 0x0F, 0xF8, 0x30, 0x60, 0x80, 0xFE, 0x02, 0x04, 0x08,
0x10, 0x30, 0x7F, 0x80, 0x83, 0x0A, 0x27, 0x88, 0x90, 0xA0, 0x80, 0x81,
0x02, 0x04, 0x08, 0x10, 0x3F, 0x80, 0x81, 0xC3, 0xA5, 0x99, 0x91, 0x81,
0x81, 0x83, 0x86, 0x8C, 0x98, 0xB0, 0xE0, 0x80, 0xFF, 0x06, 0x0C, 0x18,
0x30, 0x7F, 0x80, 0xFF, 0x06, 0x0F, 0xF8, 0x10, 0x20, 0x00, 0xFE, 0x82,
0x82, 0x82, 0x82, 0x82, 0xFF, 0xFF, 0x06, 0x0F, 0xF8, 0x90, 0xA0, 0x80,
0xFF, 0x02, 0x07, 0xF0, 0x20, 0x7F, 0x80, 0xFE, 0x20, 0x40, 0x81, 0x02,
0x04, 0x00, 0x83, 0x06, 0x0C, 0x18, 0x30, 0x7F, 0x80, 0xC0, 0xD0, 0x22,
0x10, 0x84, 0x12, 0x03, 0x00, 0xC0, 0x86, 0x28, 0xC5, 0x28, 0x94, 0xA2,
0x94, 0x63, 0x04, 0x20, 0xC3, 0x24, 0x18, 0x18, 0x18, 0x24, 0xC3, 0x82,
0x88, 0xA1, 0x41, 0x02, 0x04, 0x00, 0xFE, 0x08, 0x20, 0x86, 0x10, 0x3F,
0x80, 0xEA, 0xAC, 0x84, 0x10, 0x41, 0x04, 0x20, 0xD5, 0x5C, 0x00, 0xFE,
0x80, 0xFC, 0x10, 0x7F, 0x87, 0xF0, 0x82, 0x0F, 0xE1, 0x86, 0x18, 0x7F,
0xFE, 0x08, 0x20, 0x83, 0xF0, 0x04, 0x1F, 0xE1, 0x86, 0x18, 0x7F, 0xFE,
0x18, 0x7F, 0x83, 0xF0, 0xF8, 0xF8, 0x88, 0x88, 0xFE, 0x18, 0x61, 0x87,
0xF0, 0x5F, 0x82, 0x0F, 0xE1, 0x86, 0x18, 0x61, 0xBF, 0x10, 0x01, 0x11,
0x11, 0x11, 0xF0, 0x82, 0x08, 0xE2, 0x93, 0xC9, 0xA3, 0xAA, 0xAB, 0xFF,
0xE2, 0x18, 0x86, 0x21, 0x88, 0x62, 0x10, 0xFE, 0x18, 0x61, 0x86, 0x10,
0xFE, 0x18, 0x61, 0x87, 0xF0, 0xFE, 0x18, 0x61, 0x87, 0xF8, 0x20, 0xFE,
0x18, 0x61, 0x87, 0xF0, 0x41, 0xFC, 0x21, 0x08, 0x40, 0xFF, 0x02, 0x07,
0xF0, 0x3F, 0xC0, 0x88, 0xF8, 0x88, 0x8F, 0x86, 0x18, 0x61, 0x87, 0xF0,
0x83, 0x42, 0x44, 0x24, 0x18, 0x18, 0x84, 0x52, 0x94, 0xA4, 0xCE, 0x31,
0x8C, 0x40, 0xC4, 0xA1, 0x0C, 0x2B, 0x10, 0x83, 0x06, 0x0C, 0x18, 0x3F,
0xC0, 0x9F, 0xF8, 0x44, 0xC8, 0x7C, 0xEA, 0xAC, 0xFF, 0x80, 0xD5, 0x5C,
0xF0 };
const GFXglyph Orbitron_Light5pt7bGlyphs[] PROGMEM = {
{ 0, 1, 1, 3, 0, 0 }, // 0x20 ' '
{ 1, 1, 7, 2, 0, -6 }, // 0x21 '!'
{ 2, 2, 1, 4, 1, -6 }, // 0x22 '"'
{ 3, 8, 7, 8, 0, -6 }, // 0x23 '#'
{ 10, 8, 9, 8, 0, -7 }, // 0x24 '$'
{ 19, 10, 7, 11, 0, -6 }, // 0x25 '%'
{ 28, 9, 7, 10, 0, -6 }, // 0x26 '&'
{ 36, 1, 1, 2, 1, -6 }, // 0x27 '''
{ 37, 2, 7, 3, 0, -6 }, // 0x28 '('
{ 39, 2, 7, 3, 0, -6 }, // 0x29 ')'
{ 41, 5, 4, 5, 0, -6 }, // 0x2A '*'
{ 44, 5, 4, 4, 0, -4 }, // 0x2B '+'
{ 47, 1, 2, 2, 0, 0 }, // 0x2C ','
{ 48, 3, 1, 5, 1, -2 }, // 0x2D '-'
{ 49, 1, 1, 2, 0, 0 }, // 0x2E '.'
{ 50, 5, 7, 5, 0, -6 }, // 0x2F '/'
{ 55, 7, 7, 9, 1, -6 }, // 0x30 '0'
{ 62, 3, 7, 4, 0, -6 }, // 0x31 '1'
{ 65, 7, 7, 9, 1, -6 }, // 0x32 '2'
{ 72, 8, 7, 9, 0, -6 }, // 0x33 '3'
{ 79, 7, 7, 7, 0, -6 }, // 0x34 '4'
{ 86, 7, 7, 9, 1, -6 }, // 0x35 '5'
{ 93, 7, 7, 9, 1, -6 }, // 0x36 '6'
{ 100, 6, 7, 7, 0, -6 }, // 0x37 '7'
{ 106, 7, 7, 9, 1, -6 }, // 0x38 '8'
{ 113, 7, 7, 9, 1, -6 }, // 0x39 '9'
{ 120, 1, 6, 2, 0, -5 }, // 0x3A ':'
{ 121, 1, 7, 2, 0, -5 }, // 0x3B ';'
{ 122, 4, 6, 5, 0, -5 }, // 0x3C '<'
{ 125, 5, 3, 6, 1, -3 }, // 0x3D '='
{ 127, 4, 6, 5, 1, -5 }, // 0x3E '>'
{ 130, 7, 7, 8, 0, -6 }, // 0x3F '?'
{ 137, 8, 7, 9, 0, -6 }, // 0x40 '@'
{ 144, 7, 7, 9, 1, -6 }, // 0x41 'A'
{ 151, 7, 7, 9, 1, -6 }, // 0x42 'B'
{ 158, 7, 7, 8, 0, -6 }, // 0x43 'C'
{ 165, 7, 7, 9, 1, -6 }, // 0x44 'D'
{ 172, 7, 7, 8, 0, -6 }, // 0x45 'E'
{ 179, 7, 7, 7, 0, -6 }, // 0x46 'F'
{ 186, 7, 7, 9, 1, -6 }, // 0x47 'G'
{ 193, 7, 7, 9, 1, -6 }, // 0x48 'H'
{ 200, 1, 7, 2, 0, -6 }, // 0x49 'I'
{ 201, 7, 7, 8, 0, -6 }, // 0x4A 'J'
{ 208, 7, 7, 8, 0, -6 }, // 0x4B 'K'
{ 215, 7, 7, 8, 0, -6 }, // 0x4C 'L'
{ 222, 8, 7, 10, 1, -6 }, // 0x4D 'M'
{ 229, 7, 7, 9, 1, -6 }, // 0x4E 'N'
{ 236, 7, 7, 9, 1, -6 }, // 0x4F 'O'
{ 243, 7, 7, 9, 1, -6 }, // 0x50 'P'
{ 250, 8, 7, 9, 1, -6 }, // 0x51 'Q'
{ 257, 7, 7, 9, 1, -6 }, // 0x52 'R'
{ 264, 7, 7, 9, 1, -6 }, // 0x53 'S'
{ 271, 7, 7, 8, 0, -6 }, // 0x54 'T'
{ 278, 7, 7, 9, 1, -6 }, // 0x55 'U'
{ 285, 10, 7, 10, 0, -6 }, // 0x56 'V'
{ 294, 11, 7, 12, 0, -6 }, // 0x57 'W'
{ 304, 8, 7, 8, 0, -6 }, // 0x58 'X'
{ 311, 7, 7, 8, 0, -6 }, // 0x59 'Y'
{ 318, 7, 7, 8, 1, -6 }, // 0x5A 'Z'
{ 325, 2, 7, 3, 0, -6 }, // 0x5B '['
{ 327, 5, 7, 5, 0, -6 }, // 0x5C '\'
{ 332, 2, 7, 3, 0, -6 }, // 0x5D ']'
{ 334, 1, 1, 0, 0, 0 }, // 0x5E '^'
{ 335, 7, 1, 8, 1, 1 }, // 0x5F '_'
{ 336, 1, 1, 2, 0, -9 }, // 0x60 '`'
{ 337, 6, 6, 8, 1, -5 }, // 0x61 'a'
{ 342, 6, 8, 8, 1, -7 }, // 0x62 'b'
{ 348, 6, 6, 7, 0, -5 }, // 0x63 'c'
{ 353, 6, 8, 7, 0, -7 }, // 0x64 'd'
{ 359, 6, 6, 8, 1, -5 }, // 0x65 'e'
{ 364, 4, 8, 4, 0, -7 }, // 0x66 'f'
{ 368, 6, 8, 7, 0, -5 }, // 0x67 'g'
{ 374, 6, 8, 8, 1, -7 }, // 0x68 'h'
{ 380, 1, 8, 2, 0, -7 }, // 0x69 'i'
{ 381, 4, 11, 3, -2, -7 }, // 0x6A 'j'
{ 387, 6, 8, 6, 0, -7 }, // 0x6B 'k'
{ 393, 2, 8, 3, 0, -7 }, // 0x6C 'l'
{ 395, 10, 6, 11, 0, -5 }, // 0x6D 'm'
{ 403, 6, 6, 8, 1, -5 }, // 0x6E 'n'
{ 408, 6, 6, 8, 1, -5 }, // 0x6F 'o'
{ 413, 6, 8, 8, 1, -5 }, // 0x70 'p'
{ 419, 6, 8, 7, 0, -5 }, // 0x71 'q'
{ 425, 5, 6, 5, 0, -5 }, // 0x72 'r'
{ 429, 7, 6, 8, 0, -5 }, // 0x73 's'
{ 435, 4, 8, 4, 0, -7 }, // 0x74 't'
{ 439, 6, 6, 8, 1, -5 }, // 0x75 'u'
{ 444, 8, 6, 8, 0, -5 }, // 0x76 'v'
{ 450, 10, 6, 11, 0, -5 }, // 0x77 'w'
{ 458, 6, 6, 7, 0, -5 }, // 0x78 'x'
{ 463, 7, 8, 8, 0, -5 }, // 0x79 'y'
{ 470, 5, 6, 7, 1, -5 }, // 0x7A 'z'
{ 474, 2, 7, 3, 0, -6 }, // 0x7B '{'
{ 476, 1, 9, 2, 0, -7 }, // 0x7C '|'
{ 478, 2, 7, 3, 0, -6 }, // 0x7D '}'
{ 480, 4, 1, 4, 0, -2 } }; // 0x7E '~'
const GFXfont Orbitron_Light5pt7b PROGMEM = {
(uint8_t *)Orbitron_Light5pt7bBitmaps,
(GFXglyph *)Orbitron_Light5pt7bGlyphs,
0x20, 0x7E, 10 };
// Approx. 1153 bytes
|
ingoha/TTGO-T-Wristband | include/fonts/Orbitron_Medium_5.h | <filename>include/fonts/Orbitron_Medium_5.h
// Created by http://oleddisplay.squix.ch/ Consider a donation
// In case of problems make sure that you are using the font file with the correct version!
const uint8_t Orbitron_Medium_5Bitmaps[] PROGMEM = {
// Bitmap Data:
0x00, // ' '
0xAA, // '!'
0xC0, // '"'
0x57,0x9D,0x40, // '#'
0xF6,0x1D,0xE4,0x00, // '$'
0x4B,0x43,0x36, // '%'
0x72,0x0F,0x3E, // '&'
0x80, // '''
0xAA, // '('
0xAA, // ')'
0x58, // '*'
0xC8, // '+'
0xA0, // ','
0xC0, // '-'
0x80, // '.'
0x24,0x48, // '/'
0x75,0xB5,0xE0, // '0'
0x59,0x20, // '1'
0xF0,0xB9,0xE0, // '2'
0xE0,0x9D,0xE0, // '3'
0x26,0xE2, // '4'
0xF4,0x1D,0xE0, // '5'
0x64,0x3D,0xE0, // '6'
0xE2,0x22, // '7'
0x74,0xBD,0xE0, // '8'
0x74,0x9D,0xE0, // '9'
0x88, // ':'
0x8A, // ';'
0x51,0x00, // '<'
0xE0, // '='
0x8A,0x00, // '>'
0xE2,0x68, // '?'
0x77,0xB5,0xE0, // '@'
0x74,0xBD,0x20, // 'A'
0xE4,0xBD,0xE0, // 'B'
0x74,0x21,0xE0, // 'C'
0xF4,0xA5,0xE0, // 'D'
0xF4,0x39,0xE0, // 'E'
0xF4,0x39,0x00, // 'F'
0x74,0x2D,0xE0, // 'G'
0x94,0xBD,0x20, // 'H'
0xAA, // 'I'
0x10,0x85,0xE0, // 'J'
0x95,0x39,0x20, // 'K'
0x84,0x21,0xE0, // 'L'
0x96,0xAD,0x20, // 'M'
0x96,0xAD,0x20, // 'N'
0x74,0xA5,0xE0, // 'O'
0xF4,0xBD,0x00, // 'P'
0x74,0xA5,0xE0, // 'Q'
0xF4,0xBD,0x20, // 'R'
0x74,0x1D,0xE0, // 'S'
0xF2,0x10,0x80, // 'T'
0x94,0xA5,0xE0, // 'U'
0x89,0x45,0x08, // 'V'
0xA5,0x69,0x62,0x40, // 'W'
0x93,0x19,0x20, // 'X'
0x93,0x08,0x40, // 'Y'
0xF1,0x11,0xE0, // 'Z'
0xAA, // '['
0x88,0x42, // '\'
0xAA, // ']'
0x00, // '^'
0xF0, // '_'
0x80, // '`'
0xEE,0xE0, // 'a'
0x8E,0xAE, // 'b'
0xE8,0xE0, // 'c'
0x2E,0xAE, // 'd'
0xEE,0xE0, // 'e'
0xDA,0x40, // 'f'
0xEA,0xE6, // 'g'
0x8E,0xAA, // 'h'
0xAA, // 'i'
0x49,0x2C, // 'j'
0x8A,0xCA, // 'k'
0xAA, // 'l'
0xFA,0xAA,0x80, // 'm'
0xEA,0xA0, // 'n'
0xEA,0xE0, // 'o'
0xEA,0xE8, // 'p'
0xEA,0xE2, // 'q'
0xE8,0x80, // 'r'
0xEE,0xE0, // 's'
0x9A,0x60, // 't'
0xAA,0xE0, // 'u'
0x93,0x18, // 'v'
0xA9,0x65,0x00, // 'w'
0xA4,0xA0, // 'x'
0xAA,0xE6, // 'y'
0xE4,0xE0, // 'z'
0xAA, // '{'
0xAA,0x80, // '|'
0xAA // '}'
};
const GFXglyph Orbitron_Medium_5Glyphs[] PROGMEM = {
// bitmapOffset, width, height, xAdvance, xOffset, yOffset
{ 0, 1, 1, 2, 0, 0 }, // ' '
{ 1, 2, 4, 2, 0, -4 }, // '!'
{ 2, 3, 1, 3, 0, -4 }, // '"'
{ 3, 5, 4, 5, 0, -4 }, // '#'
{ 6, 5, 5, 5, 0, -4 }, // '$'
{ 10, 6, 4, 6, 0, -4 }, // '%'
{ 13, 6, 4, 6, 0, -4 }, // '&'
{ 16, 2, 1, 2, 0, -4 }, // '''
{ 17, 2, 4, 2, 0, -4 }, // '('
{ 18, 2, 4, 2, 0, -4 }, // ')'
{ 19, 3, 2, 3, 0, -4 }, // '*'
{ 20, 3, 2, 3, 0, -2 }, // '+'
{ 21, 2, 2, 2, 0, -1 }, // ','
{ 22, 3, 1, 4, 0, -2 }, // '-'
{ 23, 2, 1, 2, 0, -1 }, // '.'
{ 24, 4, 4, 4, 0, -4 }, // '/'
{ 26, 5, 4, 5, 0, -4 }, // '0'
{ 29, 3, 4, 3, 0, -4 }, // '1'
{ 31, 5, 4, 5, 0, -4 }, // '2'
{ 34, 5, 4, 5, 0, -4 }, // '3'
{ 37, 4, 4, 5, 0, -4 }, // '4'
{ 39, 5, 4, 5, 0, -4 }, // '5'
{ 42, 5, 4, 5, 0, -4 }, // '6'
{ 45, 4, 4, 4, 0, -4 }, // '7'
{ 47, 5, 4, 5, 0, -4 }, // '8'
{ 50, 5, 4, 5, 0, -4 }, // '9'
{ 53, 2, 3, 2, 0, -3 }, // ':'
{ 54, 2, 4, 2, 0, -3 }, // ';'
{ 55, 3, 3, 3, 0, -3 }, // '<'
{ 57, 4, 1, 4, 0, -2 }, // '='
{ 58, 3, 3, 3, 0, -3 }, // '>'
{ 60, 4, 4, 4, 0, -4 }, // '?'
{ 62, 5, 4, 5, 0, -4 }, // '@'
{ 65, 5, 4, 5, 0, -4 }, // 'A'
{ 68, 5, 4, 5, 0, -4 }, // 'B'
{ 71, 5, 4, 5, 0, -4 }, // 'C'
{ 74, 5, 4, 5, 0, -4 }, // 'D'
{ 77, 5, 4, 5, 0, -4 }, // 'E'
{ 80, 5, 4, 5, 0, -4 }, // 'F'
{ 83, 5, 4, 5, 0, -4 }, // 'G'
{ 86, 5, 4, 5, 0, -4 }, // 'H'
{ 89, 2, 4, 2, 0, -4 }, // 'I'
{ 90, 5, 4, 5, 0, -4 }, // 'J'
{ 93, 5, 4, 5, 0, -4 }, // 'K'
{ 96, 5, 4, 5, 0, -4 }, // 'L'
{ 99, 5, 4, 6, 0, -4 }, // 'M'
{ 102, 5, 4, 5, 0, -4 }, // 'N'
{ 105, 5, 4, 5, 0, -4 }, // 'O'
{ 108, 5, 4, 5, 0, -4 }, // 'P'
{ 111, 5, 4, 5, 0, -4 }, // 'Q'
{ 114, 5, 4, 5, 0, -4 }, // 'R'
{ 117, 5, 4, 5, 0, -4 }, // 'S'
{ 120, 5, 4, 5, 0, -4 }, // 'T'
{ 123, 5, 4, 5, 0, -4 }, // 'U'
{ 126, 6, 4, 6, 0, -4 }, // 'V'
{ 129, 7, 4, 7, 0, -4 }, // 'W'
{ 133, 5, 4, 5, 0, -4 }, // 'X'
{ 136, 5, 4, 5, 0, -4 }, // 'Y'
{ 139, 5, 4, 5, 0, -4 }, // 'Z'
{ 142, 2, 4, 2, 0, -4 }, // '['
{ 143, 4, 4, 4, 0, -4 }, // '\'
{ 145, 2, 4, 2, 0, -4 }, // ']'
{ 146, 1, 1, 1, 0, 0 }, // '^'
{ 147, 5, 1, 5, 0, 0 }, // '_'
{ 148, 2, 1, 2, 0, -5 }, // '`'
{ 149, 4, 3, 4, 0, -3 }, // 'a'
{ 151, 4, 4, 4, 0, -4 }, // 'b'
{ 153, 4, 3, 4, 0, -3 }, // 'c'
{ 155, 4, 4, 4, 0, -4 }, // 'd'
{ 157, 4, 3, 4, 0, -3 }, // 'e'
{ 159, 3, 4, 3, 0, -4 }, // 'f'
{ 161, 4, 4, 4, 0, -3 }, // 'g'
{ 163, 4, 4, 4, 0, -4 }, // 'h'
{ 165, 2, 4, 2, 0, -4 }, // 'i'
{ 166, 3, 5, 2, -1, -4 }, // 'j'
{ 168, 4, 4, 4, 0, -4 }, // 'k'
{ 170, 2, 4, 3, 0, -4 }, // 'l'
{ 171, 6, 3, 6, 0, -3 }, // 'm'
{ 174, 4, 3, 4, 0, -3 }, // 'n'
{ 176, 4, 3, 4, 0, -3 }, // 'o'
{ 178, 4, 4, 4, 0, -3 }, // 'p'
{ 180, 4, 4, 4, 0, -3 }, // 'q'
{ 182, 4, 3, 4, 0, -3 }, // 'r'
{ 184, 4, 3, 4, 0, -3 }, // 's'
{ 186, 3, 4, 3, 0, -4 }, // 't'
{ 188, 4, 3, 4, 0, -3 }, // 'u'
{ 190, 5, 3, 5, 0, -3 }, // 'v'
{ 192, 6, 3, 6, 0, -3 }, // 'w'
{ 195, 4, 3, 4, 0, -3 }, // 'x'
{ 197, 4, 4, 4, 0, -3 }, // 'y'
{ 199, 4, 3, 4, 0, -3 }, // 'z'
{ 201, 2, 4, 2, 0, -4 }, // '{'
{ 202, 2, 5, 2, 0, -4 }, // '|'
{ 204, 2, 4, 2, 0, -4 } // '}'
};
const GFXfont Orbitron_Medium_5 PROGMEM = {
(uint8_t *)Orbitron_Medium_5Bitmaps,(GFXglyph *)Orbitron_Medium_5Glyphs,0x20, 0x7E, 6};
|
ingoha/TTGO-T-Wristband | include/fonts/Orbitron_Light_6.h | const uint8_t Orbitron_Light6pt7bBitmaps[] PROGMEM = {
0x00, 0xFC, 0x80, 0xB4, 0x08, 0x88, 0x9F, 0xE2, 0x22, 0x21, 0x13, 0xFE,
0x84, 0x44, 0x00, 0x08, 0x7F, 0xE2, 0x31, 0x08, 0x87, 0xFC, 0x22, 0x11,
0x88, 0xFF, 0xC2, 0x00, 0xF8, 0x51, 0x1A, 0x26, 0x7D, 0x00, 0x40, 0x13,
0xCC, 0x4B, 0x09, 0x41, 0xE0, 0x7F, 0x10, 0x24, 0x01, 0x00, 0xB0, 0x22,
0x48, 0x72, 0x02, 0xFF, 0x40, 0xC0, 0xEA, 0xAA, 0xC0, 0xD5, 0x55, 0xC0,
0x25, 0x5C, 0xA5, 0x00, 0x21, 0x3E, 0x42, 0x00, 0xE0, 0xF0, 0x80, 0x04,
0x10, 0x84, 0x10, 0x84, 0x20, 0x80, 0xFF, 0x81, 0x83, 0x85, 0x89, 0xB1,
0xE1, 0xC1, 0xFF, 0x37, 0x59, 0x11, 0x11, 0x10, 0xFF, 0x81, 0x01, 0x01,
0xFF, 0x80, 0x80, 0x80, 0xFF, 0xFF, 0x81, 0x01, 0x01, 0x7F, 0x01, 0x01,
0x81, 0xFF, 0x06, 0x0E, 0x1A, 0x32, 0x62, 0xC2, 0xFF, 0x02, 0x02, 0xFF,
0x80, 0x80, 0x80, 0xFF, 0x01, 0x01, 0x81, 0xFF, 0xFE, 0x80, 0x80, 0x80,
0xFF, 0x81, 0x81, 0x81, 0xFF, 0xFE, 0x04, 0x08, 0x10, 0x20, 0x40, 0x81,
0x02, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0xFF, 0x81,
0x81, 0x81, 0xFF, 0x01, 0x01, 0x01, 0xFF, 0x82, 0x83, 0x80, 0x09, 0x99,
0x06, 0x18, 0x20, 0xFC, 0x0F, 0xC0, 0x86, 0x0C, 0x13, 0x62, 0x00, 0xFF,
0x01, 0x01, 0x01, 0x01, 0x3F, 0x20, 0x00, 0x20, 0xFF, 0x81, 0x81, 0xBD,
0xA5, 0xA5, 0xBF, 0x80, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0x81, 0xFF, 0x81,
0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0xFF,
0xC0, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01, 0x00, 0xFF, 0x80, 0xFF, 0x81,
0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF, 0xFF, 0x80, 0x80, 0x80, 0xFE,
0x80, 0x80, 0x80, 0xFF, 0xFF, 0x80, 0x80, 0x80, 0xFE, 0x80, 0x80, 0x80,
0x80, 0xFF, 0x81, 0x80, 0x80, 0x87, 0x81, 0x81, 0x81, 0xFF, 0x80, 0xC0,
0x60, 0x30, 0x1F, 0xFC, 0x06, 0x03, 0x01, 0x80, 0x80, 0xFF, 0x80, 0x00,
0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x03, 0x01, 0xFF, 0x80, 0x81, 0x82,
0x84, 0x88, 0xF8, 0x88, 0x84, 0x82, 0x81, 0x80, 0x40, 0x20, 0x10, 0x08,
0x04, 0x02, 0x01, 0x00, 0xFF, 0x80, 0xC0, 0xF8, 0x7A, 0x16, 0x49, 0x8C,
0x62, 0x18, 0x06, 0x01, 0x80, 0x40, 0xC1, 0xC1, 0xA1, 0x91, 0x99, 0x89,
0x85, 0x83, 0x83, 0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF,
0xFF, 0x81, 0x81, 0x81, 0x81, 0xFF, 0x80, 0x80, 0x80, 0xFF, 0x40, 0xA0,
0x50, 0x28, 0x14, 0x0A, 0x05, 0x02, 0xFF, 0x80, 0xFF, 0x81, 0x81, 0x81,
0x81, 0xFF, 0x84, 0x82, 0x83, 0xFF, 0x81, 0x80, 0x80, 0xFF, 0x01, 0x01,
0x81, 0xFF, 0xFF, 0x84, 0x02, 0x01, 0x00, 0x80, 0x40, 0x20, 0x10, 0x08,
0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF, 0xC0, 0x34,
0x02, 0x20, 0x42, 0x0C, 0x10, 0x81, 0x90, 0x09, 0x00, 0x60, 0x06, 0x00,
0xC3, 0x05, 0x0C, 0x24, 0x28, 0x89, 0x22, 0x24, 0x90, 0x91, 0x41, 0x87,
0x06, 0x18, 0x18, 0x20, 0x83, 0x42, 0x24, 0x38, 0x10, 0x38, 0x24, 0x42,
0x83, 0xC1, 0xA0, 0x88, 0x82, 0x81, 0xC0, 0x40, 0x20, 0x10, 0x08, 0x00,
0xFF, 0x01, 0x06, 0x0C, 0x18, 0x30, 0x40, 0x80, 0xFF, 0xEA, 0xAA, 0xC0,
0x82, 0x04, 0x08, 0x10, 0x40, 0x81, 0x04, 0xD5, 0x55, 0xC0, 0x00, 0xFF,
0x90, 0xFE, 0x04, 0x0F, 0xF8, 0x30, 0x7F, 0x80, 0x81, 0x03, 0xFC, 0x18,
0x30, 0x60, 0xC1, 0xFE, 0xFF, 0x02, 0x04, 0x08, 0x10, 0x3F, 0x80, 0x02,
0x07, 0xFC, 0x18, 0x30, 0x60, 0xC1, 0xFE, 0xFF, 0x06, 0x0F, 0xF8, 0x10,
0x3F, 0x80, 0xF8, 0xF8, 0x88, 0x88, 0x80, 0xFF, 0x81, 0x81, 0x81, 0x81,
0x81, 0xFF, 0x01, 0x01, 0x3F, 0x81, 0x03, 0xFC, 0x18, 0x30, 0x60, 0xC1,
0x82, 0xBF, 0x80, 0x10, 0x11, 0x11, 0x11, 0x11, 0x1F, 0x81, 0x02, 0x1C,
0x69, 0x9E, 0x26, 0x46, 0x86, 0x92, 0x49, 0x24, 0xE0, 0xFF, 0xE2, 0x18,
0x86, 0x21, 0x88, 0x62, 0x18, 0x84, 0xFF, 0x06, 0x0C, 0x18, 0x30, 0x60,
0x80, 0xFF, 0x06, 0x0C, 0x18, 0x30, 0x7F, 0x80, 0xFF, 0x06, 0x0C, 0x18,
0x30, 0x7F, 0xC0, 0x81, 0x00, 0xFF, 0x06, 0x0C, 0x18, 0x30, 0x7F, 0x81,
0x02, 0x04, 0xFC, 0x21, 0x08, 0x42, 0x00, 0xFF, 0x06, 0x07, 0xF0, 0x30,
0x7F, 0x80, 0x88, 0xF8, 0x88, 0x88, 0xF0, 0x83, 0x06, 0x0C, 0x18, 0x30,
0x7F, 0x80, 0xC0, 0xA0, 0x88, 0x44, 0x41, 0x20, 0xA0, 0x30, 0xC2, 0x1A,
0x28, 0x91, 0x44, 0x59, 0x42, 0x8A, 0x0C, 0x60, 0x41, 0x00, 0x86, 0x90,
0xE1, 0x83, 0x89, 0x21, 0x80, 0x83, 0x06, 0x0C, 0x18, 0x30, 0x7F, 0x81,
0x02, 0xFC, 0xFE, 0x0C, 0x21, 0x86, 0x10, 0x3F, 0x80, 0x69, 0x28, 0x92,
0x60, 0xFF, 0xE0, 0xC9, 0x22, 0x92, 0xC0, 0xF0 };
const GFXglyph Orbitron_Light6pt7bGlyphs[] PROGMEM = {
{ 0, 1, 1, 3, 0, 0 }, // 0x20 ' '
{ 1, 1, 9, 3, 1, -8 }, // 0x21 '!'
{ 3, 3, 2, 5, 1, -8 }, // 0x22 '"'
{ 4, 9, 9, 10, 0, -8 }, // 0x23 '#'
{ 15, 9, 11, 9, 0, -9 }, // 0x24 '$'
{ 28, 11, 9, 12, 0, -8 }, // 0x25 '%'
{ 41, 10, 9, 11, 1, -8 }, // 0x26 '&'
{ 53, 1, 2, 3, 1, -8 }, // 0x27 '''
{ 54, 2, 9, 3, 1, -8 }, // 0x28 '('
{ 57, 2, 9, 3, 1, -8 }, // 0x29 ')'
{ 60, 5, 5, 6, 0, -8 }, // 0x2A '*'
{ 64, 5, 5, 5, 0, -5 }, // 0x2B '+'
{ 68, 1, 3, 2, 1, 0 }, // 0x2C ','
{ 69, 4, 1, 6, 1, -3 }, // 0x2D '-'
{ 70, 1, 1, 3, 1, 0 }, // 0x2E '.'
{ 71, 6, 9, 6, 0, -8 }, // 0x2F '/'
{ 78, 8, 9, 10, 1, -8 }, // 0x30 '0'
{ 87, 4, 9, 5, 0, -8 }, // 0x31 '1'
{ 92, 8, 9, 10, 1, -8 }, // 0x32 '2'
{ 101, 8, 9, 10, 1, -8 }, // 0x33 '3'
{ 110, 8, 9, 9, 0, -8 }, // 0x34 '4'
{ 119, 8, 9, 10, 1, -8 }, // 0x35 '5'
{ 128, 8, 9, 10, 1, -8 }, // 0x36 '6'
{ 137, 7, 9, 8, 0, -8 }, // 0x37 '7'
{ 145, 8, 9, 10, 1, -8 }, // 0x38 '8'
{ 154, 8, 9, 10, 1, -8 }, // 0x39 '9'
{ 163, 1, 7, 3, 1, -6 }, // 0x3A ':'
{ 164, 1, 9, 2, 1, -6 }, // 0x3B ';'
{ 166, 5, 7, 6, 0, -6 }, // 0x3C '<'
{ 171, 6, 3, 8, 1, -4 }, // 0x3D '='
{ 174, 5, 7, 6, 1, -6 }, // 0x3E '>'
{ 179, 8, 9, 9, 0, -8 }, // 0x3F '?'
{ 188, 8, 9, 10, 1, -8 }, // 0x40 '@'
{ 197, 8, 9, 10, 1, -8 }, // 0x41 'A'
{ 206, 8, 9, 10, 1, -8 }, // 0x42 'B'
{ 215, 9, 9, 10, 1, -8 }, // 0x43 'C'
{ 226, 8, 9, 10, 1, -8 }, // 0x44 'D'
{ 235, 8, 9, 9, 1, -8 }, // 0x45 'E'
{ 244, 8, 9, 9, 1, -8 }, // 0x46 'F'
{ 253, 8, 9, 10, 1, -8 }, // 0x47 'G'
{ 262, 9, 9, 11, 1, -8 }, // 0x48 'H'
{ 273, 1, 9, 3, 1, -8 }, // 0x49 'I'
{ 275, 9, 9, 10, 0, -8 }, // 0x4A 'J'
{ 286, 8, 9, 10, 1, -8 }, // 0x4B 'K'
{ 295, 9, 9, 9, 1, -8 }, // 0x4C 'L'
{ 306, 10, 9, 12, 1, -8 }, // 0x4D 'M'
{ 318, 8, 9, 10, 1, -8 }, // 0x4E 'N'
{ 327, 8, 9, 10, 1, -8 }, // 0x4F 'O'
{ 336, 8, 9, 10, 1, -8 }, // 0x50 'P'
{ 345, 9, 9, 10, 1, -8 }, // 0x51 'Q'
{ 356, 8, 9, 10, 1, -8 }, // 0x52 'R'
{ 365, 8, 9, 10, 1, -8 }, // 0x53 'S'
{ 374, 9, 9, 9, 0, -8 }, // 0x54 'T'
{ 385, 8, 9, 10, 1, -8 }, // 0x55 'U'
{ 394, 12, 9, 12, 0, -8 }, // 0x56 'V'
{ 408, 14, 9, 14, 0, -8 }, // 0x57 'W'
{ 424, 8, 9, 10, 1, -8 }, // 0x58 'X'
{ 433, 9, 9, 10, 0, -8 }, // 0x59 'Y'
{ 444, 8, 9, 10, 1, -8 }, // 0x5A 'Z'
{ 453, 2, 9, 3, 1, -8 }, // 0x5B '['
{ 456, 6, 9, 6, 0, -8 }, // 0x5C '\'
{ 463, 2, 9, 3, 1, -8 }, // 0x5D ']'
{ 466, 1, 1, 0, 0, 0 }, // 0x5E '^'
{ 467, 8, 1, 10, 1, 1 }, // 0x5F '_'
{ 468, 2, 2, 3, 0, -11 }, // 0x60 '`'
{ 469, 7, 7, 9, 1, -6 }, // 0x61 'a'
{ 476, 7, 9, 9, 1, -8 }, // 0x62 'b'
{ 484, 7, 7, 8, 1, -6 }, // 0x63 'c'
{ 491, 7, 9, 8, 0, -8 }, // 0x64 'd'
{ 499, 7, 7, 9, 1, -6 }, // 0x65 'e'
{ 506, 4, 9, 5, 1, -8 }, // 0x66 'f'
{ 511, 8, 10, 9, 0, -6 }, // 0x67 'g'
{ 521, 7, 9, 9, 1, -8 }, // 0x68 'h'
{ 529, 1, 9, 3, 1, -8 }, // 0x69 'i'
{ 531, 4, 12, 3, -2, -8 }, // 0x6A 'j'
{ 537, 7, 9, 8, 1, -8 }, // 0x6B 'k'
{ 545, 3, 9, 4, 1, -8 }, // 0x6C 'l'
{ 549, 10, 7, 12, 1, -6 }, // 0x6D 'm'
{ 558, 7, 7, 9, 1, -6 }, // 0x6E 'n'
{ 565, 7, 7, 9, 1, -6 }, // 0x6F 'o'
{ 572, 7, 10, 9, 1, -6 }, // 0x70 'p'
{ 581, 7, 10, 8, 0, -6 }, // 0x71 'q'
{ 590, 5, 7, 6, 1, -6 }, // 0x72 'r'
{ 595, 7, 7, 9, 1, -6 }, // 0x73 's'
{ 602, 4, 9, 5, 1, -8 }, // 0x74 't'
{ 607, 7, 7, 9, 1, -6 }, // 0x75 'u'
{ 614, 9, 7, 9, 0, -6 }, // 0x76 'v'
{ 622, 13, 7, 13, 0, -6 }, // 0x77 'w'
{ 634, 7, 7, 8, 1, -6 }, // 0x78 'x'
{ 641, 7, 10, 9, 1, -6 }, // 0x79 'y'
{ 650, 7, 7, 8, 1, -6 }, // 0x7A 'z'
{ 657, 3, 9, 4, 0, -8 }, // 0x7B '{'
{ 661, 1, 11, 3, 1, -9 }, // 0x7C '|'
{ 663, 3, 9, 3, 1, -8 }, // 0x7D '}'
{ 667, 4, 1, 5, 0, -3 } }; // 0x7E '~'
const GFXfont Orbitron_Light6pt7b PROGMEM = {
(uint8_t *)Orbitron_Light6pt7bBitmaps,
(GFXglyph *)Orbitron_Light6pt7bGlyphs,
0x20, 0x7E, 12 };
// Approx. 1340 bytes
|
ingoha/TTGO-T-Wristband | include/fonts/Orbitron_Light_9.h | const uint8_t orbitron_light9pt7bBitmaps[] PROGMEM = {
0x00, 0xFF, 0x88, 0x99, 0x90, 0x0C, 0x10, 0x61, 0x82, 0x09, 0xFF, 0xF1,
0x06, 0x08, 0x20, 0xC1, 0x06, 0x18, 0x30, 0xC7, 0xFF, 0x98, 0x60, 0x83,
0x0C, 0x10, 0x00, 0x02, 0x00, 0x10, 0x1F, 0xFD, 0xFF, 0xF8, 0x21, 0xC1,
0x02, 0x08, 0x10, 0x40, 0x7F, 0xF0, 0x10, 0xC0, 0x86, 0x04, 0x38, 0x21,
0xC1, 0x0D, 0xFF, 0xC0, 0x40, 0x02, 0x00, 0x78, 0x02, 0x84, 0x06, 0x84,
0x0C, 0x84, 0x18, 0x84, 0x30, 0x78, 0xE0, 0x01, 0x80, 0x03, 0x1E, 0x06,
0x21, 0x1C, 0x21, 0x38, 0x21, 0x20, 0x21, 0x40, 0x1E, 0x3F, 0xE0, 0xFF,
0xE1, 0x00, 0x42, 0x00, 0x04, 0x00, 0x0C, 0x00, 0x3E, 0x00, 0x47, 0x84,
0x83, 0xC9, 0x03, 0xF2, 0x01, 0xF4, 0x00, 0xF7, 0xFF, 0x20, 0xE0, 0x7A,
0x49, 0x24, 0x92, 0x66, 0xDD, 0xB6, 0xDB, 0x6D, 0xFC, 0x10, 0x23, 0x7B,
0xE3, 0x8D, 0x91, 0x00, 0x10, 0x20, 0x47, 0xF1, 0x02, 0x04, 0x00, 0xE0,
0xFE, 0x80, 0x00, 0x80, 0x40, 0x60, 0x60, 0x20, 0x20, 0x20, 0x30, 0x30,
0x30, 0x10, 0x10, 0x08, 0x00, 0x7F, 0xF7, 0xFF, 0xE0, 0x0F, 0x00, 0xF8,
0x0E, 0xC1, 0xC6, 0x1C, 0x31, 0xC1, 0x9C, 0x0F, 0xC0, 0x78, 0x03, 0x80,
0x17, 0xFF, 0x00, 0x1C, 0xF6, 0xD3, 0x8C, 0x30, 0xC3, 0x0C, 0x30, 0xC3,
0x0C, 0x7F, 0xF7, 0xFF, 0xE0, 0x02, 0x00, 0x10, 0x00, 0x80, 0x05, 0xFF,
0xD0, 0x00, 0x80, 0x04, 0x00, 0x20, 0x01, 0x00, 0x0F, 0xFF, 0x80, 0x7F,
0xEF, 0xFF, 0xC0, 0x10, 0x01, 0x00, 0x10, 0x01, 0x3F, 0xF0, 0x01, 0x00,
0x10, 0x01, 0x00, 0x1C, 0x01, 0x7F, 0xE0, 0x00, 0xC0, 0x1C, 0x03, 0xC0,
0x74, 0x1C, 0x43, 0x84, 0x70, 0x4C, 0x04, 0xFF, 0xF0, 0x04, 0x00, 0x40,
0x04, 0x00, 0x40, 0xFF, 0xFF, 0xFF, 0xE0, 0x01, 0x00, 0x08, 0x00, 0x40,
0x03, 0xFF, 0xC0, 0x01, 0x00, 0x08, 0x00, 0x60, 0x03, 0x00, 0x17, 0xFF,
0x00, 0x7F, 0xC7, 0xFE, 0x20, 0x01, 0x00, 0x08, 0x00, 0x40, 0x03, 0xFF,
0xD0, 0x01, 0x80, 0x0C, 0x00, 0x60, 0x03, 0x00, 0x17, 0xFF, 0x00, 0xFF,
0xBF, 0xF0, 0x04, 0x01, 0x00, 0x40, 0x10, 0x04, 0x01, 0x00, 0x40, 0x10,
0x04, 0x01, 0x00, 0x40, 0x7F, 0xF7, 0xFF, 0xE0, 0x03, 0x00, 0x18, 0x00,
0xC0, 0x07, 0xFF, 0xF0, 0x01, 0x80, 0x0C, 0x00, 0x60, 0x03, 0x00, 0x17,
0xFF, 0x00, 0x7F, 0xF7, 0xFF, 0xF0, 0x03, 0x80, 0x1C, 0x00, 0xE0, 0x05,
0xFF, 0xE0, 0x01, 0x00, 0x08, 0x00, 0x40, 0x02, 0x00, 0x1F, 0xFF, 0x00,
0x80, 0x40, 0x80, 0xF0, 0x02, 0x0C, 0x73, 0x8C, 0x18, 0x1C, 0x0E, 0x06,
0x04, 0xFF, 0x80, 0x00, 0x00, 0x0F, 0xF8, 0x81, 0xC1, 0xC0, 0xE0, 0x60,
0xC7, 0x38, 0xE1, 0x00, 0xFF, 0xDF, 0xFC, 0x00, 0x80, 0x10, 0x02, 0x00,
0x47, 0xF1, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x7F, 0xF7,
0xFF, 0xE0, 0x03, 0x00, 0x18, 0x78, 0xC4, 0x26, 0x21, 0x31, 0x09, 0x87,
0xFC, 0x00, 0x20, 0x01, 0x00, 0x07, 0xFF, 0x80, 0x7F, 0xF4, 0x00, 0x60,
0x03, 0x00, 0x18, 0x00, 0xC0, 0x06, 0x00, 0x3F, 0xFF, 0x80, 0x0C, 0x00,
0x60, 0x03, 0x00, 0x18, 0x00, 0x80, 0xFF, 0xE8, 0x01, 0x80, 0x18, 0x01,
0x80, 0x18, 0x01, 0xFF, 0xF8, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01,
0xFF, 0xE0, 0x7F, 0xF8, 0x00, 0x80, 0x08, 0x00, 0x80, 0x08, 0x00, 0x80,
0x08, 0x00, 0x80, 0x08, 0x00, 0x80, 0x08, 0x00, 0x7F, 0xF0, 0xFF, 0xF4,
0x00, 0x60, 0x03, 0x00, 0x18, 0x00, 0xC0, 0x06, 0x00, 0x30, 0x01, 0x80,
0x0C, 0x00, 0x60, 0x03, 0x00, 0x1F, 0xFF, 0x00, 0xFF, 0xF0, 0x02, 0x00,
0x40, 0x08, 0x01, 0x00, 0x3F, 0xE4, 0x00, 0x80, 0x10, 0x02, 0x00, 0x40,
0x0F, 0xFE, 0xFF, 0xF0, 0x02, 0x00, 0x40, 0x08, 0x01, 0x00, 0x3F, 0xE4,
0x00, 0x80, 0x10, 0x02, 0x00, 0x40, 0x08, 0x00, 0x7F, 0xF4, 0x00, 0x60,
0x03, 0x00, 0x08, 0x00, 0x40, 0x02, 0x01, 0xF0, 0x01, 0x80, 0x0C, 0x00,
0x60, 0x03, 0x00, 0x17, 0xFF, 0x00, 0x80, 0x0C, 0x00, 0x60, 0x03, 0x00,
0x18, 0x00, 0xC0, 0x07, 0xFF, 0xF0, 0x01, 0x80, 0x0C, 0x00, 0x60, 0x03,
0x00, 0x18, 0x00, 0x80, 0xFF, 0xF8, 0x00, 0x08, 0x00, 0x40, 0x02, 0x00,
0x10, 0x00, 0x80, 0x04, 0x00, 0x20, 0x01, 0x00, 0x08, 0x00, 0x60, 0x03,
0x00, 0x17, 0xFF, 0x00, 0x80, 0x38, 0x06, 0x80, 0xC8, 0x18, 0x83, 0x08,
0x20, 0xFC, 0x08, 0x20, 0x83, 0x08, 0x18, 0x80, 0xC8, 0x06, 0x80, 0x30,
0x80, 0x04, 0x00, 0x20, 0x01, 0x00, 0x08, 0x00, 0x40, 0x02, 0x00, 0x10,
0x00, 0x80, 0x04, 0x00, 0x20, 0x01, 0x00, 0x0F, 0xFF, 0x80, 0xC0, 0x0F,
0x80, 0x7B, 0x03, 0x66, 0x19, 0x98, 0x66, 0x33, 0x18, 0x78, 0x60, 0xC1,
0x82, 0x06, 0x00, 0x18, 0x00, 0x60, 0x01, 0x80, 0x04, 0xE0, 0x0F, 0x00,
0x6C, 0x03, 0x30, 0x19, 0xC0, 0xC7, 0x06, 0x1C, 0x30, 0x71, 0x81, 0xCC,
0x06, 0x60, 0x1B, 0x00, 0x78, 0x03, 0x80, 0x7F, 0xE8, 0x01, 0x80, 0x18,
0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18,
0x01, 0x7F, 0xE0, 0xFF, 0xF4, 0x00, 0x60, 0x03, 0x00, 0x18, 0x00, 0xC0,
0x06, 0x00, 0x3F, 0xFE, 0x80, 0x04, 0x00, 0x20, 0x01, 0x00, 0x08, 0x00,
0x00, 0x7F, 0xE2, 0x00, 0x48, 0x01, 0x20, 0x04, 0x80, 0x12, 0x00, 0x48,
0x01, 0x20, 0x04, 0x80, 0x12, 0x00, 0x48, 0x01, 0x20, 0x04, 0x7F, 0xFC,
0xFF, 0xE8, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x1F, 0xFE,
0x81, 0x08, 0x18, 0x80, 0xC8, 0x06, 0x80, 0x30, 0x7F, 0xE8, 0x01, 0x80,
0x18, 0x00, 0x80, 0x08, 0x00, 0x7F, 0xE0, 0x01, 0x00, 0x10, 0x01, 0x80,
0x18, 0x01, 0x7F, 0xE0, 0xFF, 0xF8, 0x10, 0x00, 0x80, 0x04, 0x00, 0x20,
0x01, 0x00, 0x08, 0x00, 0x40, 0x02, 0x00, 0x10, 0x00, 0x80, 0x04, 0x00,
0x20, 0x00, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x80,
0x18, 0x01, 0x80, 0x18, 0x01, 0x80, 0x18, 0x01, 0x7F, 0xE0, 0xC0, 0x03,
0xC0, 0x02, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x10, 0x18, 0x18, 0x18,
0x0C, 0x30, 0x04, 0x20, 0x06, 0x60, 0x02, 0x40, 0x03, 0xC0, 0x01, 0x80,
0x80, 0x60, 0x3C, 0x0E, 0x02, 0x40, 0xA0, 0x64, 0x1B, 0x04, 0x61, 0x90,
0xC2, 0x11, 0x8C, 0x33, 0x18, 0x83, 0x30, 0x98, 0x12, 0x0D, 0x81, 0xE0,
0xD0, 0x1E, 0x07, 0x00, 0xC0, 0x60, 0x0C, 0x06, 0x00, 0xC0, 0x3B, 0x03,
0x0C, 0x18, 0x31, 0x80, 0xD8, 0x07, 0x80, 0x18, 0x01, 0xE0, 0x0D, 0x80,
0xC6, 0x0C, 0x18, 0xC0, 0xCC, 0x03, 0x80, 0xC0, 0x1B, 0x01, 0x8C, 0x18,
0x21, 0x81, 0x8C, 0x06, 0xC0, 0x1C, 0x00, 0x40, 0x02, 0x00, 0x10, 0x00,
0x80, 0x04, 0x00, 0x20, 0x00, 0xFF, 0xF8, 0x00, 0xC0, 0x0C, 0x01, 0xC0,
0x1C, 0x01, 0xC0, 0x1C, 0x01, 0xC0, 0x1C, 0x01, 0x80, 0x38, 0x01, 0x80,
0x0F, 0xFF, 0x80, 0xFE, 0x49, 0x24, 0x92, 0x4E, 0x80, 0x40, 0x10, 0x0C,
0x03, 0x00, 0xC0, 0x20, 0x08, 0x02, 0x01, 0x80, 0x60, 0x10, 0x08, 0xFD,
0xB6, 0xDB, 0x6D, 0xBE, 0x00, 0xFF, 0xF8, 0xAC, 0xFF, 0xC0, 0x0C, 0x01,
0x80, 0x3F, 0xFF, 0x00, 0xE0, 0x1C, 0x03, 0x80, 0x6F, 0xFC, 0x80, 0x20,
0x08, 0x02, 0x00, 0xFF, 0xA0, 0x18, 0x06, 0x01, 0x80, 0x60, 0x18, 0x06,
0x01, 0x80, 0x7F, 0xE0, 0x7F, 0xE0, 0x08, 0x02, 0x00, 0x80, 0x20, 0x08,
0x02, 0x00, 0x80, 0x1F, 0xF0, 0x00, 0x20, 0x04, 0x00, 0x80, 0x17, 0xFF,
0x80, 0x70, 0x0E, 0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0, 0x1C, 0x02, 0xFF,
0xC0, 0x7F, 0xD0, 0x0E, 0x01, 0xC0, 0x3F, 0xFF, 0x00, 0x20, 0x04, 0x00,
0x80, 0x0F, 0xFC, 0x7E, 0x08, 0x20, 0xFE, 0x08, 0x20, 0x82, 0x08, 0x20,
0x82, 0x00, 0x7F, 0xA0, 0x18, 0x06, 0x01, 0x80, 0x60, 0x18, 0x06, 0x01,
0x80, 0x5F, 0xF0, 0x04, 0x01, 0x3F, 0xCF, 0xE0, 0x80, 0x20, 0x08, 0x02,
0x00, 0xFF, 0xA0, 0x18, 0x06, 0x01, 0x80, 0x60, 0x18, 0x06, 0x01, 0x80,
0x60, 0x10, 0x8F, 0xFC, 0x04, 0x00, 0x00, 0x04, 0x10, 0x41, 0x04, 0x10,
0x41, 0x04, 0x10, 0x41, 0x07, 0xFF, 0x80, 0x80, 0x20, 0x08, 0x02, 0x03,
0x81, 0xA0, 0xC8, 0x62, 0x30, 0xF8, 0x23, 0x08, 0x62, 0x0C, 0x81, 0xA0,
0x30, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0xFF, 0xFE, 0xC1, 0x81,
0xC1, 0x81, 0xC1, 0x81, 0xC1, 0x81, 0xC1, 0x81, 0xC1, 0x81, 0xC1, 0x81,
0xC1, 0x81, 0xC1, 0x81, 0xFF, 0xA0, 0x18, 0x06, 0x01, 0x80, 0x60, 0x18,
0x06, 0x01, 0x80, 0x60, 0x10, 0x7F, 0xD0, 0x0E, 0x01, 0xC0, 0x38, 0x07,
0x00, 0xE0, 0x1C, 0x03, 0x80, 0x6F, 0xF8, 0xFF, 0xA0, 0x18, 0x06, 0x01,
0x80, 0x60, 0x18, 0x06, 0x01, 0x80, 0x7F, 0xE8, 0x02, 0x00, 0x80, 0x20,
0x00, 0x7F, 0xF8, 0x07, 0x00, 0xE0, 0x1C, 0x03, 0x80, 0x70, 0x0E, 0x01,
0xC0, 0x2F, 0xFC, 0x00, 0x80, 0x10, 0x02, 0x00, 0x40, 0x7F, 0x80, 0x80,
0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7F, 0xD0, 0x0E, 0x00, 0x40,
0x07, 0xFC, 0x00, 0xC0, 0x18, 0x03, 0x80, 0x6F, 0xF8, 0x82, 0x08, 0x20,
0xFE, 0x08, 0x20, 0x82, 0x08, 0x20, 0x81, 0xF0, 0x80, 0x60, 0x18, 0x06,
0x01, 0x80, 0x60, 0x18, 0x06, 0x01, 0x80, 0x5F, 0xE0, 0xC0, 0x0D, 0x80,
0x63, 0x03, 0x0C, 0x0C, 0x18, 0x60, 0x21, 0x00, 0xCC, 0x01, 0x20, 0x07,
0x80, 0x0C, 0x00, 0x80, 0xC0, 0xF0, 0x70, 0x24, 0x16, 0x19, 0x8C, 0x84,
0x62, 0x33, 0x0D, 0x8C, 0xC3, 0x61, 0xA0, 0x70, 0x78, 0x1C, 0x0C, 0x02,
0x03, 0x00, 0xC0, 0xCC, 0x30, 0xCC, 0x0D, 0x00, 0xC0, 0x1C, 0x06, 0x81,
0x88, 0x61, 0x98, 0x1C, 0x80, 0x60, 0x18, 0x06, 0x01, 0x80, 0x60, 0x18,
0x06, 0x01, 0x80, 0x5F, 0xF0, 0x04, 0x01, 0x3F, 0xCF, 0xE0, 0xFF, 0xE0,
0x1C, 0x07, 0x01, 0xC0, 0xE0, 0x38, 0x0E, 0x03, 0x80, 0xC0, 0x1F, 0xFC,
0x36, 0x44, 0x4C, 0x8C, 0x44, 0x46, 0x30, 0xFF, 0xFF, 0x80, 0xCE, 0x22,
0x23, 0x13, 0x22, 0x26, 0xC0, 0xE0, 0x3C };
const GFXglyph orbitron_light9pt7bGlyphs[] PROGMEM = {
{ 0, 1, 1, 5, 0, 0 }, // 0x20 ' '
{ 1, 1, 13, 4, 1, -12 }, // 0x21 '!'
{ 3, 4, 3, 6, 1, -12 }, // 0x22 '"'
{ 5, 13, 13, 14, 1, -12 }, // 0x23 '#'
{ 27, 13, 17, 14, 1, -14 }, // 0x24 '$'
{ 55, 16, 13, 18, 1, -12 }, // 0x25 '%'
{ 81, 15, 13, 17, 1, -12 }, // 0x26 '&'
{ 106, 1, 3, 4, 1, -12 }, // 0x27 '''
{ 107, 3, 13, 5, 1, -12 }, // 0x28 '('
{ 112, 3, 13, 5, 1, -12 }, // 0x29 ')'
{ 117, 7, 7, 9, 1, -12 }, // 0x2A '*'
{ 124, 7, 7, 8, 0, -8 }, // 0x2B '+'
{ 131, 1, 3, 3, 1, 0 }, // 0x2C ','
{ 132, 7, 1, 9, 1, -5 }, // 0x2D '-'
{ 133, 1, 1, 4, 1, 0 }, // 0x2E '.'
{ 134, 9, 13, 9, 0, -12 }, // 0x2F '/'
{ 149, 13, 13, 15, 1, -12 }, // 0x30 '0'
{ 171, 6, 13, 8, 0, -12 }, // 0x31 '1'
{ 181, 13, 13, 15, 1, -12 }, // 0x32 '2'
{ 203, 12, 13, 14, 1, -12 }, // 0x33 '3'
{ 223, 12, 13, 13, 0, -12 }, // 0x34 '4'
{ 243, 13, 13, 15, 1, -12 }, // 0x35 '5'
{ 265, 13, 13, 15, 1, -12 }, // 0x36 '6'
{ 287, 10, 13, 12, 1, -12 }, // 0x37 '7'
{ 304, 13, 13, 15, 1, -12 }, // 0x38 '8'
{ 326, 13, 13, 15, 1, -12 }, // 0x39 '9'
{ 348, 1, 10, 4, 1, -9 }, // 0x3A ':'
{ 350, 1, 12, 3, 1, -9 }, // 0x3B ';'
{ 352, 7, 10, 9, 0, -9 }, // 0x3C '<'
{ 361, 9, 5, 11, 1, -7 }, // 0x3D '='
{ 367, 7, 10, 9, 1, -9 }, // 0x3E '>'
{ 376, 11, 13, 13, 1, -12 }, // 0x3F '?'
{ 394, 13, 13, 15, 1, -12 }, // 0x40 '@'
{ 416, 13, 13, 15, 1, -12 }, // 0x41 'A'
{ 438, 12, 13, 14, 1, -12 }, // 0x42 'B'
{ 458, 12, 13, 15, 1, -12 }, // 0x43 'C'
{ 478, 13, 13, 15, 1, -12 }, // 0x44 'D'
{ 500, 11, 13, 14, 1, -12 }, // 0x45 'E'
{ 518, 11, 13, 13, 1, -12 }, // 0x46 'F'
{ 536, 13, 13, 15, 1, -12 }, // 0x47 'G'
{ 558, 13, 13, 15, 1, -12 }, // 0x48 'H'
{ 580, 1, 13, 4, 1, -12 }, // 0x49 'I'
{ 582, 13, 13, 14, 0, -12 }, // 0x4A 'J'
{ 604, 12, 13, 14, 1, -12 }, // 0x4B 'K'
{ 624, 13, 13, 14, 1, -12 }, // 0x4C 'L'
{ 646, 14, 13, 16, 1, -12 }, // 0x4D 'M'
{ 669, 13, 13, 15, 1, -12 }, // 0x4E 'N'
{ 691, 12, 13, 14, 1, -12 }, // 0x4F 'O'
{ 711, 13, 13, 15, 1, -12 }, // 0x50 'P'
{ 733, 14, 13, 15, 1, -12 }, // 0x51 'Q'
{ 756, 12, 13, 14, 1, -12 }, // 0x52 'R'
{ 776, 12, 13, 14, 1, -12 }, // 0x53 'S'
{ 796, 13, 13, 14, 0, -12 }, // 0x54 'T'
{ 818, 12, 13, 14, 1, -12 }, // 0x55 'U'
{ 838, 16, 13, 18, 1, -12 }, // 0x56 'V'
{ 864, 20, 13, 21, 1, -12 }, // 0x57 'W'
{ 897, 13, 13, 15, 1, -12 }, // 0x58 'X'
{ 919, 13, 13, 15, 0, -12 }, // 0x59 'Y'
{ 941, 13, 13, 15, 1, -12 }, // 0x5A 'Z'
{ 963, 3, 13, 5, 1, -12 }, // 0x5B '['
{ 968, 9, 13, 9, 0, -12 }, // 0x5C '\'
{ 983, 3, 13, 5, 1, -12 }, // 0x5D ']'
{ 988, 1, 1, 0, 0, 0 }, // 0x5E '^'
{ 989, 13, 1, 15, 1, 1 }, // 0x5F '_'
{ 991, 2, 3, 4, 1, -17 }, // 0x60 '`'
{ 992, 11, 10, 13, 1, -9 }, // 0x61 'a'
{ 1006, 10, 14, 12, 1, -13 }, // 0x62 'b'
{ 1024, 10, 10, 13, 1, -9 }, // 0x63 'c'
{ 1037, 11, 14, 12, 0, -13 }, // 0x64 'd'
{ 1057, 11, 10, 13, 1, -9 }, // 0x65 'e'
{ 1071, 6, 14, 7, 1, -13 }, // 0x66 'f'
{ 1082, 10, 14, 12, 1, -9 }, // 0x67 'g'
{ 1100, 10, 14, 12, 1, -13 }, // 0x68 'h'
{ 1118, 1, 14, 4, 1, -13 }, // 0x69 'i'
{ 1120, 6, 19, 4, -3, -13 }, // 0x6A 'j'
{ 1135, 10, 14, 12, 1, -13 }, // 0x6B 'k'
{ 1153, 4, 14, 5, 1, -13 }, // 0x6C 'l'
{ 1160, 16, 10, 18, 1, -9 }, // 0x6D 'm'
{ 1180, 10, 10, 12, 1, -9 }, // 0x6E 'n'
{ 1193, 11, 10, 13, 1, -9 }, // 0x6F 'o'
{ 1207, 10, 14, 12, 1, -9 }, // 0x70 'p'
{ 1225, 11, 14, 12, 0, -9 }, // 0x71 'q'
{ 1245, 8, 10, 9, 1, -9 }, // 0x72 'r'
{ 1255, 11, 10, 13, 1, -9 }, // 0x73 's'
{ 1269, 6, 14, 7, 1, -13 }, // 0x74 't'
{ 1280, 10, 10, 12, 1, -9 }, // 0x75 'u'
{ 1293, 14, 10, 14, 0, -9 }, // 0x76 'v'
{ 1311, 18, 10, 19, 1, -9 }, // 0x77 'w'
{ 1334, 11, 10, 12, 1, -9 }, // 0x78 'x'
{ 1348, 10, 14, 12, 1, -9 }, // 0x79 'y'
{ 1366, 11, 10, 13, 1, -9 }, // 0x7A 'z'
{ 1380, 4, 13, 5, 0, -12 }, // 0x7B '{'
{ 1387, 1, 17, 4, 1, -14 }, // 0x7C '|'
{ 1390, 4, 13, 5, 1, -12 }, // 0x7D '}'
{ 1397, 7, 2, 7, 0, -5 } }; // 0x7E '~'
const GFXfont orbitron_light9pt7b PROGMEM = {
(uint8_t *)orbitron_light9pt7bBitmaps,
(GFXglyph *)orbitron_light9pt7bGlyphs,
0x20, 0x7E, 18 };
// Approx. 2071 bytes
|
GauravWalia19/minfile | src/util.c | <filename>src/util.c<gh_stars>1-10
#include "util.h"
/*HASHTABLE WORK*/
/**
* This is my hash function
*
* @param string for hash
*
* @return hash value
**/
int hashfunction(char* str)
{
int sum=0;
register int i=0;
while(str[i]!='\0')
{
sum=sum + (int)str[i] - 65;
i++;
}
return sum;
}
/**
* this function will print the hashtable
* just for testing
*
* @return void
**/
void printHashTable()
{
if(HASH==NULL)
{
printf("NULL\n");
return;
}
register int i=0;
for(i=0;i<HASHSIZE;i++)
{
if(HASH[i]!=NULL)
{
printf("%d\t%s\n",i,HASH[i]);
}
}
}
/**
* This function will free the memory taken by the hashtable
*
* @return void
**/
void freeHashTable()
{
register int i=0;
if(HASH!=NULL)
{
for(i=0;i<HASHSIZE;i++)
{
free(HASH[i]);
}
}
free(HASH);
} |
GauravWalia19/minfile | src/Main.c | #include "Main.h"
#include "util.c"
#include "function.c"
#include "minfile.c"
/**
* this is the main program
*
* @return int
**/
int main(int argc,char* argv[])
{
// buildHTML();
// printf("%d\n",reservedHTML("<head"));
// printHashTable();
// freeHashTable();
// exit(0);
if(argc==1) // check argument count
{
printf("Invalid arguments !!!\n");
printf("Format should be: ./minfile filename\n");
/*GLOBAL VARIABLES FOR PARSING*/
char clistring[100]; // for taking input string
bool parseflag=false; // flag for parsing the string
register int i=0,j=0,k=0; // register values for looping
char copy[30]; // string needed for parsing
argc=0;
argv=NULL;
printf("minfile: ");
scanf("%[^\t\n]s",clistring); // input the string with spaces
while(clistring[i]!='\0') // traversing and counting the arguments
{
if(clistring[i]==' ' || clistring[i]=='\n')
{
if(parseflag)
{
parseflag=false;
argc++;
}
}
else
{
if(!parseflag)
{
parseflag=true;
}
}
i++;
}
argc++;
// printf("arguments: %d\n",argc);
argv = (char**)malloc(sizeof(char *)*argc); // storing the arguments
/**
* RESETTING VARAIBLES
**/
i=0;
j=0;
k=0;
parseflag=false;
while(i<(strlen(clistring)+1)) // string parsing anf storing
{
if(clistring[i]==' ' || clistring[i]=='\n' || clistring[i]=='\0') // if character found while parsing
{
if(parseflag) // if flag is true change to false as string gets end
{
parseflag=false;
copy[j]='\0';
int len = strlen(copy);
//allocating memory
argv[k] = (char*)malloc(sizeof(char)*(len+1));
strcpy(argv[k],copy);
k++;
j=0;
}
}
else // if other char found
{
if(!parseflag) // if flag gets false then change to true
{
parseflag=true;
}
copy[j] = clistring[i]; // storing the characters
j++;
}
i++;
}
// free(argv);
}
printf("ARGUMENT CHECK: %d\n",argc);
int i=0;
for(i=0;i<argc;i++)
{
printf("%s\n",argv[i]);
}
if(argc==1)
{
printf("awesome");
}
else if(argc==2)
{
minfile(argv[1]);
}
}
|
GauravWalia19/minfile | test/C/test.c | #include <stdio.h>
#define CONST 10
#include <string.h>
int main()
{
char str[50]="This is test";
printf("Hello World");
} |
GauravWalia19/minfile | src/minfile.h | <gh_stars>1-10
#include "Main.h"
void minfile(char*); |
GauravWalia19/minfile | src/function.h | #include "Main.h"
/*OTHER FUNCTIONS*/
bool wildcard(char);
bool checkValid(char*);
/*RESERVED FUNCTIONS*/
bool reservedHTML(char*);
bool reservedJS(char*);
bool reservedC(char*);
bool reservedCPP(char*);
bool reservedJAVA(char*);
bool reservedCSharp(char*);
/*BUILD TREE FUNCTIONS*/
void buildHTML();
void buildJS();
void buildC();
void buildCPP();
void buildJAVA();
void buildCSharp(); |
GauravWalia19/minfile | src/Main.h | /**
* This header file contains the
* main headers needed
**/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h> |
GauravWalia19/minfile | src/function.c | #include "function.h"
/**
* this function will tell whether given char is wildcard or not
* for discarding char in filename
*
* @param ch for char
*
* @return bool
**/
bool wildcard(char ch)
{
switch(ch)
{
case '!':
case '\"':
case '#':
case '$':
case '%':
case '&':
case '(':
case ')':
case '*':
case '+':
case '\'':
case ',':
case '-':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '@':
case '[':
case '\\':
case ']':
case '^':
case '_':
case '`':
case '{':
case '|':
case '}':
case '~':
return true;
default:
return false;
}
}
/**
* it will check whether the string is valid or not
* i.e it contains single . or not
*
* @param string
*
* @return bool
**/
bool checkValid(char *str)
{
int count=0; // counting the number of dots in the filename
int i=0;
/**
* traversing the string and counting . chars
**/
while(str[i]!='\0')
{
if(wildcard(str[i]))
{
return false;
}
if(str[i]=='.')
{
count++;
}
i++;
}
if(count==1) // valid for only one dot in string
{
return true;
}
return false;
}
/**
* This function conveys that the string is a html keyword or not
*
* @param search string
*
* @return bool
**/
bool reservedHTML(char *str)
{
int key = hashfunction(str); // finding the key of string
/**
* collison: 146 <code
* collison: 109 <del
* collison: 282 <details
* collison: 165 <link
* collison: 156 <main
* collison: 118 <map
* collison: 130 <sub
* collison: 144 <sup
* collison: 81 <td
* collison: 188 <thead
* collison: 166 <time
* collison: 216 <title
* collison: 95 <tr
* collison: 131 <wbr
**/
char ch = str[1];
switch (ch)
{
case 'c':
if(strcmp(str,"<code")==0)
{
key++;
}
break;
case 'd':
if(strcmp(str,"<del")==0 || strcmp(str,"<details")==0)
{
key++;
}
break;
case 'l':
if(strcmp(str,"<link")==0)
{
key++;
}
break;
case 'm':
if(strcmp(str,"<main")==0 || strcmp(str,"<map")==0)
{
key++;
}
break;
case 's':
if(strcmp(str,"<sub")==0 || strcmp(str,"<sup")==0)
{
key++;
}
break;
case 't':
{
ch = str[2];
switch (ch)
{
case 'h':
if(strcmp(str,"<thead")==0)
{
key++;
}
break;
case 'i':
if(strcmp(str,"<time")==0 || strcmp(str,"<title")==0)
{
key++;
}
break;
case 'r':
if(strcmp(str,"<tr")==0)
{
key++;
}
break;
default:
break;
}
}
break;
case 'w':
if(strcmp(str,"<wbr")==0)
{
key++;
}
break;
default:
break;
}
if(key<0 || key>HASHSIZE) // if key not valid
{
return false;
}
else if(HASH[key]!=NULL && strcmp(str,HASH[key])==0) // key found but checking the string for total surety
{
return true;
}
else
{
return false;
}
}
/**
* This function will search a string in the collection of JavaScript reserved words
*
* @param search string
*
* @return bool
**/
bool reservedJS(char* str)
{
int key = hashfunction(str); // finding the key of string
/**
* COLLISION SOLUTION
* Added initial shift value
*
* float -- 210
**/
if(strcmp(str,"float")==0)
{
key++;
}
if(key<0 || key>HASHSIZE) // if key is not valid
{
return false;
}
else if(HASH[key]!=NULL && strcmp(str,HASH[key])==0) // if key found
{
return true;
}
else
{
return false;
}
}
/**
* it will search a string in the collection of reserved words in C language
*
* @param search string
*
* @return bool
**/
bool reservedC(char* str)
{
int key = hashfunction(str); // finding the key of string
/**
* COLLISION SOLUTION
* Adding initial shift value to key
*
* 349 -- continue
* 181 -- goto
**/
if(strcmp(str,"continue")==0 || strcmp(str,"goto")==0)
{
key++;
}
if(key<0 || key>HASHSIZE) // if key is not valid
{
return false;
}
else if(HASH[key]!=NULL && strcmp(str,HASH[key])==0) // if key founded
{
return true;
}
else
{
return false;
}
}
/**
* it will search a string in the collection of reserved words in C++ language
*
* @param search string
*
* @return bool
**/
bool reservedCPP(char* str)
{
int key = hashfunction(str);
/**
* COLLISION SOLUTION
* Added initial shift value to key
*
* 349-continue
* 209-class
* 181-goto
* 356-operator
* 249-public
**/
char ch = str[0];
switch (ch) // faster mechanism for comparing strings
{
case 'c':
{
ch = str[1];
switch (ch)
{
case 'o':
if(strcmp(str,"continue")==0)
{
key++;
}
break;
case 'l':
if(strcmp(str,"class")==0)
{
key++;
}
break;
default:
break;
}
}
break;
case 'g':
if(strcmp(str,"goto")==0)
{
key++;
}
break;
case 'o':
if(strcmp(str,"operator")==0)
{
key++;
}
break;
case 'p':
if(strcmp(str,"public")==0)
{
key++;
}
break;
default:
break;
}
if(key<0 || key>HASHSIZE) // if the key is not valid
{
return false;
}
else if(HASH[key]!=NULL && strcmp(str,HASH[key])==0) // if key found
{
return true;
}
else
{
return false;
}
}
/**
* it will search a string in the collection of reserved words in JAVA language
*
* @param search string
*
* @return bool
**/
bool reservedJAVA(char* str)
{
int key = hashfunction(str);
/**
* collision solution
* 209-float
* 308-private
* 268-switch
**/
if(strcmp(str,"float")==0 || strcmp(str,"private")==0 || strcmp(str,"switch")==0)
{
key++;
}
if(key<0 || key>HASHSIZE) // if key is not valid
{
return false;
}
else if(HASH[key]!=NULL && strcmp(str,HASH[key])==0) // if key found
{
return true;
}
else
{
return false;
}
}
/**
* it will search a string in the collection of reserved words in C# language
*
* @param search string
*
* @return bool
**/
bool reservedCSharp(char* str)
{
int key = hashfunction(str);
/**
* COLLISIONS FOUND
* 209 -- float
* 165 -- lock
* 356 -- operator
* 226 -- sbyte
* 273 -- string
* 273 -- typeof
* 188 -- unit
* 287 -- ushort
* 344 -- volatile
**/
char ch = str[0];
switch (ch)
{
case 'f':
if(strcmp(str,"float")==0)
{
key++;
}
break;
case 'l':
if(strcmp(str,"lock")==0)
{
key++;
}
break;
case 'o':
if(strcmp(str,"operator")==0)
{
key++;
}
break;
case 's':
{
ch = str[1];
switch (ch)
{
case 'b':
if(strcmp(str,"sbyte")==0)
{
key++;
}
break;
case 't':
if(strcmp(str,"string")==0)
{
key++;
}
break;
default:
break;
}
}
break;
case 't':
if(strcmp(str,"typeof")==0)
{
key=key+2;
}
break;
case 'u':
{
ch = str[1];
switch (ch)
{
case 'n':
if(strcmp(str,"unit")==0)
{
key++;
}
break;
case 's':
if(strcmp(str,"ushort")==0)
{
key++;
}
break;
default:
break;
}
}
break;
case 'v':
if(strcmp(str,"volatile")==0)
{
key++;
}
break;
default:
break;
}
if(key<0 || key>HASHSIZE) // if key is not valid
{
return false;
}
else if(HASH[key]!=NULL && strcmp(str,HASH[key])==0) // is key found
{
return true;
}
else
{
return false;
}
}
/**
* It will build keyword tree of html keywords
*
* @return void
**/
void buildHTML()
{
int key = INT_MIN;
HASH = (char**)malloc(sizeof(char*)*HASHSIZE); // making hashtable of the size
char* HTML[] ={"<!DOCTYPE","<a","<abbr","<address","<area","<article","<aside","<audio","<b","<base",
"<bdi","<bdo","<blockquote","<body","<br/","<br","<button","<canvas","<caption","<cite","<code","<col",
"<colgroup","<data","<datalist","<dd","<del","<details","<dfn","<dialog","<div","<dl","<dt","<em","<embed",
"<fieldset","<figcaption","<figure","<footer","<form","<frame","<frameset","<h1","<h2","<h3","<h4","<h5",
"<h6","<head","<header","<hr","<html","<i","<iframe","<img","<input","<ins","<kbd","<label","<legend",
"<li","<link","<main","<map","<amrk","<meta","<meter","<nav","<noscript","<object","<ol","<optgroup",
"<option","<output","<p","<param","<picture","<pre","<progress","<q","<rp","<rt","<ruby","<s","<samp",
"<script","<section","<select","<small","<source","<span","<strong","<style","<sub","<summary","<sup",
"<svg","<table","<tbody","<td","<template","<textarea","<tfoot","<th","<thead","<time","<title","<tr",
"<track","<tt","<u","<ul","<var","<video","<wbr"};
register int i;
for(i=0;i<115;i++)
{
key = hashfunction(HTML[i]);
if(key >= 0 && key<HASHSIZE && HASH[key]==NULL)
{
int s = strlen(HTML[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],HTML[i]);
}
else
{
// printf("collison: %d %s\n",key,HTML[i]);
// printf("BUG FOUND IN BuildHTML!!!");
// exit(1);
key++;
int s = strlen(HTML[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],HTML[i]);
}
}
}
/**
* It will build keyword tree of Javscript keywords
*
* @return void
**/
void buildJS()
{
int key = INT_MIN;
HASH = (char**)malloc(sizeof(char*)*HASHSIZE); // making hashtable of the size
//better efficiency is needed here
//may be binary search tree for string searching
//js reserved words
char* JS[] = {"new","abstract","else","instanceof","super","boolean","enum","int","switch","break","export","interface","synchronised","byte","extends","let"
,"this","case","false","long","throw","catch","final","native","throws","char","finally","transient","class","float","null","true"
,"const","for","package","try","continue","function","private","typeof","debugger","goto","protected","var","default","if","public","void","delete"
,"implements","return","volatile","do","import","short","while","double","in","static","with"};
register int i;
for(i=0;i<60;i++)
{
key = hashfunction(JS[i]);
if(key >= 0 && key<HASHSIZE && HASH[key]==NULL)
{
int s = strlen(JS[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],JS[i]);
}
else // collision on 210 float
{
key++;
int s = strlen(JS[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],JS[i]);
}
}
}
/**
* It will build keyword tree of C keywords
*
* @return void
**/
void buildC()
{
int key = INT_MIN;
HASH = (char**)malloc(sizeof(char*)*HASHSIZE); // making hashtable of the size
char* C[] = {"auto","else","long","switch","break","enum","register","typedef","case",
"extern","return","union","char","float","short","unsigned","const","for","signed"
,"void","continue","goto","sizeof","volatile","default","if","static","while","do",
"int","struct","double","bool","true","false"};
register int i;
for(i=0;i<35;i++)
{
key = hashfunction(C[i]);
if(key >= 0 && key<HASHSIZE && HASH[key]==NULL)
{
int s = strlen(C[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],C[i]);
}
else // collision on 349 continue 181 - goto
{
// printf("collision %d %s\n",key,C[i]);
key++;
int s = strlen(C[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],C[i]);
}
}
}
/**
* It will build keyword tree of C++ keywords
*
* @return void
**/
void buildCPP()
{
int key = INT_MIN;
HASH = (char**)malloc(sizeof(char*)*HASHSIZE); // making hashtable of the size
char* CPP[]={"auto","double","int","struct","break","else","long","switch","case","enum","register",
"typedef","char","extern","return","union","const","float","short","unsigned","continue",
"for","signed","void","default","goto","sizeof","volatile","do","if","static","while","asm","bool"
,"catch","class","const_cast","delete","dynamic_cast","explicit","export","false","friend",
"inline","mutable","namespace","new","operator","private","protected","public","reinterpret_cast",
"static_cast","template","this","throw","true","try","typeid","typename","using","virtual","wchar_t"};
register int i;
for(i=0;i<63;i++)
{
key = hashfunction(CPP[i]);
if(key >= 0 && key<HASHSIZE && HASH[key]==NULL)
{
int s = strlen(CPP[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],CPP[i]);
}
else // collisions 349-continue 181-goto 209-class 356-operator 249-public
{
// printf("collision %d %s\n",key,CPP[i]);
// exit(1);
key++;
int s = strlen(CPP[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],CPP[i]);
}
}
}
/**
* It will build keyword tree of JAVA keywords
*
* @return void
**/
void buildJAVA()
{
int key = INT_MIN;
HASH = (char**)malloc(sizeof(char*)*HASHSIZE); // making hashtable of the size
char* JAVA[]={"abstract","assert","boolean","break","byte","case","catch","char",
"class","continue","default","do","double","else","enum","extends","final","finally",
"float","for","if","implements","import","istanceof","int","interface","long","native",
"new","null","package","private","protected","public","return","short","static","strictfp",
"super","switch","synchronized","this","throw","throws","transient","try","void","volatile",
"while"};
register int i=0;
for(i=0;i<49;i++)
{
key = hashfunction(JAVA[i]);
if(key >= 0 && key<HASHSIZE && HASH[key]==NULL)
{
int s = strlen(JAVA[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],JAVA[i]);
}
else // collisions 209-float 308-private 268-switch
{
// printf("collision %d %s\n",key,JAVA[i]);
// exit(1);
key++;
int s = strlen(JAVA[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],JAVA[i]);
}
}
}
/**
* It will build keyword tree of CSharp keywords
*
* @return void
**/
void buildCSharp()
{
int key = INT_MIN;
HASH = (char**)malloc(sizeof(char*)*HASHSIZE); // making hashtable of the size
char* CSHARP[] ={"abstract","as","base","bool","break","byte","case","catch","char"
,"checked","class","const","continue","decimal","default","delegate","do","double"
,"else","enum","event","explicit","extern","false","finally","fixed","float","for"
,"foreach","goto","if","implicit","in","int","interface","internal","is","lock"
,"long","namespace","new","null","object","operator","out","override","params","private"
,"protected","public","readonly","ref","return","sbyte","sealed","short","sizeof"
,"stackalloc","static","string","struct","switch","this","throw","true","try","typeof"
,"unit","ulong","unchecked","unsafe","ushort","using","using static","virtual","void","volatile"
,"while"};
register int i;
for(i=0;i<78;i++)
{
key = hashfunction(CSHARP[i]);
if(key >= 0 && key<HASHSIZE && HASH[key]==NULL)
{
int s = strlen(CSHARP[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],CSHARP[i]);
}
else
{
/**
* COLLISIONS FOUND
* 209 -- float
* 165 -- lock
* 356 -- operator
* 226 -- sbyte
* 273 -- string
* 273 -- typeof
* 188 -- unit
* 287 -- ushort
* 344 -- volatile
**/
// printf("collision %d %s\n",key,CSHARP[i]);
// exit(1);
if(strcmp(CSHARP[i],"typeof")==0)
{
key=key+2;
}
else
{
key++;
}
int s = strlen(CSHARP[i]);
HASH[key] = (char*)malloc(sizeof(char)*(s+1));
strcpy(HASH[key],CSHARP[i]);
}
}
} |
GauravWalia19/minfile | src/minfile.c | <filename>src/minfile.c
#include "minfile.h"
/**
* this function is the main function of the application
* it will single file into minfile
*
* @param string for filename
*
* @return void
**/
void minfile(char* argv)
{
printf("Valid filename: %d\n",checkValid(argv)); // check for valid file
if(checkValid(argv)) // if valid filename found
{
//booleans for file extensions
bool css = false; //* initial
bool scss = false; //* values
bool json = false; //* for
bool html = false; //* all
bool js = false; //* langauge
bool c = false; //* are
bool cpp = false; //* taken
bool java = false; //* false
bool csharp = false; //*
bool other = false; //* for other files
/**
* setting the boolean according to file extensions
**/
int len = strlen(argv);
char ch=argv[len-1]; // last char of file extension
/**
* making hashtable according to language extension found
**/
switch(ch)
{
case 'c': // chances: c
c=true; // file found: c
buildC(); // C HASHTABLE MADE
break;
case 'p': // chances: cpp
if(argv[len-2]=='p' && argv[len-3]=='c')
{
cpp = true; // file found: cpp
buildCPP(); // CPP HASHTABLE MADE
}
break;
case 's': // chances: cs css js scss
ch = argv[len-2]; // second last char of file extension
switch(ch)
{
case 'c': // chances: cs
csharp=true; // file found: c#
buildCSharp(); // CSHARP HASHTABLE MADE
break;
case 's': // chances: css scss
ch = argv[len-3]; // last third char of file extension
switch(ch)
{
case 'c': // chances: css scss
ch = argv[len-4];
switch(ch)
{
case '.': // chances: css
css=true; // file found: css
break;
case 's': // chances: scss
scss=true; // file found: scss
break;
default:
break;
} // end of switch arg 4
break;
default:
break;
} // end of switch arg 3
break;
case 'j': // chances js
js = true; // js file found
buildJS(); // JS HASHTABLE MADE
break;
default:
break;
} // end of switch arg 2
break;
case 'l': // chances: html
if(argv[len-2]=='m' && argv[len-3]=='t' && argv[len-4]=='h')
{
html = true; // file found: html
buildHTML(); // HTML HASHTABLE MADE
}
break;
case 'a': // chances: java
if(argv[len-2]=='v' && argv[len-3]=='a' && argv[len-4]=='j')
{
java=true; // file found: java
buildJAVA(); // JAVA HASHTABLE BUILD
}
break;
case 'n': // chances: json
if(argv[len-2]=='o' && argv[len-3]=='s' && argv[len-4]=='j')
json=true; // file found: json
break;
default:
break;
} // end of switch arg 1
/**
* printing hashtable for checking
**/
// printHashTable();
// exit(1);
/**
* CHECKING THE FILE NAME IS VALID OR NOT
**/
FILE *ptr;
ptr = fopen(argv,"r"); // reading file for conversion
if(ptr==NULL)
{
printf("ERROR: No file found\n"); // if file not found then exit the program
exit(1);
}
/**
* Create new file extension with min in it
*
* test.css -> test.min.css -----
* test.scss -> test.min.scss -----
* test.json -> test.min.json -----
* test.html -> test.min.html --
* test.js -> test.min.js -----
* test.c -> test.min.c ----
* test.cpp -> test.min.cpp
* test.java -> test.min.java
* test.cs -> test.min.cs
**/
int newlen = len+5; // increased length for adding .min
int i=0;
int j=0;
char *newfile = (char*)malloc(sizeof(char)*newlen); // heap memory for new file creation
/**
* extracting the new file name from old file name
**/
while(argv[i]!='\0')
{
if(argv[i]=='.') // file name should have . in it
{
/**
* add min. to string
**/
newfile[j]=argv[i]; //.
j++;
newfile[j]='m';
j++;
newfile[j]='i';
j++;
newfile[j]='n';
j++;
newfile[j]='.';
}
else
{
newfile[j]=argv[i];
}
i++;
j++;
}
newfile[j]='\0';
/**
* Writing the new file i.e is minfile i.e main task
**/
FILE *copy; // file pointer for copying files
copy = fopen(newfile,"w"); // open file for writing
bool flag=false; // boolean for parsing
char str[100]; // string for temp storage
int l=0; // iterator for string storage
/**
* Initialize FLAGS for exceptional behaviour
**/
bool dcomma=false; // boolean for double commas
bool lessgreater=false; // boolean for html > <
bool cart = false; // boolean for ` for js
bool curlybrackets = false; // boolean for { } for js
bool chashtag = false; // boolean for #include for c,cpp
bool cdefine = false; // boolean for #define for c,cpp
bool cppclass = false; // boolean for class
while(!feof(ptr)) // writing the file
{
char ch = fgetc(ptr);
if(ch==' ' || ch=='\n' || ch=='\t' || ch==EOF) // if space new line or tab found
{
if(flag) // when we go from word to space
{
str[l]='\0';
if(css || scss || json) // when css,scss,json file found
{
fprintf(copy,"%s",str); // print the string formed
//compress all chars
if(dcomma==true && json && ch==' ') // comma mechanism for json
{
fputc(ch,copy);
}
}
else if(html) // print space only for html files
{
fprintf(copy,"%s",str); // print the string formed
if((reservedHTML(str) || !lessgreater || dcomma) && ch==' ')
{
fputc(ch,copy); // if html tag found then there should be 1 space
}
}
else if(js) // if js file found
{
fprintf(copy,"%s",str); // print the string formed
if(ch=='\n' && str[l-1]!=';' && !curlybrackets)
{
fputc(';',copy);
}
if((reservedJS(str) || dcomma || cart) && ch==' ')
{
fputc(ch,copy);
}
}
else if(c) // if c file found
{
fprintf(copy,"%s",str); // print the string formed
if(strcmp(str,"#define")==0) // if #define string is finded
{
cdefine=true;
}
else if(ch=='\n') // if line end found
{
cdefine=false;
if(chashtag) // printing \n when header file line is there in c
{
fputc(ch,copy);
chashtag = false;
}
}
if((reservedC(str) || dcomma || cdefine) && ch==' ') // if c reserved words found or double commas
{
fputc(ch,copy); // printing the space char when reserved word found in c
}
}
else if(cpp) // if cpp file found
{
fprintf(copy,"%s",str); // print the string formed
if(strcmp(str,"#define")==0) // if #define string is finded
{
cdefine=true;
}
else if(ch=='\n') // if line end found
{
cdefine=false;
if(chashtag) // printing \n when header file line is there in c
{
fputc(ch,copy);
chashtag = false;
}
}
if((reservedCPP(str) || dcomma || cdefine) && ch==' ') // if cpp reserved words found or double commas
{
fputc(ch,copy); // printing the space char when reserved word found in c
}
}
else if(ch==' ') // for other file format
{
fputc(ch,copy);
}
l=0;
flag=false;
}
}
else // if chars found
{
if(flag==false)
{
flag=true;
}
/**
* MAINTAINING FLAGS BY CHECKING CHAR BY CHAR
* for handling the flags for exceptions in file extension
**/
if(ch=='\"' && (json || html || js || c || cpp)) // if double commas come in json,html,js,c
{
if(dcomma==true) // if string is ending then do it false
{
dcomma=false;
}
else // if string is started then doing it true
{
dcomma=true;
}
}
else if((ch=='<' || ch=='>') && html) // if < > char found change flags
{
if(lessgreater==true) // if lessgreater flag is true make it false for data
{
lessgreater=false;
}
else // if lessgreater flag is false make it true as tags found
{
lessgreater=true;
}
}
else if(ch=='`' && js) // if ` found in string in js
{
if(cart==true)
{
cart=false;
}
else
{
cart=true;
}
}
else if((ch=='{' || ch=='}') && js) // if { } found in the string while parsing in js file
{
if(curlybrackets==true)
{
curlybrackets=false;
}
else
{
curlybrackets=true;
}
}
else if(str[0]=='#' && (c || cpp)) // if # found in the c and cpp file
{
if(chashtag == false)
{
chashtag = true;
}
}
// fputc(ch,copy); // printing all the chars directly to the file
str[l] = ch; // storing the char in temporary string for checks
l++;
}
}
printf("Generated new file name: %s\n",newfile);
fclose(copy);
fclose(ptr);
free(newfile);
/**
* FREEING THE HASHTABLE
**/
freeHashTable();
}
} |
GauravWalia19/minfile | test/C/test2.c | #include <stdio.h>
int main()
{
printf("This is awseome");
#define HEL 12
} |
GauravWalia19/minfile | mfiles/tested/test.min.c | #include<stdio.h>
#define CONST 10
#include<string.h>
int main(){char str[50]="This is test";printf("Hello World");} |
GauravWalia19/minfile | test/C/test1.c | #include <stdio.h>
int main()
{
/**
* checking the comments
**/
//check this test comment
} |
GauravWalia19/minfile | src/util.h | #include "Main.h"
#define HASHSIZE INT_MAX/100000
/*HASHTABLE*/
char** HASH=NULL;
/*FUNCTIONS*/
int hashfunction(char*);
void printHashTable();
void freeHashTable(); |
ryanoabel/incubator-nuttx | arch/risc-v/src/esp32c3/esp32c3_ble_adapter.c | /****************************************************************************
* arch/risc-v/src/esp32c3/esp32c3_ble_adapter.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <debug.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <clock/clock.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <nuttx/kmalloc.h>
#include <nuttx/mqueue.h>
#include <nuttx/spinlock.h>
#include <nuttx/irq.h>
#include <nuttx/kthread.h>
#include <nuttx/wdog.h>
#include <nuttx/wqueue.h>
#include <nuttx/sched.h>
#include <nuttx/signal.h>
#include "hardware/esp32c3_syscon.h"
#include "hardware/wdev_reg.h"
#include "rom/esp32c3_spiflash.h"
#include "espidf_wifi.h"
#include "esp32c3.h"
#include "esp32c3_attr.h"
#include "esp32c3_irq.h"
#include "esp32c3_rt_timer.h"
#include "esp32c3_spiflash.h"
#include "esp32c3_wireless.h"
#include "esp32c3_ble_adapter.h"
#include "esp32c3_wireless.h"
#ifdef CONFIG_ESP32C3_WIFI_BT_COEXIST
# include "esp_coexist_internal.h"
# include "esp_coexist_adapter.h"
#endif
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define OSI_FUNCS_TIME_BLOCKING 0xffffffff
#define OSI_VERSION 0x00010006
#define OSI_MAGIC_VALUE 0xfadebead
#ifdef CONFIG_PM
#define BTDM_MIN_TIMER_UNCERTAINTY_US (1800)
/* Sleep and wakeup interval control */
#define BTDM_MIN_SLEEP_DURATION (24) /* threshold of interval in half slots to allow to fall into modem sleep */
#define BTDM_MODEM_WAKE_UP_DELAY (8) /* delay in half slots of modem wake up procedure, including re-enable PHY/RF */
#endif
/****************************************************************************
* Private Types
****************************************************************************/
/* BLE message queue private data */
struct mq_adpt_s
{
struct file mq; /* Message queue handle */
uint32_t msgsize; /* Message size */
char name[16]; /* Message queue name */
};
/* BLE interrupt adapter private data */
struct irq_adpt_s
{
void (*func)(void *arg); /* Interrupt callback function */
void *arg; /* Interrupt private data */
};
/* BLE low power control struct */
typedef enum btdm_lpclk_sel_e
{
BTDM_LPCLK_SEL_XTAL = 0,
BTDM_LPCLK_SEL_XTAL32K = 1,
BTDM_LPCLK_SEL_RTC_SLOW = 2,
BTDM_LPCLK_SEL_8M = 3,
} btdm_lpclk_sel_t;
typedef enum btdm_vnd_ol_sig_e
{
BTDM_VND_OL_SIG_WAKEUP_TMR,
BTDM_VND_OL_SIG_NUM,
} btdm_vnd_ol_sig_t;
typedef struct btdm_lpcntl_s
{
bool enable; /* whether low power mode is required */
bool wakeup_timer_required; /* whether system timer is needed */
btdm_lpclk_sel_t lpclk_sel; /* low power clock source */
} btdm_lpcntl_t;
/* low power control status */
typedef struct btdm_lpstat_s
{
bool pm_lock_released; /* whether power management lock is released */
bool phy_enabled; /* whether phy is switched on */
bool wakeup_timer_started; /* whether wakeup timer is started */
} btdm_lpstat_t;
struct bt_sem_s
{
sem_t sem;
#ifdef CONFIG_ESP32C3_SPIFLASH
struct esp32c3_wl_semcache_s sc;
#endif
};
#ifdef CONFIG_PM
/* wakeup request sources */
enum btdm_wakeup_src_e
{
BTDM_ASYNC_WAKEUP_SRC_VHCI,
BTDM_ASYNC_WAKEUP_SRC_DISA,
BTDM_ASYNC_WAKEUP_SRC_TMR,
BTDM_ASYNC_WAKEUP_SRC_MAX,
};
#endif
/* prototype of function to handle vendor dependent signals */
typedef void (* btdm_vnd_ol_task_func_t)(void *param);
/* VHCI function interface */
typedef struct vhci_host_callback_s
{
void (*notify_host_send_available)(void); /* callback used to notify that the host can send packet to controller */
int (*notify_host_recv)(uint8_t *data, uint16_t len); /* callback used to notify that the controller has a packet to send to the host */
} vhci_host_callback_t;
/* DRAM region */
typedef struct btdm_dram_available_region_s
{
esp_bt_mode_t mode;
intptr_t start;
intptr_t end;
} btdm_dram_available_region_t;
typedef void (* osi_intr_handler)(void);
/* BLE OS function */
struct osi_funcs_s
{
uint32_t _magic;
uint32_t _version;
void (*_interrupt_set)(int cpu_no, int intr_source,
int interrupt_no, int interrpt_prio);
void (*_interrupt_clear)(int interrupt_source, int interrupt_no);
void (*_interrupt_handler_set)(int interrupt_no, void * fn, void *arg);
void (*_interrupt_disable)(void);
void (*_interrupt_restore)(void);
void (*_task_yield)(void);
void (*_task_yield_from_isr)(void);
void *(*_semphr_create)(uint32_t max, uint32_t init);
void (*_semphr_delete)(void *semphr);
int (*_semphr_take_from_isr)(void *semphr, void *hptw);
int (*_semphr_give_from_isr)(void *semphr, void *hptw);
int (*_semphr_take)(void *semphr, uint32_t block_time_ms);
int (*_semphr_give)(void *semphr);
void *(*_mutex_create)(void);
void (*_mutex_delete)(void *mutex);
int (*_mutex_lock)(void *mutex);
int (*_mutex_unlock)(void *mutex);
void *(* _queue_create)(uint32_t queue_len, uint32_t item_size);
void (* _queue_delete)(void *queue);
int (* _queue_send)(void *queue, void *item, uint32_t block_time_ms);
int (* _queue_send_from_isr)(void *queue, void *item, void *hptw);
int (* _queue_recv)(void *queue, void *item, uint32_t block_time_ms);
int (* _queue_recv_from_isr)(void *queue, void *item, void *hptw);
int (* _task_create)(void *task_func, const char *name,
uint32_t stack_depth, void *param, uint32_t prio,
void *task_handle, uint32_t core_id);
void (* _task_delete)(void *task_handle);
bool (* _is_in_isr)(void);
int (* _cause_sw_intr_to_core)(int core_id, int intr_no);
void *(* _malloc)(size_t size);
void *(* _malloc_internal)(size_t size);
void (* _free)(void *p);
int (* _read_efuse_mac)(uint8_t mac[6]);
void (* _srand)(unsigned int seed);
int (* _rand)(void);
uint32_t (* _btdm_lpcycles_2_hus)(uint32_t cycles, uint32_t *error_corr);
uint32_t (* _btdm_hus_2_lpcycles)(uint32_t us);
bool (* _btdm_sleep_check_duration)(int32_t *slot_cnt);
void (* _btdm_sleep_enter_phase1)(uint32_t lpcycles); /* called when interrupt is disabled */
void (* _btdm_sleep_enter_phase2)(void);
void (* _btdm_sleep_exit_phase1)(void); /* called from ISR */
void (* _btdm_sleep_exit_phase2)(void); /* called from ISR */
void (* _btdm_sleep_exit_phase3)(void); /* called from task */
void (* _coex_wifi_sleep_set)(bool sleep);
int (* _coex_core_ble_conn_dyn_prio_get)(bool *low, bool *high);
void (* _coex_schm_status_bit_set)(uint32_t type, uint32_t status);
void (* _coex_schm_status_bit_clear)(uint32_t type, uint32_t status);
void (* _interrupt_on)(int intr_num);
void (* _interrupt_off)(int intr_num);
void (* _esp_hw_power_down)(void);
void (* _esp_hw_power_up)(void);
void (* _ets_backup_dma_copy)(uint32_t reg,
uint32_t mem_addr, uint32_t num,
bool to_rem);
};
/****************************************************************************
* Private Function
****************************************************************************/
static void interrupt_set_wrapper(int cpu_no, int intr_source,
int intr_num, int intr_prio);
static void interrupt_clear_wrapper(int intr_source, int intr_num);
static void interrupt_handler_set_wrapper(int n, void *fn, void *arg);
static void interrupt_disable(void);
static void interrupt_restore(void);
static void task_yield_from_isr(void);
static void *semphr_create_wrapper(uint32_t max, uint32_t init);
static void semphr_delete_wrapper(void *semphr);
static int semphr_take_from_isr_wrapper(void *semphr, void *hptw);
static int semphr_give_from_isr_wrapper(void *semphr, void *hptw);
static int semphr_take_wrapper(void *semphr, uint32_t block_time_ms);
static int semphr_give_wrapper(void *semphr);
static void *mutex_create_wrapper(void);
static void mutex_delete_wrapper(void *mutex);
static int mutex_lock_wrapper(void *mutex);
static int mutex_unlock_wrapper(void *mutex);
static int queue_send_from_isr_wrapper(void *queue, void *item,
void *hptw);
static int queue_recv_from_isr_wrapper(void *queue, void *item,
void *hptw);
static int task_create_wrapper(void *task_func, const char *name,
uint32_t stack_depth, void *param,
uint32_t prio, void *task_handle,
uint32_t core_id);
static void task_delete_wrapper(void *task_handle);
static bool is_in_isr_wrapper(void);
static void *malloc_wrapper(size_t size);
static void *malloc_internal_wrapper(size_t size);
static int read_mac_wrapper(uint8_t mac[6]);
static void srand_wrapper(unsigned int seed);
static int rand_wrapper(void);
static uint32_t btdm_lpcycles_2_hus(uint32_t cycles,
uint32_t *error_corr);
static uint32_t btdm_hus_2_lpcycles(uint32_t us);
static void coex_wifi_sleep_set_hook(bool sleep);
static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status);
static void coex_schm_status_bit_clear_wrapper(uint32_t type,
uint32_t status);
static void interrupt_on_wrapper(int intr_num);
static void interrupt_off_wrapper(int intr_num);
static void *queue_create_wrapper(uint32_t queue_len, uint32_t item_size);
static int queue_send_wrapper(void *queue, void *item,
uint32_t block_time_ms);
static int queue_recv_wrapper(void *queue, void *item,
uint32_t block_time_ms);
static void queue_delete_wrapper(void *queue);
#ifdef CONFIG_PM
static bool btdm_sleep_check_duration(int32_t *half_slot_cnt);
static void btdm_sleep_enter_phase1_wrapper(uint32_t lpcycles);
static void btdm_sleep_enter_phase2_wrapper(void);
static void btdm_sleep_exit_phase3_wrapper(void);
#endif
/****************************************************************************
* Extern Functions declaration and value
****************************************************************************/
extern int btdm_osi_funcs_register(void *osi_funcs);
extern void btdm_controller_rom_data_init(void);
/* Initialise and De-initialise */
extern int btdm_controller_init(esp_bt_controller_config_t *config_opts);
extern void btdm_controller_deinit(void);
extern int btdm_controller_enable(esp_bt_mode_t mode);
extern void btdm_controller_disable(void);
extern uint8_t btdm_controller_get_mode(void);
extern const char *btdm_controller_get_compile_version(void);
extern void btdm_rf_bb_init_phase2(void); /* shall be called after PHY/RF is enabled */
/* Sleep */
extern void btdm_controller_enable_sleep(bool enable);
extern uint8_t btdm_controller_get_sleep_mode(void);
extern bool btdm_power_state_active(void);
extern void btdm_wakeup_request(void);
extern void btdm_in_wakeup_requesting_set(bool in_wakeup_requesting);
/* vendor dependent tasks to be posted and handled by controller task */
extern int btdm_vnd_offload_task_register(btdm_vnd_ol_sig_t sig,
btdm_vnd_ol_task_func_t func);
extern int btdm_vnd_offload_task_deregister(btdm_vnd_ol_sig_t sig);
extern int btdm_vnd_offload_post_from_isr(btdm_vnd_ol_sig_t sig,
void *param, bool need_yield);
extern int btdm_vnd_offload_post(btdm_vnd_ol_sig_t sig, void *param);
/* Low Power Clock */
extern bool btdm_lpclk_select_src(uint32_t sel);
extern bool btdm_lpclk_set_div(uint32_t div);
extern int btdm_hci_tl_io_event_post(int event);
/* VHCI */
extern bool api_vhci_host_check_send_available(void); /* Functions in bt lib */
extern void api_vhci_host_send_packet(uint8_t * data, uint16_t len);
extern int api_vhci_host_register_callback(const vhci_host_callback_t
*callback);
/* TX power */
extern int ble_txpwr_set(int power_type, int power_level);
extern int ble_txpwr_get(int power_type);
extern uint16_t l2c_ble_link_get_tx_buf_num(void);
extern int coex_core_ble_conn_dyn_prio_get(bool *low, bool *high);
extern bool btdm_deep_sleep_mem_init(void);
extern void btdm_deep_sleep_mem_deinit(void);
extern void btdm_ble_power_down_dma_copy(bool copy);
extern uint8_t btdm_sleep_clock_sync(void);
extern char _bss_start_btdm;
extern char _bss_end_btdm;
extern char _data_start_btdm;
extern char _data_end_btdm;
extern uint32_t _data_start_btdm_rom;
extern uint32_t _data_end_btdm_rom;
extern uint32_t _bt_bss_start;
extern uint32_t _bt_bss_end;
extern uint32_t _btdm_bss_start;
extern uint32_t _btdm_bss_end;
extern uint32_t _bt_data_start;
extern uint32_t _bt_data_end;
extern uint32_t _btdm_data_start;
extern uint32_t _btdm_data_end;
extern char _bt_tmp_bss_start;
extern char _bt_tmp_bss_end;
/****************************************************************************
* Private Data
****************************************************************************/
/* Controller status */
static DRAM_ATTR esp_bt_controller_status_t btdm_controller_status =
ESP_BT_CONTROLLER_STATUS_IDLE;
/* low power control struct */
static DRAM_ATTR btdm_lpcntl_t g_lp_cntl;
/* low power status struct */
static DRAM_ATTR btdm_lpstat_t g_lp_stat;
/* measured average low power clock period in micro seconds */
static DRAM_ATTR uint32_t g_btdm_lpcycle_us = 0;
/* number of fractional bit for g_btdm_lpcycle_us */
static DRAM_ATTR uint8_t g_btdm_lpcycle_us_frac = 0;
#ifdef CONFIG_PM
/* semaphore used for blocking VHCI API to wait for controller to wake up */
static DRAM_ATTR void * g_wakeup_req_sem = NULL;
/* wakeup timer */
static DRAM_ATTR esp_timer_handle_t g_btdm_slp_tmr;
#endif
/* BT interrupt private data */
static bool g_ble_irq_bind;
static irqstate_t g_inter_flags;
/****************************************************************************
* Public Data
****************************************************************************/
/* BLE OS adapter data */
static struct osi_funcs_s g_osi_funcs =
{
._magic = OSI_MAGIC_VALUE,
._version = OSI_VERSION,
._interrupt_set = interrupt_set_wrapper,
._interrupt_clear = interrupt_clear_wrapper,
._interrupt_handler_set = interrupt_handler_set_wrapper,
._interrupt_disable = interrupt_disable,
._interrupt_restore = interrupt_restore,
._task_yield = task_yield_from_isr,
._task_yield_from_isr = task_yield_from_isr,
._semphr_create = semphr_create_wrapper,
._semphr_delete = semphr_delete_wrapper,
._semphr_take_from_isr = semphr_take_from_isr_wrapper,
._semphr_give_from_isr = semphr_give_from_isr_wrapper,
._semphr_take = semphr_take_wrapper,
._semphr_give = semphr_give_wrapper,
._mutex_create = mutex_create_wrapper,
._mutex_delete = mutex_delete_wrapper,
._mutex_lock = mutex_lock_wrapper,
._mutex_unlock = mutex_unlock_wrapper,
._queue_create = queue_create_wrapper,
._queue_delete = queue_delete_wrapper,
._queue_send = queue_send_wrapper,
._queue_send_from_isr = queue_send_from_isr_wrapper,
._queue_recv = queue_recv_wrapper,
._queue_recv_from_isr = queue_recv_from_isr_wrapper,
._task_create = task_create_wrapper,
._task_delete = task_delete_wrapper,
._is_in_isr = is_in_isr_wrapper,
._malloc = malloc_wrapper,
._malloc_internal = malloc_internal_wrapper,
._free = free,
._read_efuse_mac = read_mac_wrapper,
._srand = srand_wrapper,
._rand = rand_wrapper,
._btdm_lpcycles_2_hus = btdm_lpcycles_2_hus,
._btdm_hus_2_lpcycles = btdm_hus_2_lpcycles,
#ifdef CONFIG_PM
._btdm_sleep_check_duration = btdm_sleep_check_duration,
._btdm_sleep_enter_phase1 = btdm_sleep_enter_phase1_wrapper,
._btdm_sleep_enter_phase2 = btdm_sleep_enter_phase2_wrapper,
._btdm_sleep_exit_phase3 = btdm_sleep_exit_phase3_wrapper,
#endif
._coex_wifi_sleep_set = coex_wifi_sleep_set_hook,
._coex_core_ble_conn_dyn_prio_get = coex_core_ble_conn_dyn_prio_get,
._coex_schm_status_bit_set = coex_schm_status_bit_set_wrapper,
._coex_schm_status_bit_clear = coex_schm_status_bit_clear_wrapper,
._interrupt_on = interrupt_on_wrapper,
._interrupt_off = interrupt_off_wrapper,
};
/****************************************************************************
* Private Functions and Public Functions only used by libraries
****************************************************************************/
/****************************************************************************
* Name: esp_errno_trans
*
* Description:
* Transform from nuttx error code to Wi-Fi adapter error code
*
* Input Parameters:
* ret - NuttX error code
*
* Returned Value:
* Wi-Fi adapter error code
*
****************************************************************************/
static inline int32_t esp_errno_trans(int ret)
{
if (!ret)
{
return true;
}
else
{
return false;
}
}
/****************************************************************************
* Name: esp_task_create_pinned_to_core
*
* Description:
* Create task and bind it to target CPU, the task will run when it
* is created
*
* Input Parameters:
* entry - Task entry
* name - Task name
* stack_depth - Task stack size
* param - Task private data
* prio - Task priority
* task_handle - Task handle pointer which is used to pause, resume
* and delete the task
* core_id - CPU which the task runs in
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int32_t esp_task_create_pinned_to_core(void *entry,
const char *name,
uint32_t stack_depth,
void *param,
uint32_t prio,
void *task_handle,
uint32_t core_id)
{
int pid;
pid = kthread_create(name, prio, stack_depth, entry,
(char * const *)param);
if (pid > 0)
{
if (task_handle)
{
*((int *)task_handle) = pid;
}
}
else
{
wlerr("Failed to create task\n");
}
return pid > 0 ? true : false;
}
/****************************************************************************
* Name: interrupt_set_wrapper
*
* Description:
* Bind IRQ and resource with given parameters.
*
* Input Parameters:
* cpu_no - The CPU which the interrupt number belongs.
* intr_source - The interrupt hardware source number.
* intr_num - The interrupt number CPU.
* intr_prio - The interrupt priority.
*
* Returned Value:
* None
*
****************************************************************************/
static void interrupt_set_wrapper(int cpu_no,
int intr_source,
int intr_num,
int intr_prio)
{
wlinfo("cpu_no=%d , intr_source=%d , intr_num=%d, intr_prio=%d\n",
cpu_no, intr_source, intr_num, intr_prio);
esp32c3_bind_irq(intr_num, intr_source, intr_prio, ESP32C3_INT_LEVEL);
#ifdef CONFIG_ESP32C3_SPIFLASH
esp32c3_spiflash_unmask_cpuint(intr_num);
#endif
}
/****************************************************************************
* Name: interrupt_clear_wrapper
*
* Description:
* Not supported
*
****************************************************************************/
static void IRAM_ATTR interrupt_clear_wrapper(int intr_source, int intr_num)
{
}
/****************************************************************************
* Name: esp_int_adpt_cb
*
* Description:
* BT interrupt adapter callback function
*
* Input Parameters:
* arg - interrupt adapter private data
*
* Returned Value:
* NuttX error code
*
****************************************************************************/
static int IRAM_ATTR esp_int_adpt_cb(int irq, void *context, FAR void *arg)
{
struct irq_adpt_s *adapter = (struct irq_adpt_s *)arg;
adapter->func(adapter->arg);
return OK;
}
/****************************************************************************
* Name: interrupt_handler_set_wrapper
*
* Description:
* Register interrupt function
*
* Input Parameters:
* n - Interrupt ID
* f - Interrupt function
* arg - Function private data
*
* Returned Value:
* None
*
****************************************************************************/
static void interrupt_handler_set_wrapper(int n, void *fn, void *arg)
{
int ret;
struct irq_adpt_s *adapter;
if (g_ble_irq_bind)
{
return;
}
adapter = kmm_malloc(sizeof(struct irq_adpt_s));
DEBUGASSERT(adapter);
adapter->func = fn;
adapter->arg = arg;
ret = irq_attach(n + ESP32C3_IRQ_FIRSTPERIPH, esp_int_adpt_cb, adapter);
DEBUGASSERT(ret == OK);
g_ble_irq_bind = true;
}
/****************************************************************************
* Name: esp32c3_ints_on
*
* Description:
* Enable Wi-Fi interrupt
*
* Input Parameters:
* intr_num - No mean
*
* Returned Value:
* None
*
****************************************************************************/
static void interrupt_on_wrapper(int intr_num)
{
up_enable_irq(intr_num);
}
/****************************************************************************
* Name: esp32c3_ints_off
*
* Description:
* Disable Wi-Fi interrupt
*
* Input Parameters:
* intr_num - No mean
*
* Returned Value:
* None
*
****************************************************************************/
static void interrupt_off_wrapper(int intr_num)
{
up_disable_irq(intr_num);
}
/****************************************************************************
* Name: interrupt_disable
*
* Description:
* Enter critical section by disabling interrupts and taking the spin lock
* if in SMP mode.
*
* Input Parameters:
* None
*
* Returned Value:
* None.
*
****************************************************************************/
static void IRAM_ATTR interrupt_disable(void)
{
g_inter_flags = enter_critical_section();
}
/****************************************************************************
* Name: interrupt_restore
*
* Description:
* Exit from critical section by enabling interrupts and releasing the spin
* lock if in SMP mode.
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void IRAM_ATTR interrupt_restore(void)
{
leave_critical_section(g_inter_flags);
}
/****************************************************************************
* Name: task_yield_from_isr
*
* Description:
* Do nothing in NuttX
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void task_yield_from_isr(void)
{
}
/****************************************************************************
* Name: semphr_create_wrapper
*
* Description:
* Create and initialize semaphore
*
* Input Parameters:
* max - Unused
* init - semaphore initialization value
*
* Returned Value:
* Semaphore data pointer
*
****************************************************************************/
static void *semphr_create_wrapper(uint32_t max, uint32_t init)
{
int ret;
struct bt_sem_s *bt_sem;
int tmp;
tmp = sizeof(struct bt_sem_s);
bt_sem = kmm_malloc(tmp);
DEBUGASSERT(bt_sem);
ret = sem_init(&bt_sem->sem, 0, init);
DEBUGASSERT(ret == OK);
#ifdef CONFIG_ESP32C3_SPIFLASH
esp32c3_wl_init_semcache(&bt_sem->sc, &bt_sem->sem);
#endif
return bt_sem;
}
/****************************************************************************
* Name: semphr_delete_wrapper
*
* Description:
* Delete semaphore
*
* Input Parameters:
* semphr - Semaphore data pointer
*
* Returned Value:
* None
*
****************************************************************************/
static void semphr_delete_wrapper(void *semphr)
{
struct bt_sem_s *bt_sem = (struct bt_sem_s *)semphr;
sem_destroy(&bt_sem->sem);
kmm_free(bt_sem);
}
/****************************************************************************
* Name: semphr_take_from_isr_wrapper
*
* Description:
* Take a semaphore from an ISR.
*
* Input Parameters:
* semphr - Semaphore data pointer
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int semphr_take_from_isr_wrapper(void *semphr, void *hptw)
{
DEBUGASSERT(0);
return false;
}
/****************************************************************************
* Name: semphr_give_from_isr_wrapper
*
* Description:
* Post semaphore
*
* Input Parameters:
* semphr - Semaphore data pointer
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int IRAM_ATTR semphr_give_from_isr_wrapper(void *semphr, void *hptw)
{
int ret;
struct bt_sem_s *bt_sem = (struct bt_sem_s *)semphr;
#ifdef CONFIG_ESP32C3_SPIFLASH
if (spi_flash_cache_enabled())
{
ret = semphr_give_wrapper(&bt_sem->sem);
ret = esp_errno_trans(ret);
}
else
{
esp32c3_wl_post_semcache(&bt_sem->sc);
ret = true;
}
#else
ret = semphr_give_wrapper(&bt_sem->sem);
ret = esp_errno_trans(ret);
#endif
return ret;
}
/****************************************************************************
* Name: esp_update_time
*
* Description:
* Transform ticks to time and add this time to timespec value
*
* Input Parameters:
* timespec - Input timespec data pointer
* ticks - System ticks
*
* Returned Value:
* None
*
****************************************************************************/
static void esp_update_time(struct timespec *timespec, uint32_t ticks)
{
uint32_t tmp;
tmp = TICK2SEC(ticks);
timespec->tv_sec += tmp;
ticks -= SEC2TICK(tmp);
tmp = TICK2NSEC(ticks);
timespec->tv_nsec += tmp;
}
/****************************************************************************
* Name: semphr_take_wrapper
*
* Description:
* Wait semaphore within a certain period of time
*
* Input Parameters:
* semphr - Semaphore data pointer
* block_time_ms - Wait time
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int semphr_take_wrapper(void *semphr, uint32_t block_time_ms)
{
int ret;
struct timespec timeout;
struct bt_sem_s *bt_sem = (struct bt_sem_s *)semphr;
if (block_time_ms == OSI_FUNCS_TIME_BLOCKING)
{
ret = sem_wait(&bt_sem->sem);
if (ret)
{
wlerr("Failed to wait sem\n");
}
}
else
{
if (block_time_ms > 0)
{
ret = clock_gettime(CLOCK_REALTIME, &timeout);
if (ret < 0)
{
wlerr("Failed to get time\n");
return false;
}
esp_update_time(&timeout, MSEC2TICK(block_time_ms));
ret = sem_timedwait(&bt_sem->sem, &timeout);
}
else
{
ret = sem_trywait(&bt_sem->sem);
}
}
return esp_errno_trans(ret);
}
/****************************************************************************
* Name: semphr_give_wrapper
*
* Description:
* Post semaphore
*
* Input Parameters:
* semphr - Semaphore data pointer
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int semphr_give_wrapper(void *semphr)
{
int ret;
struct bt_sem_s *bt_sem = (struct bt_sem_s *)semphr;
ret = sem_post(&bt_sem->sem);
if (ret)
{
wlerr("Failed to post sem error=%d\n", ret);
}
return esp_errno_trans(ret);
}
/****************************************************************************
* Name: mutex_create_wrapper
*
* Description:
* Create mutex
*
* Input Parameters:
* None
*
* Returned Value:
* Mutex data pointer
*
****************************************************************************/
static void *mutex_create_wrapper(void)
{
int ret;
pthread_mutex_t *mutex;
int tmp;
tmp = sizeof(pthread_mutex_t);
mutex = kmm_malloc(tmp);
DEBUGASSERT(mutex);
ret = pthread_mutex_init(mutex, NULL);
if (ret)
{
wlerr("Failed to initialize mutex error=%d\n", ret);
kmm_free(mutex);
return NULL;
}
return mutex;
}
/****************************************************************************
* Name: mutex_delete_wrapper
*
* Description:
* Delete mutex
*
* Input Parameters:
* None
*
* Returned Value:
* Mutex data pointer
*
****************************************************************************/
static void mutex_delete_wrapper(void *mutex)
{
pthread_mutex_destroy(mutex);
kmm_free(mutex);
}
/****************************************************************************
* Name: mutex_lock_wrapper
*
* Description:
* Lock mutex
*
* Input Parameters:
* mutex_data - mutex data pointer
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int mutex_lock_wrapper(void *mutex)
{
int ret;
ret = pthread_mutex_lock(mutex);
if (ret)
{
wlerr("Failed to lock mutex error=%d\n", ret);
}
return esp_errno_trans(ret);
}
/****************************************************************************
* Name: mutex_unlock_wrapper
*
* Description:
* Unlock mutex
*
* Input Parameters:
* mutex_data - mutex data pointer
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int mutex_unlock_wrapper(void *mutex)
{
int ret;
ret = pthread_mutex_unlock(mutex);
if (ret)
{
wlerr("Failed to unlock mutex error=%d\n", ret);
}
return esp_errno_trans(ret);
}
/****************************************************************************
* Name: esp_queue_send_generic
*
* Description:
* Generic send message to queue within a certain period of time
*
* Input Parameters:
* queue - Message queue data pointer
* item - Message data pointer
* ticks - Wait ticks
* prio - Message priority
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int32_t esp_queue_send_generic(void *queue, void *item,
uint32_t ticks, int prio)
{
int ret;
struct timespec timeout;
struct mq_adpt_s *mq_adpt = (struct mq_adpt_s *)queue;
if (ticks == OSI_FUNCS_TIME_BLOCKING || ticks == 0)
{
/**
* BLE interrupt function will call this adapter function to send
* message to message queue, so here we should call kernel API
* instead of application API
*/
ret = file_mq_send(&mq_adpt->mq, (const char *)item,
mq_adpt->msgsize, prio);
if (ret < 0)
{
wlerr("Failed to send message to mqueue error=%d\n", ret);
}
}
else
{
ret = clock_gettime(CLOCK_REALTIME, &timeout);
if (ret < 0)
{
wlerr("Failed to get time\n");
return false;
}
if (ticks)
{
esp_update_time(&timeout, ticks);
}
ret = file_mq_timedsend(&mq_adpt->mq, (const char *)item,
mq_adpt->msgsize, prio, &timeout);
if (ret < 0)
{
wlerr("Failed to timedsend message to mqueue error=%d\n", ret);
}
}
return esp_errno_trans(ret);
}
/****************************************************************************
* Name: queue_send_from_isr_wrapper
*
* Description:
* Send message of low priority to queue in ISR within
* a certain period of time
*
* Input Parameters:
* queue - Message queue data pointer
* item - Message data pointer
* hptw - Unused
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int IRAM_ATTR queue_send_from_isr_wrapper(void *queue,
void *item,
void *hptw)
{
return esp_queue_send_generic(queue, item, 0, 0);
}
/****************************************************************************
* Name: queue_recv_from_isr_wrapper
*
* Description:
* Receive message from queue within a certain period of time
*
* Input Parameters:
* queue - Message queue data pointer
* item - Message data pointer
* hptw - Unused
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int queue_recv_from_isr_wrapper(void *queue, void *item, void *hptw)
{
DEBUGASSERT(0);
return false;
}
/****************************************************************************
* Name: task_create_wrapper
*
* Description:
* Create task and the task will run when it is created
*
* Input Parameters:
* entry - Task entry
* name - Task name
* stack_depth - Task stack size
* param - Task private data
* prio - Task priority
* task_handle - Task handle pointer which is used to pause, resume
* and delete the task
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int task_create_wrapper(void *task_func, const char *name,
uint32_t stack_depth, void *param,
uint32_t prio, void *task_handle,
uint32_t core_id)
{
return esp_task_create_pinned_to_core(task_func, name,
stack_depth, param,
prio, task_handle, UINT32_MAX);
}
/****************************************************************************
* Name: task_delete_wrapper
*
* Description:
* Delete the target task
*
* Input Parameters:
* task_handle - Task handle pointer which is used to pause, resume
* and delete the task
*
* Returned Value:
* None
*
****************************************************************************/
static void task_delete_wrapper(void *task_handle)
{
pid_t pid = (pid_t)((uintptr_t)task_handle);
kthread_delete(pid);
}
/****************************************************************************
* Name: is_in_isr_wrapper
*
* Description:
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static bool IRAM_ATTR is_in_isr_wrapper(void)
{
return false;
}
/****************************************************************************
* Name: malloc_wrapper
*
* Description:
* Malloc buffer
*
* Input Parameters:
* szie - buffer size
*
* Returned Value:
* None
*
****************************************************************************/
static void *malloc_wrapper(size_t size)
{
void * p = NULL;
p = kmm_malloc(size);
DEBUGASSERT(p);
return p;
}
/****************************************************************************
* Name: malloc_internal_wrapper
*
* Description:
* Malloc buffer in DRAM
*
* Input Parameters:
* szie - buffer size
*
* Returned Value:
* None
*
****************************************************************************/
static void *malloc_internal_wrapper(size_t size)
{
void * p = NULL;
p = kmm_malloc(size);
DEBUGASSERT(p);
return p;
}
/****************************************************************************
* Name: read_mac_wrapper
*
* Description:
* Get Mac Address
*
* Input Parameters:
* mac - mac address
*
* Returned Value:
* None
*
****************************************************************************/
static int read_mac_wrapper(uint8_t mac[6])
{
return 0;
}
/****************************************************************************
* Name: srand_wrapper
*
* Description:
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void srand_wrapper(unsigned int seed)
{
/* empty function */
}
/****************************************************************************
* Name: rand_wrapper
*
* Description:
* Get random value
* Input Parameters:
* None
*
* Returned Value:
* Random value
*
****************************************************************************/
static IRAM_ATTR int rand_wrapper(void)
{
return getreg32(WDEV_RND_REG);
}
/****************************************************************************
* Name: btdm_lpcycles_2_hus
*
* Description:
* Converts a number of low power clock cycles into a duration in half us.
*
* Input Parameters:
* cycles
* error_corr
*
* Returned Value:
* us
*
****************************************************************************/
static uint32_t IRAM_ATTR btdm_lpcycles_2_hus(uint32_t cycles,
uint32_t *error_corr)
{
uint64_t us = (uint64_t)g_btdm_lpcycle_us * cycles;
us = (us + (1 << (g_btdm_lpcycle_us_frac - 1))) >> g_btdm_lpcycle_us_frac;
return (uint32_t)us;
}
/****************************************************************************
* Name: btdm_hus_2_lpcycles
*
* Description:
* Converts a duration in half us into a number of low power clock cycles.
*
* Input Parameters:
* us
*
* Returned Value:
* cycles
*
****************************************************************************/
static uint32_t IRAM_ATTR btdm_hus_2_lpcycles(uint32_t us)
{
uint64_t cycles;
cycles = ((uint64_t)(us) << g_btdm_lpcycle_us_frac) / g_btdm_lpcycle_us;
return (uint32_t)cycles;
}
#ifdef CONFIG_PM
/****************************************************************************
* Name: btdm_sleep_exit_phase0
*
* Description:
* acquire PM lock and stop esp timer.
*
* Input Parameters:
* param - wakeup event
*
* Returned Value:
* None
*
****************************************************************************/
static void IRAM_ATTR btdm_sleep_exit_phase0(void *param)
{
DEBUGASSERT(g_lp_cntl.enable == true);
if (g_lp_stat.pm_lock_released)
{
esp32c3_pm_lockacquire();
g_lp_stat.pm_lock_released = false;
}
int event = (int) param;
if (event == BTDM_ASYNC_WAKEUP_SRC_VHCI ||
event == BTDM_ASYNC_WAKEUP_SRC_DISA)
{
btdm_wakeup_request();
}
if (g_lp_cntl.wakeup_timer_required && g_lp_stat.wakeup_timer_started)
{
esp_timer_stop(g_btdm_slp_tmr);
g_lp_stat.wakeup_timer_started = false;
}
if (event == BTDM_ASYNC_WAKEUP_SRC_VHCI ||
event == BTDM_ASYNC_WAKEUP_SRC_DISA)
{
semphr_give_wrapper(g_wakeup_req_sem);
}
}
/****************************************************************************
* Name: btdm_slp_tmr_callback
*
* Description:
* Esp ble sleep callback function.
*
* Input Parameters:
* arg - Unused
*
* Returned Value:
* None
*
****************************************************************************/
static void IRAM_ATTR btdm_slp_tmr_callback(void *arg)
{
btdm_vnd_offload_post(BTDM_VND_OL_SIG_WAKEUP_TMR,
(void *)BTDM_ASYNC_WAKEUP_SRC_TMR);
}
/****************************************************************************
* Name: btdm_sleep_check_duration
*
* Description:
* Wake up in advance considering the delay in enabling PHY/RF.
*
* Input Parameters:
* half_slot_cnt - half slots to allow to fall into modem sleep
*
* Returned Value:
* None
*
****************************************************************************/
static bool IRAM_ATTR btdm_sleep_check_duration(int32_t *half_slot_cnt)
{
if (*half_slot_cnt < BTDM_MIN_SLEEP_DURATION)
{
return false;
}
*half_slot_cnt -= BTDM_MODEM_WAKE_UP_DELAY;
return true;
}
/****************************************************************************
* Name: btdm_sleep_enter_phase1_wrapper
*
* Description:
* ESP32C3 BLE lightsleep callback function.
*
* Input Parameters:
* lpcycles - light sleep cycles
*
* Returned Value:
* None
*
****************************************************************************/
static void btdm_sleep_enter_phase1_wrapper(uint32_t lpcycles)
{
if (g_lp_cntl.wakeup_timer_required == false)
{
return;
}
/* start a timer to wake up and acquire the pm_lock before sleep awakes */
uint32_t us_to_sleep = btdm_lpcycles_2_hus(lpcycles, NULL) >> 1;
DEBUGASSERT(us_to_sleep > BTDM_MIN_TIMER_UNCERTAINTY_US);
uint32_t uncertainty = (us_to_sleep >> 11);
if (uncertainty < BTDM_MIN_TIMER_UNCERTAINTY_US)
{
uncertainty = BTDM_MIN_TIMER_UNCERTAINTY_US;
}
DEBUGASSERT(g_lp_stat.wakeup_timer_started == false);
if (esp_timer_start_once(g_btdm_slp_tmr,
us_to_sleep - uncertainty) == ESP_OK)
{
g_lp_stat.wakeup_timer_started = true;
}
else
{
wlerr("timer start failed");
DEBUGASSERT(0);
}
}
/****************************************************************************
* Name: btdm_sleep_enter_phase2_wrapper
*
* Description:
* ESP32C3 BLE lightsleep callback function.
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void btdm_sleep_enter_phase2_wrapper(void)
{
if (btdm_controller_get_sleep_mode() == ESP_BT_SLEEP_MODE_1)
{
if (g_lp_stat.phy_enabled)
{
bt_phy_disable();
g_lp_stat.phy_enabled = false;
}
else
{
DEBUGASSERT(0);
}
if (g_lp_stat.pm_lock_released == false)
{
esp32c3_pm_lockrelease();
g_lp_stat.pm_lock_released = true;
}
}
}
/****************************************************************************
* Name: btdm_sleep_exit_phase3_wrapper
*
* Description:
* ESP32C3 BLE lightsleep callback function..
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void btdm_sleep_exit_phase3_wrapper(void)
{
if (g_lp_stat.pm_lock_released)
{
esp32c3_pm_lockacquire();
g_lp_stat.pm_lock_released = false;
}
if (btdm_sleep_clock_sync())
{
wlerr("sleep eco state err\n");
DEBUGASSERT(0);
}
if (btdm_controller_get_sleep_mode() == ESP_BT_SLEEP_MODE_1)
{
if (g_lp_stat.phy_enabled == false)
{
bt_phy_enable();
g_lp_stat.phy_enabled = true;
}
}
if (g_lp_cntl.wakeup_timer_required && g_lp_stat.wakeup_timer_started)
{
esp_timer_stop(g_btdm_slp_tmr);
g_lp_stat.wakeup_timer_started = false;
}
}
#endif
/****************************************************************************
* Name: coex_schm_status_bit_set_wrapper
*
* Description:
*
* Input Parameters:
* type
* status
*
* Returned Value:
* None
*
****************************************************************************/
static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status)
{
#ifdef CONFIG_ESP32C3_WIFI_BT_COEXIST
coex_schm_status_bit_set(type, status);
#endif
}
/****************************************************************************
* Name: coex_schm_status_bit_clear_wrapper
*
* Description:
*
* Input Parameters:
* szie
* status
*
* Returned Value:
* None
*
****************************************************************************/
static void coex_schm_status_bit_clear_wrapper(uint32_t type,
uint32_t status)
{
#ifdef CONFIG_ESP32C3_WIFI_BT_COEXIST
coex_schm_status_bit_clear(type, status);
#endif
}
/****************************************************************************
* Name: btdm_controller_mem_init
*
* Description:
* Initialize BT controller to allocate task and other resource.
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void btdm_controller_mem_init(void)
{
btdm_controller_rom_data_init();
}
/****************************************************************************
* Name: phy_printf
*
* Description:
* Output format string and its arguments
*
* Input Parameters:
* format - format string
*
* Returned Value:
* 0
*
****************************************************************************/
#ifndef CONFIG_ESP32C3_WIFI
int phy_printf(const char *format, ...)
{
#ifdef CONFIG_DEBUG_WIRELESS_INFO
va_list arg;
va_start(arg, format);
vsyslog(LOG_INFO, format, arg);
va_end(arg);
#endif
return 0;
}
#endif
/****************************************************************************
* Name: bt_phy_disable
*
* Description:
* Disable BT phy.
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void bt_phy_disable(void)
{
esp32c3_phy_disable();
}
/****************************************************************************
* Name: bt_phy_enable
*
* Description:
* Enable BT phy.
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void bt_phy_enable(void)
{
esp32c3_phy_enable();
}
/****************************************************************************
* Name: coex_wifi_sleep_set_hook
*
* Description:
* Don't support
*
****************************************************************************/
static void coex_wifi_sleep_set_hook(bool sleep)
{
}
/****************************************************************************
* Name: queue_create_wrapper
*
* Description:
* Create message queue
*
* Input Parameters:
* queue_len - queue message number
* item_size - message size
*
* Returned Value:
* Message queue data pointer
*
****************************************************************************/
static void *queue_create_wrapper(uint32_t queue_len, uint32_t item_size)
{
struct mq_attr attr;
struct mq_adpt_s *mq_adpt;
int ret;
mq_adpt = kmm_malloc(sizeof(struct mq_adpt_s));
DEBUGASSERT(mq_adpt);
snprintf(mq_adpt->name, sizeof(mq_adpt->name), "/tmp/%p", mq_adpt);
attr.mq_maxmsg = queue_len;
attr.mq_msgsize = item_size;
attr.mq_curmsgs = 0;
attr.mq_flags = 0;
ret = file_mq_open(&mq_adpt->mq, mq_adpt->name,
O_RDWR | O_CREAT, 0644, &attr);
if (ret < 0)
{
wlerr("Failed to create mqueue\n");
kmm_free(mq_adpt);
return NULL;
}
mq_adpt->msgsize = item_size;
return (void *)mq_adpt;
}
/****************************************************************************
* Name: queue_send_wrapper
*
* Description:
* Generic send message to queue within a certain period of time
*
* Input Parameters:
* queue - Message queue data pointer
* item - Message data pointerint
* block_time_ms - Wait time
*
* Returned Value:uint32_t
* True if success or false if fail
*
****************************************************************************/
static int queue_send_wrapper(void *queue, void *item,
uint32_t block_time_ms)
{
return esp_queue_send_generic(queue, item, block_time_ms, 0);
}
/****************************************************************************
* Name: queue_recv_wrapper
*
* Description:
* Receive message from queue within a certain period of time
*
* Input Parameters:
* queue - Message queue data pointer
* item - Message data pointer
* block_time_ms - Wait time
*
* Returned Value:
* True if success or false if fail
*
****************************************************************************/
static int queue_recv_wrapper(void *queue, void *item,
uint32_t block_time_ms)
{
ssize_t ret;
struct timespec timeout;
unsigned int prio;
struct mq_adpt_s *mq_adpt = (struct mq_adpt_s *)queue;
if (block_time_ms == OSI_FUNCS_TIME_BLOCKING)
{
ret = file_mq_receive(&mq_adpt->mq, (char *)item,
mq_adpt->msgsize, &prio);
if (ret < 0)
{
wlerr("Failed to receive from mqueue error=%d\n", ret);
}
}
else
{
ret = clock_gettime(CLOCK_REALTIME, &timeout);
if (ret < 0)
{
wlerr("Failed to get time\n");
return false;
}
if (block_time_ms)
{
esp_update_time(&timeout, MSEC2TICK(block_time_ms));
}
ret = file_mq_timedreceive(&mq_adpt->mq, (char *)item,
mq_adpt->msgsize, &prio, &timeout);
if (ret < 0)
{
wlerr("Failed to timedreceive from mqueue error=%d\n", ret);
}
}
return ret > 0 ? true : false;
}
/****************************************************************************
* Name: queue_delete_wrapper
*
* Description:
* Delete message queue
*
* Input Parameters:
* queue - Message queue data pointer
*
* Returned Value:
* None
*
****************************************************************************/
static void queue_delete_wrapper(void *queue)
{
struct mq_adpt_s *mq_adpt = (struct mq_adpt_s *)queue;
file_mq_close(&mq_adpt->mq);
file_mq_unlink(mq_adpt->name);
kmm_free(mq_adpt);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: esp32c3_bt_controller_init
*
* Description:
* Init BT controller.
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
int esp32c3_bt_controller_init(void)
{
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_config_t *cfg = &bt_cfg;
#ifdef CONFIG_PM
bool select_src_ret;
bool set_div_ret;
#endif
if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE)
{
wlerr("Invalid controller status");
return -1;
}
cfg->controller_task_stack_size = CONFIG_ESP32C3_BLE_TASK_STACK_SIZE;
cfg->controller_task_prio = CONFIG_ESP32C3_BLE_TASK_PRIORITY;
cfg->controller_task_run_cpu = 0;
cfg->ble_max_act = 10;
cfg->sleep_mode = 0;
cfg->coex_phy_coded_tx_rx_time_limit = 0;
cfg->bluetooth_mode = 1;
cfg->sleep_clock = 0;
cfg->ble_st_acl_tx_buf_nb = 0;
cfg->ble_hw_cca_check = 0;
cfg->ble_adv_dup_filt_max = 30;
cfg->ce_len_type = 0;
cfg->hci_tl_type = 1;
cfg->hci_tl_funcs = NULL;
cfg->txant_dft = 0;
cfg->rxant_dft = 0;
cfg->txpwr_dft = 7;
cfg->cfg_mask = 1;
cfg->scan_duplicate_mode = 0;
cfg->scan_duplicate_type = 0;
cfg->normal_adv_size = 20;
cfg->mesh_adv_size = 0;
btdm_controller_mem_init();
if (btdm_osi_funcs_register(&g_osi_funcs) != 0)
{
return -EINVAL;
}
wlinfo("BT controller compile version [%s]\n",
btdm_controller_get_compile_version());
#ifdef CONFIG_PM
/* init low-power control resources */
memset(&g_lp_cntl, 0x0, sizeof(btdm_lpcntl_t));
memset(&g_lp_stat, 0x0, sizeof(btdm_lpstat_t));
g_wakeup_req_sem = NULL;
g_btdm_slp_tmr = NULL;
/* configure and initialize resources */
g_lp_cntl.enable = (cfg->sleep_mode == ESP_BT_SLEEP_MODE_1) ? true : false;
if (g_lp_cntl.enable)
{
g_lp_cntl.wakeup_timer_required = true;
g_wakeup_req_sem = semphr_create_wrapper(1, 0);
if (g_wakeup_req_sem == NULL)
{
goto error;
}
btdm_vnd_offload_task_register(BTDM_VND_OL_SIG_WAKEUP_TMR,
btdm_sleep_exit_phase0);
}
if (g_lp_cntl.wakeup_timer_required)
{
esp_timer_create_args_t create_args =
{
.callback = btdm_slp_tmr_callback,
.arg = NULL,
.name = "btSlp",
};
if ((err = esp_timer_create(&create_args, &g_btdm_slp_tmr)) != ESP_OK)
{
goto error;
}
}
g_btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
g_btdm_lpcycle_us = 2 << (g_btdm_lpcycle_us_frac);
if (esp32c3_rtc_clk_slow_freq_get() == RTC_SLOW_FREQ_32K_XTAL)
{
g_lp_cntl.lpclk_sel = BTDM_LPCLK_SEL_XTAL32K;
}
else
{
wlwarn("32.768kHz XTAL not detected");
g_lp_cntl.lpclk_sel = BTDM_LPCLK_SEL_XTAL;
}
if (g_lp_cntl.lpclk_sel == BTDM_LPCLK_SEL_XTAL)
{
select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_XTAL);
set_div_ret = btdm_lpclk_set_div(esp32c3_rtc_clk_xtal_freq_get() * 2);
DEBUGASSERT(select_src_ret && set_div_ret);
g_btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
g_btdm_lpcycle_us = 2 << (g_btdm_lpcycle_us_frac);
}
else if (g_lp_cntl.lpclk_sel == BTDM_LPCLK_SEL_XTAL32K)
{
select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_XTAL32K);
set_div_ret = btdm_lpclk_set_div(0);
DEBUGASSERT(select_src_ret && set_div_ret);
g_btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
g_btdm_lpcycle_us = (RTC_CLK_CAL_FRACT > 15) ?
(1000000 << (RTC_CLK_CAL_FRACT - 15)) :
(1000000 >> (15 - RTC_CLK_CAL_FRACT));
DEBUGASSERT(g_btdm_lpcycle_us != 0);
}
else if (g_lp_cntl.lpclk_sel == BTDM_LPCLK_SEL_RTC_SLOW)
{
select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_RTC_SLOW);
set_div_ret = btdm_lpclk_set_div(0);
DEBUGASSERT(select_src_ret && set_div_ret);
g_btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
g_btdm_lpcycle_us = esp_clk_slowclk_cal_get_wrapper();
}
else
{
goto error;
}
g_lp_stat.pm_lock_released = true;
#endif
#ifdef CONFIG_ESP32C3_WIFI_BT_COEXIST
coex_init();
#endif
modifyreg32(SYSTEM_WIFI_CLK_EN_REG, 0, UINT32_MAX);
bt_phy_enable();
g_lp_stat.phy_enabled = true;
if (btdm_controller_init(cfg) != 0)
{
bt_phy_disable();
g_lp_stat.phy_enabled = false;
return -EIO;
}
btdm_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
#ifdef CONFIG_ESP32C3_SPIFLASH
if (esp32c3_wl_init() < 0)
{
return -EIO;
}
#endif
return 0;
#ifdef CONFIG_PM
error:
if (g_lp_stat.phy_enabled)
{
bt_phy_disable();
g_lp_stat.phy_enabled = false;
}
g_lp_stat.pm_lock_released = false;
if (g_lp_cntl.wakeup_timer_required && g_btdm_slp_tmr != NULL)
{
esp_timer_delete(g_btdm_slp_tmr);
g_btdm_slp_tmr = NULL;
}
if (g_lp_cntl.enable)
{
btdm_vnd_offload_task_deregister(BTDM_VND_OL_SIG_WAKEUP_TMR);
if (g_wakeup_req_sem != NULL)
{
semphr_delete_wrapper(g_wakeup_req_sem);
g_wakeup_req_sem = NULL;
}
}
return ENOMEM;
#endif
}
/****************************************************************************
* Name: esp32c3_bt_controller_deinit
*
* Description:
* Deinit BT controller.
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
int esp32c3_bt_controller_deinit(void)
{
if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_INITED)
{
return -1;
}
btdm_controller_deinit();
if (g_lp_stat.phy_enabled)
{
bt_phy_disable();
g_lp_stat.phy_enabled = false;
}
else
{
DEBUGASSERT(0);
}
#ifdef CONFIG_PM
/* deinit low power control resources */
g_lp_stat.pm_lock_released = false;
if (g_lp_cntl.wakeup_timer_required)
{
if (g_lp_stat.wakeup_timer_started)
{
esp_timer_stop(g_btdm_slp_tmr);
}
g_lp_stat.wakeup_timer_started = false;
esp_timer_delete(g_btdm_slp_tmr);
g_btdm_slp_tmr = NULL;
}
if (g_lp_cntl.enable)
{
btdm_vnd_offload_task_deregister(BTDM_VND_OL_SIG_WAKEUP_TMR);
semphr_delete_wrapper(g_wakeup_req_sem);
g_wakeup_req_sem = NULL;
}
#endif
btdm_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
g_btdm_lpcycle_us = 0;
return 0;
}
/****************************************************************************
* Name: esp32c3_bt_controller_disable
*
* Description:
* disable BT controller.
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
int esp32c3_bt_controller_disable(void)
{
if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED)
{
return -1;
}
while (!btdm_power_state_active())
{
usleep(1000); /* wait */
}
btdm_controller_disable();
#ifdef CONFIG_ESP32C3_WIFI_BT_COEXIST
coex_disable();
#endif
btdm_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
#ifdef CONFIG_PM
/* disable low power mode */
if (g_lp_stat.pm_lock_released == false)
{
esp32c3_pm_lockrelease();
g_lp_stat.pm_lock_released = true;
}
else
{
DEBUGASSERT(0);
}
#endif
return 0;
}
/****************************************************************************
* Name: esp32c3_bt_controller_enable
*
* Description:
* Enable BT controller.
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
int esp32c3_bt_controller_enable(esp_bt_mode_t mode)
{
int ret = 0;
if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_INITED)
{
return -1;
}
if (mode != btdm_controller_get_mode())
{
wlerr("invalid mode %d, controller support mode is %d",
mode, btdm_controller_get_mode());
return -1;
}
#ifdef CONFIG_ESP32C3_WIFI_BT_COEXIST
coex_enable();
#endif
#ifdef CONFIG_PM
/* enable low power mode */
esp32c3_pm_lockacquire();
g_lp_stat.pm_lock_released = false;
if (g_lp_cntl.enable)
{
btdm_controller_enable_sleep(true);
}
#endif
if (g_lp_cntl.enable)
{
btdm_controller_enable_sleep(true);
}
if (btdm_controller_enable(mode) != 0)
{
ret = -1;
goto error;
}
btdm_controller_status = ESP_BT_CONTROLLER_STATUS_ENABLED;
return ret;
error:
/* disable low power mode */
btdm_controller_enable_sleep(false);
#ifdef CONFIG_PM
if (g_lp_stat.pm_lock_released == false)
{
esp32c3_pm_lockrelease();
g_lp_stat.pm_lock_released = true;
}
#endif
return ret;
}
esp_bt_controller_status_t esp32c3_bt_controller_get_status(void)
{
return btdm_controller_status;
}
/****************************************************************************
* Name: esp32c3_vhci_host_check_send_available
*
* Description:
* Check if the host can send packet to controller or not.
*
* Input Parameters:
* None
*
* Returned Value:
* bool - true or false
*
****************************************************************************/
bool esp32c3_vhci_host_check_send_available(void)
{
if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED)
{
return false;
}
return api_vhci_host_check_send_available();
}
/****************************************************************************
* Name: esp32c3_vhci_host_send_packet
*
* Description:
* host send packet to controller.
* Input Parameters:
* data - the packet point
* len - the packet length
*
* Returned Value:
* None
*
****************************************************************************/
void esp32c3_vhci_host_send_packet(uint8_t *data, uint16_t len)
{
if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED)
{
return;
}
api_vhci_host_send_packet(data, len);
}
/****************************************************************************
* Name: esp32c3_vhci_register_callback
*
* Description:
* register the vhci reference callback.
* Input Parameters:
* callback - struct defined by vhci_host_callback structure.
*
* Returned Value:
* status - success or fail
*
****************************************************************************/
int esp32c3_vhci_register_callback(const esp_vhci_host_callback_t *callback)
{
int ret = -1;
if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED)
{
return ret;
}
ret = api_vhci_host_register_callback(
(const vhci_host_callback_t *)callback) == 0 ? 0 : -1;
return ret;
}
|
ryanoabel/incubator-nuttx | arch/risc-v/src/esp32c3/esp32c3_wireless.h | /****************************************************************************
* arch/risc-v/src/esp32c3/esp32c3_wireless.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
#ifndef __ARCH_RISCV_SRC_ESP32C3_ESP32C3_WIRELESS_H
#define __ARCH_RISCV_SRC_ESP32C3_ESP32C3_WIRELESS_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdbool.h>
#include <stdint.h>
#include <semaphore.h>
#include <nuttx/list.h>
#ifndef __ASSEMBLY__
#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif
/****************************************************************************
* Pre-processor Macros
****************************************************************************/
/* Semaphore Cache Data */
struct esp32c3_wl_semcache_s
{
struct list_node node;
sem_t *sem;
uint32_t count;
};
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
/****************************************************************************
* Name: esp32c3_phy_enable
*
* Description:
* Initialize PHY hardware
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void esp32c3_phy_enable(void);
/****************************************************************************
* Name: esp32c3_phy_disable
*
* Description:
* Deinitialize PHY hardware
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void esp32c3_phy_disable(void);
/****************************************************************************
* Name: esp32c3_wl_init_semcache
*
* Description:
* Initialize semaphore cache.
*
* Parameters:
* sc - Semaphore cache data pointer
* sem - Semaphore data pointer
*
* Returned Value:
* None.
*
****************************************************************************/
void esp32c3_wl_init_semcache(struct esp32c3_wl_semcache_s *sc,
sem_t *sem);
/****************************************************************************
* Name: esp32c3_wl_post_semcache
*
* Description:
* Store posting semaphore action into semaphore cache.
*
* Parameters:
* sc - Semaphore cache data pointer
*
* Returned Value:
* None.
*
****************************************************************************/
void esp32c3_wl_post_semcache(struct esp32c3_wl_semcache_s *sc);
/****************************************************************************
* Name: esp32c3_wl_init
*
* Description:
* Initialize ESP32-C3 wireless common components for both BT and Wi-Fi.
*
* Parameters:
* None
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
int esp32c3_wl_init(void);
/****************************************************************************
* Name: esp32c3_wl_deinit
*
* Description:
* De-initialize ESP32-C3 wireless common components.
*
* Parameters:
* None
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
int esp32c3_wl_deinit(void);
#ifdef __cplusplus
}
#endif
#undef EXTERN
#endif /* __ASSEMBLY__ */
#endif /* __ARCH_RISCV_SRC_ESP32C3_ESP32C3_WIRELESS_H */
|
ryanoabel/incubator-nuttx | arch/risc-v/src/esp32c3/esp32c3_wireless.c | <filename>arch/risc-v/src/esp32c3/esp32c3_wireless.c<gh_stars>0
/****************************************************************************
* arch/risc-v/src/esp32c3/esp32c3_wireless.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/kmalloc.h>
#include <semaphore.h>
#include <debug.h>
#include "riscv_internal.h"
#include "hardware/esp32c3_system.h"
#include "hardware/esp32c3_soc.h"
#include "hardware/esp32c3_syscon.h"
#include "esp32c3.h"
#include "esp32c3_irq.h"
#include "esp32c3_attr.h"
#include "esp32c3_wireless.h"
#include "espidf_wifi.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Software Interrupt */
#define SWI_IRQ ESP32C3_IRQ_FROM_CPU_INT0
#define SWI_PERIPH ESP32C3_PERIPH_FROM_CPU_INT0
/****************************************************************************
* Private Types
****************************************************************************/
/* ESP32-C3 Wireless Private Data */
struct esp32c3_wl_priv_s
{
volatile int ref; /* Reference count */
int cpuint; /* CPU interrupt assigned to SWI */
struct list_node sc_list; /* Semaphore cache list */
};
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
static inline void phy_digital_regs_store(void);
static inline void phy_digital_regs_load(void);
static void esp32c3_phy_enable_clock(void);
static void esp32c3_phy_disable_clock(void);
/****************************************************************************
* Extern Functions declaration
****************************************************************************/
#ifdef CONFIG_ESP32C3_BLE
extern void coex_pti_v2(void);
#endif
/****************************************************************************
* Private Data
****************************************************************************/
/* Wi-Fi sleep private data */
static uint32_t g_phy_clk_en_cnt;
/* Reference count of enabling PHY */
static uint8_t g_phy_access_ref;
/* Memory to store PHY digital registers */
static uint32_t *g_phy_digital_regs_mem = NULL;
/* Indicate PHY is calibrated or not */
static bool g_is_phy_calibrated = false;
static struct esp32c3_wl_priv_s g_esp32c3_wl_priv;
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: phy_digital_regs_store
*
* Description:
* Store PHY digital registers.
*
****************************************************************************/
static inline void phy_digital_regs_store(void)
{
if (g_phy_digital_regs_mem == NULL)
{
g_phy_digital_regs_mem = (uint32_t *)
kmm_malloc(SOC_PHY_DIG_REGS_MEM_SIZE);
}
DEBUGASSERT(g_phy_digital_regs_mem != NULL);
phy_dig_reg_backup(true, g_phy_digital_regs_mem);
}
/****************************************************************************
* Name: phy_digital_regs_load
*
* Description:
* Load PHY digital registers.
*
****************************************************************************/
static inline void phy_digital_regs_load(void)
{
if (g_phy_digital_regs_mem != NULL)
{
phy_dig_reg_backup(false, g_phy_digital_regs_mem);
}
}
/****************************************************************************
* Name: esp32c3_phy_enable_clock
*
* Description:
* Enable PHY hardware clock
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void esp32c3_phy_enable_clock(void)
{
irqstate_t flags;
flags = enter_critical_section();
if (g_phy_clk_en_cnt == 0)
{
modifyreg32(SYSTEM_WIFI_CLK_EN_REG, 0,
SYSTEM_WIFI_CLK_WIFI_BT_COMMON_M);
}
g_phy_clk_en_cnt++;
leave_critical_section(flags);
}
/****************************************************************************
* Name: esp32c3_phy_disable_clock
*
* Description:
* Disable PHY hardware clock
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
static void esp32c3_phy_disable_clock(void)
{
irqstate_t flags;
flags = enter_critical_section();
if (g_phy_clk_en_cnt)
{
g_phy_clk_en_cnt--;
if (!g_phy_clk_en_cnt)
{
modifyreg32(SYSTEM_WIFI_CLK_EN_REG,
SYSTEM_WIFI_CLK_WIFI_BT_COMMON_M,
0);
}
}
leave_critical_section(flags);
}
/****************************************************************************
* Name: esp32c3_wl_swi_irq
*
* Description:
* Wireless software interrupt callback function.
*
* Parameters:
* cpuint - CPU interrupt index
* context - Context data from the ISR
* arg - NULL
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
static int esp32c3_wl_swi_irq(int irq, void *context, FAR void *arg)
{
int i;
int ret;
struct esp32c3_wl_semcache_s *sc;
struct esp32c3_wl_semcache_s *tmp;
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
putreg32(0, SYSTEM_CPU_INTR_FROM_CPU_0_REG);
list_for_every_entry_safe(&priv->sc_list, sc, tmp,
struct esp32c3_wl_semcache_s, node)
{
for (i = 0; i < sc->count; i++)
{
ret = nxsem_post(sc->sem);
if (ret < 0)
{
wlerr("ERROR: Failed to post sem ret=%d\n", ret);
}
}
sc->count = 0;
list_delete(&sc->node);
}
return OK;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: esp32c3_phy_disable
*
* Description:
* Deinitialize PHY hardware
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void esp32c3_phy_disable(void)
{
irqstate_t flags;
flags = enter_critical_section();
g_phy_access_ref--;
if (g_phy_access_ref == 0)
{
/* Store PHY digital register. */
phy_digital_regs_store();
/* Disable PHY and RF. */
phy_close_rf();
phy_xpd_tsens();
/* Disable Wi-Fi/BT common peripheral clock.
* Do not disable clock for hardware RNG.
*/
esp32c3_phy_disable_clock();
}
leave_critical_section(flags);
}
/****************************************************************************
* Name: esp32c3_phy_enable
*
* Description:
* Initialize PHY hardware
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void esp32c3_phy_enable(void)
{
static bool debug = false;
irqstate_t flags;
esp_phy_calibration_data_t *cal_data;
char *phy_version = get_phy_version_str();
if (debug == false)
{
debug = true;
wlinfo("phy_version %s\n", phy_version);
}
cal_data = kmm_zalloc(sizeof(esp_phy_calibration_data_t));
if (!cal_data)
{
wlerr("ERROR: Failed to kmm_zalloc");
DEBUGASSERT(0);
}
flags = enter_critical_section();
if (g_phy_access_ref == 0)
{
esp32c3_phy_enable_clock();
if (g_is_phy_calibrated == false)
{
register_chipv7_phy(&phy_init_data, cal_data, PHY_RF_CAL_FULL);
g_is_phy_calibrated = true;
}
else
{
phy_wakeup_init();
phy_digital_regs_load();
}
#ifdef CONFIG_ESP32C3_BLE
coex_pti_v2();
#endif
}
g_phy_access_ref++;
leave_critical_section(flags);
kmm_free(cal_data);
}
/****************************************************************************
* Name: esp32c3_wl_init_semcache
*
* Description:
* Initialize semaphore cache.
*
* Parameters:
* sc - Semaphore cache data pointer
* sem - Semaphore data pointer
*
* Returned Value:
* None.
*
****************************************************************************/
void esp32c3_wl_init_semcache(struct esp32c3_wl_semcache_s *sc,
sem_t *sem)
{
sc->sem = sem;
sc->count = 0;
list_initialize(&sc->node);
}
/****************************************************************************
* Name: esp32c3_wl_post_semcache
*
* Description:
* Store posting semaphore action into semaphore cache.
*
* Parameters:
* sc - Semaphore cache data pointer
*
* Returned Value:
* None.
*
****************************************************************************/
void IRAM_ATTR esp32c3_wl_post_semcache(
struct esp32c3_wl_semcache_s *sc)
{
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
if (!sc->count)
{
list_add_tail(&priv->sc_list, &sc->node);
}
sc->count++;
putreg32(SYSTEM_CPU_INTR_FROM_CPU_0_M, SYSTEM_CPU_INTR_FROM_CPU_0_REG);
}
/****************************************************************************
* Name: esp32c3_wl_init
*
* Description:
* Initialize ESP32-C3 wireless common components for both BT and Wi-Fi.
*
* Parameters:
* None
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
int esp32c3_wl_init(void)
{
int ret;
irqstate_t flags;
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
flags = enter_critical_section();
if (priv->ref != 0)
{
priv->ref++;
leave_critical_section(flags);
return OK;
}
priv->cpuint = esp32c3_request_irq(SWI_PERIPH,
ESP32C3_INT_PRIO_DEF,
ESP32C3_INT_LEVEL);
ret = irq_attach(SWI_IRQ, esp32c3_wl_swi_irq, NULL);
if (ret < 0)
{
esp32c3_free_cpuint(SWI_PERIPH);
leave_critical_section(flags);
wlerr("ERROR: Failed to attach IRQ ret=%d\n", ret);
return ret;
}
list_initialize(&priv->sc_list);
up_enable_irq(priv->cpuint);
priv->ref++;
leave_critical_section(flags);
return OK;
}
/****************************************************************************
* Name: esp32c3_wl_deinit
*
* Description:
* De-initialize ESP32-C3 wireless common components.
*
* Parameters:
* None
*
* Returned Value:
* Zero (OK) is returned on success. A negated errno value is returned on
* failure.
*
****************************************************************************/
int esp32c3_wl_deinit(void)
{
irqstate_t flags;
struct esp32c3_wl_priv_s *priv = &g_esp32c3_wl_priv;
flags = enter_critical_section();
if (priv->ref == 0)
{
leave_critical_section(flags);
return OK;
}
up_disable_irq(priv->cpuint);
irq_detach(SWI_IRQ);
esp32c3_free_cpuint(SWI_PERIPH);
priv->ref--;
leave_critical_section(flags);
return OK;
}
|
ryanoabel/incubator-nuttx | boards/arm/stm32/nucleo-f4x1re/src/stm32_bringup.c | <filename>boards/arm/stm32/nucleo-f4x1re/src/stm32_bringup.c
/****************************************************************************
* boards/arm/stm32/nucleo-f4x1re/src/stm32_bringup.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdio.h>
#include <syslog.h>
#include <errno.h>
#include <nuttx/arch.h>
#include <nuttx/sdio.h>
#include <nuttx/mmcsd.h>
#include <stm32.h>
#include <stm32_uart.h>
#include <arch/board/board.h>
#ifdef CONFIG_USERLED
# include <nuttx/leds/userled.h>
#endif
#include "nucleo-f4x1re.h"
#include <nuttx/board.h>
#ifdef CONFIG_SENSORS_QENCODER
#include "board_qencoder.h"
#endif
#undef HAVE_LEDS
#if !defined(CONFIG_ARCH_LEDS) && defined(CONFIG_USERLED_LOWER)
# define HAVE_LEDS 1
#endif
#ifdef CONFIG_EXAMPLES_LEDS_DEVPATH
# define LED_DRIVER_PATH CONFIG_EXAMPLES_LEDS_DEVPATH
#else
# define LED_DRIVER_PATH "/dev/userleds"
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: stm32_bringup
*
* Description:
* Perform architecture-specific initialization
*
* CONFIG_BOARD_LATE_INITIALIZE=y :
* Called from board_late_initialize().
*
* CONFIG_BOARD_LATE_INITIALIZE=n && CONFIG_BOARDCTL=y :
* Called from the NSH library
*
****************************************************************************/
int stm32_bringup(void)
{
int ret = OK;
#ifdef HAVE_LEDS
/* Register the LED driver */
ret = userled_lower_initialize(LED_DRIVER_PATH);
if (ret < 0)
{
syslog(LOG_ERR, "ERROR: userled_lower_initialize() failed: %d\n", ret);
return ret;
}
#endif
/* Configure SPI-based devices */
#ifdef CONFIG_STM32_SPI1
/* Get the SPI port */
struct spi_dev_s *spi;
spi = stm32_spibus_initialize(1);
if (!spi)
{
syslog(LOG_ERR, "ERROR: Failed to initialize SPI port 1\n");
return -ENODEV;
}
#ifdef CONFIG_CAN_MCP2515
#ifdef CONFIG_STM32_SPI1
stm32_configgpio(GPIO_MCP2515_CS); /* MEMS chip select */
#endif
/* Configure and initialize the MCP2515 CAN device */
ret = stm32_mcp2515initialize("/dev/can0");
if (ret < 0)
{
syslog(LOG_ERR, "ERROR: stm32_mcp2515initialize() failed: %d\n", ret);
}
#endif
#endif
#ifdef HAVE_MMCSD
/* First, get an instance of the SDIO interface */
g_sdio = sdio_initialize(CONFIG_NSH_MMCSDSLOTNO);
if (!g_sdio)
{
syslog(LOG_ERR, "ERROR: Failed to initialize SDIO slot %d\n",
CONFIG_NSH_MMCSDSLOTNO);
return -ENODEV;
}
/* Now bind the SDIO interface to the MMC/SD driver */
ret = mmcsd_slotinitialize(CONFIG_NSH_MMCSDMINOR, g_sdio);
if (ret != OK)
{
syslog(LOG_ERR,
"ERROR: Failed to bind SDIO to the MMC/SD driver: %d\n",
ret);
return ret;
}
/* Then let's guess and say that there is a card in the slot. There is no
* card detect GPIO.
*/
sdio_mediachange(g_sdio, true);
syslog(LOG_INFO, "[boot] Initialized SDIO\n");
#endif
#ifdef CONFIG_ADC
/* Initialize ADC and register the ADC driver. */
ret = stm32_adc_setup();
if (ret < 0)
{
syslog(LOG_ERR, "ERROR: stm32_adc_setup failed: %d\n", ret);
}
#endif
#ifdef CONFIG_SENSORS_QENCODER
/* Initialize and register the qencoder driver */
ret = board_qencoder_initialize(0, CONFIG_NUCLEO_F401RE_QETIMER);
if (ret != OK)
{
syslog(LOG_ERR,
"ERROR: Failed to register the qencoder: %d\n",
ret);
return ret;
}
#endif
#ifdef CONFIG_INPUT_AJOYSTICK
/* Initialize and register the joystick driver */
ret = board_ajoy_initialize();
if (ret != OK)
{
syslog(LOG_ERR,
"ERROR: Failed to register the joystick driver: %d\n",
ret);
return ret;
}
#endif
return ret;
}
|
loxai/rotaryGames | aim.bmp.h | #ifndef _aim_bmp
#define _aim_bmp
#define ALPHA_aim_bmp 0x00ff00U
static int maxColors_aim_bmp=256;
static int width_aim_bmp=8;
static int height_aim_bmp=8;
static constexpr byte palette_aim_bmp[] = {0,255,0,131,132,136,126,127,131,127,128,132,129,130,134,130,131,135,131,130,135,126,125,130,130,6,31,125,126,130,128,127,132,130,131,136,128,129,133};
static constexpr byte image_aim_bmp[] = {0,0,1,2,3,4,0,0,0,2,0,0,0,0,5,0,6,0,0,0,0,0,0,7,3,0,0,8,8,0,0,9,3,0,0,8,8,0,0,5,10,0,0,0,0,0,0,10,0,11,0,0,0,0,2,0,0,0,4,12,3,1,0,0};
#endif
|
loxai/rotaryGames | bullet.bmp.h | #ifndef _bullet_bmp
#define _bullet_bmp
#define ALPHA_bullet_bmp 0x00ff00U
static int maxColors_bullet_bmp=256;
static int width_bullet_bmp=3;
static int height_bullet_bmp=3;
static constexpr byte palette_bullet_bmp[] = {0,255,0,130,6,31,255,203,89};
static constexpr byte image_bullet_bmp[] = {0,1,0,1,2,1,0,1,0};
#endif
|
x0806485/ZJCFoundation | ZJCFoundationDemo/ViewController.h | <reponame>x0806485/ZJCFoundation
//
// ViewController.h
// ZJCFoundationDemo
//
// Created by baihemiyu001 on 2017/2/24.
// Copyright © 2017年 zjc. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
KOREAN139/simulator | Assets/Plugins/VideoCapture/Source/VideoCapture.c | /**
* Copyright (c) 2020 LG Electronics, Inc.
*
* This software contains code licensed as described in LICENSE.
*
*/
#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d11.h>
#include <synchapi.h>
#include "IUnityGraphics.h"
#include "IUnityGraphicsD3D11.h"
#include "nvEncodeAPI.h"
#include <intrin.h>
#include <stdarg.h>
#include <stdint.h>
#include "VideoCaptureFlip.cs.h"
static IUnityInterfaces* UnityInterfaces;
static IUnityGraphics* UnityGraphics;
static LARGE_INTEGER Frequency;
static ID3D11Device* Device;
static ID3D11DeviceContext* Context;
static ID3D11ComputeShader* FlipShader;
static SRWLOCK SrwLock;
static HMODULE NvEncodeModule;
static NV_ENCODE_API_FUNCTION_LIST NvEncodeApi;
typedef void VideoCapture_Log(const char* message);
static VideoCapture_Log* LogProc;
static char PathToFFMPEG[MAX_PATH];
typedef struct
{
void* encoder;
ID3D11UnorderedAccessView* uaView;
ID3D11ShaderResourceView* srView;
void* input;
void* output;
uint32_t width;
uint32_t height;
uint64_t timestamp;
uint32_t frame;
uint32_t framerate;
LARGE_INTEGER previous;
HANDLE process;
HANDLE write;
} VideoCapture;
static VideoCapture Captures[2];
static void Log(const char* msg, ...)
{
char buffer[1024];
va_list args;
va_start(args, msg);
wvsprintfA(buffer, msg, args);
va_end(args);
if (LogProc == NULL)
{
OutputDebugStringA(buffer);
OutputDebugStringA("\n");
}
else
{
LogProc(buffer);
}
}
UNITY_INTERFACE_EXPORT int VideoCapture_Init(const char* ffmpeg, VideoCapture_Log* logProc)
{
wsprintfA(PathToFFMPEG, "%s", ffmpeg);
LogProc = logProc;
if (NvEncodeModule == NULL)
{
InitializeSRWLock(&SrwLock);
NvEncodeModule = LoadLibraryA("nvEncodeAPI64.dll");
if (NvEncodeModule == NULL)
{
Log("NVENC library file is not found. Please ensure NV driver is installed");
return -1;
}
typedef NVENCSTATUS NVENCAPI NvEncodeAPIGetMaxSupportedVersionProc(uint32_t * version);
NvEncodeAPIGetMaxSupportedVersionProc* NvEncodeAPIGetMaxSupportedVersion = (NvEncodeAPIGetMaxSupportedVersionProc*)GetProcAddress(NvEncodeModule, "NvEncodeAPIGetMaxSupportedVersion");
if (NvEncodeAPIGetMaxSupportedVersion == NULL)
{
Log("NvEncodeAPIGetMaxSupportedVersion entry point not. Please upgrade Nvidia driver");
FreeModule(NvEncodeModule);
NvEncodeModule = NULL;
return -1;
}
typedef NVENCSTATUS NVENCAPI NvEncodeAPICreateInstanceProc(NV_ENCODE_API_FUNCTION_LIST * list);
NvEncodeAPICreateInstanceProc* NvEncodeAPICreateInstance = (NvEncodeAPICreateInstanceProc*)GetProcAddress(NvEncodeModule, "NvEncodeAPICreateInstance");
if (NvEncodeAPICreateInstance == NULL)
{
Log("NvEncodeAPICreateInstance entry point not. Please upgrade Nvidia driver");
FreeModule(NvEncodeModule);
NvEncodeModule = NULL;
return -1;
}
uint32_t version = 0;
NVENCSTATUS err = NvEncodeAPIGetMaxSupportedVersion(&version);
if (err != NV_ENC_SUCCESS)
{
Log("NvEncodeAPIGetMaxSupportedVersion failed");
FreeModule(NvEncodeModule);
NvEncodeModule = NULL;
return -1;
}
uint32_t currentVersion = (NVENCAPI_MAJOR_VERSION << 4) | NVENCAPI_MINOR_VERSION;
if (currentVersion > version)
{
Log("Current driver version does not support this NvEncodeAPI version, please upgrade driver");
FreeModule(NvEncodeModule);
NvEncodeModule = NULL;
return -1;
}
NvEncodeApi.version = NV_ENCODE_API_FUNCTION_LIST_VER;
err = NvEncodeAPICreateInstance(&NvEncodeApi);
if (err != NV_ENC_SUCCESS)
{
Log("NvEncodeAPICreateInstance failed");
FreeModule(NvEncodeModule);
NvEncodeModule = NULL;
return -1;
}
}
return 0;
}
UNITY_INTERFACE_EXPORT int VideoCapture_Start(int width, int height, int framerate, int bitrate, int maxBitrate, int quality, int streaming, const char* destination)
{
int id;
VideoCapture* capture = NULL;
// find free hw encoder
for (id = 0; id < sizeof(Captures)/sizeof(*Captures); id++)
{
if (Captures[id].encoder == NULL)
{
capture = Captures + id;
break;
}
}
if (capture == NULL)
{
return -1;
}
void* encoder = NULL;
ID3D11Texture2D* texture = NULL;
ID3D11UnorderedAccessView* uaView = NULL;
void* input = 0;
void* output = 0;
HANDLE read = NULL;
HANDLE write = NULL;
HANDLE process = NULL;
NVENCSTATUS err;
HRESULT hr;
BOOL ok;
int result = -1;
// create encoding session
{
NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params =
{
.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER,
.device = Device,
.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX,
.apiVersion = NVENCAPI_VERSION,
};
AcquireSRWLockExclusive(&SrwLock);
err = NvEncodeApi.nvEncOpenEncodeSessionEx(¶ms, &encoder);
ReleaseSRWLockExclusive(&SrwLock);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncOpenEncodeSessionEx failed, error = %u", err);
goto bail;
}
}
// select encoder configuration
{
NV_ENC_PRESET_CONFIG preset =
{
.version = NV_ENC_PRESET_CONFIG_VER,
.presetCfg =
{
.version = NV_ENC_CONFIG_VER,
},
};
GUID encodeGUID = NV_ENC_CODEC_H264_GUID;
GUID presetGUID = streaming ? NV_ENC_PRESET_LOW_LATENCY_HQ_GUID : NV_ENC_PRESET_HQ_GUID;
err = NvEncodeApi.nvEncGetEncodePresetConfig(encoder, encodeGUID, presetGUID, &preset);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncGetEncodePresetConfig failed, error = %u", err);
goto bail;
}
NV_ENC_INITIALIZE_PARAMS params =
{
.version = NV_ENC_INITIALIZE_PARAMS_VER,
.encodeGUID = encodeGUID,
.presetGUID = presetGUID,
.encodeWidth = width,
.encodeHeight = height,
.darWidth = width,
.darHeight = height,
.frameRateNum = framerate,
.frameRateDen = 1,
// .enableEncodeAsync = 1,
.enablePTD = 1,
.encodeConfig = &preset.presetCfg,
};
NV_ENC_CONFIG* config = params.encodeConfig;
config->profileGUID = streaming ? NV_ENC_H264_PROFILE_MAIN_GUID : NV_ENC_H264_PROFILE_HIGH_GUID;
config->gopLength = framerate * 2;
config->frameIntervalP = 1;
config->frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
config->rcParams.rateControlMode = streaming ? NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ : NV_ENC_PARAMS_RC_VBR_HQ;
config->rcParams.averageBitRate = bitrate * 1024; // used for CBR and VBR
config->rcParams.maxBitRate = maxBitrate * 1024; // used for VBR
config->rcParams.targetQuality = quality;
NV_ENC_CONFIG_H264* h264 = &config->encodeCodecConfig.h264Config;
h264->idrPeriod = config->gopLength;
h264->sliceMode = 0;
h264->sliceModeData = 0;
h264->repeatSPSPPS = 1;
h264->outputPictureTimingSEI = 1;
h264->h264VUIParameters.videoSignalTypePresentFlag = 1;
h264->h264VUIParameters.videoFullRangeFlag = 1;
h264->h264VUIParameters.colourDescriptionPresentFlag = 1;
h264->h264VUIParameters.colourMatrix = 1; // BT.709
h264->h264VUIParameters.colourPrimaries = 1; // BT.709
h264->h264VUIParameters.transferCharacteristics = 1; // BT.709
h264->outputBufferingPeriodSEI = streaming ? 1 : 0;
// lookahead
// config->rcParams.lookaheadDepth = 8;
// config->rcParams.enableLookahead = 1;
// temporal AQ
// config->rcParams.enableAQ = psycho_aq;
// config->rcParams.enableTemporalAQ = psycho_aq;
err = NvEncodeApi.nvEncInitializeEncoder(encoder, ¶ms);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncOpenEncodeSessionEx failed, error = %u", err);
goto bail;
}
}
// create texture used as input for encoding
{
D3D11_TEXTURE2D_DESC desc =
{
.Width = width,
.Height = height,
.MipLevels = 1,
.ArraySize = 1,
.Format = DXGI_FORMAT_R8G8B8A8_UNORM,
.SampleDesc = { 1, 0 },
.Usage = D3D11_USAGE_DEFAULT,
.BindFlags = D3D11_BIND_UNORDERED_ACCESS,
};
hr = ID3D11Device_CreateTexture2D(Device, &desc, NULL, &texture);
if (FAILED(hr))
{
Log("ID3D11Device_CreateTexture2D failed, error = 0x%08x", hr);
goto bail;
}
hr = ID3D11Device_CreateUnorderedAccessView(Device, (ID3D11Resource*)texture, NULL, &uaView);
if (FAILED(hr))
{
Log("ID3D11Device_CreateUnorderedAccessView failed, error = 0x%08x", hr);
goto bail;
}
}
// create encoding input resources
{
NV_ENC_REGISTER_RESOURCE reg =
{
.version = NV_ENC_REGISTER_RESOURCE_VER,
.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX,
.width = width,
.height = height,
.subResourceIndex = 0,
.resourceToRegister = texture,
.bufferFormat = NV_ENC_BUFFER_FORMAT_ABGR,
.bufferUsage = NV_ENC_INPUT_IMAGE,
};
err = NvEncodeApi.nvEncRegisterResource(encoder, ®);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncRegisterResource failed, error = %u", err);
goto bail;
}
input = reg.registeredResource;
}
// create encoding output buffer
{
NV_ENC_CREATE_BITSTREAM_BUFFER buffer =
{
.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER,
};
err = NvEncodeApi.nvEncCreateBitstreamBuffer(encoder, &buffer);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncCreateBitstreamBuffer failed, error = %u", err);
goto bail;
}
output = buffer.bitstreamBuffer;
}
// launch ffmpeg.exe process
{
SECURITY_ATTRIBUTES sa =
{
.nLength = sizeof(sa),
.bInheritHandle = TRUE,
};
ok = CreatePipe(&read, &write, &sa, 0);
if (!ok)
{
Log("CreatePipe failed, error = 0x%08x", GetLastError());
goto bail;
}
ok = SetHandleInformation(write, HANDLE_FLAG_INHERIT, 0);
if (!ok)
{
Log("SetHandleInformation failed, error = 0x%08x", GetLastError());
goto bail;
}
const char* format = streaming ? "flv" : "mp4";
const char* re = streaming ? "-re" : "";
char cmdline[1024];
wsprintfA(cmdline, "%s %s -loglevel quiet -i - -c:v copy -y -shortest -f %s \"%s\"",
PathToFFMPEG, re, format, destination);
STARTUPINFOA si =
{
.cb = sizeof(si),
.dwFlags = STARTF_USESTDHANDLES,
.hStdInput = read,
};
PROCESS_INFORMATION pi;
ok = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi); // CREATE_NEW_CONSOLE // CREATE_NO_WINDOW
if (!ok)
{
Log("CreateProcessA failed, error = 0x%08x", GetLastError());
goto bail;
}
CloseHandle(pi.hThread);
process = pi.hProcess;
}
// ready to go!
capture->encoder = encoder;
capture->uaView = uaView;
capture->input = input;
capture->output = output;
capture->width = width;
capture->height = height;
capture->timestamp = 0;
capture->frame = 0;
capture->process = process;
capture->write = write;
capture->framerate = framerate;
capture->previous.QuadPart = 0;
capture->srView = NULL;
write = NULL;
process = NULL;
input = NULL;
output = NULL;
uaView = NULL;
encoder = NULL;
result = id;
bail:
if (read) CloseHandle(read);
if (write) CloseHandle(write);
if (process)
{
TerminateProcess(process, 0);
CloseHandle(process);
}
if (input) NvEncodeApi.nvEncUnregisterResource(encoder, input);
if (output) NvEncodeApi.nvEncDestroyBitstreamBuffer(encoder, output);
if (uaView) ID3D11UnorderedAccessView_Release(uaView);
if (texture) ID3D11Texture2D_Release(texture);
if (encoder) NvEncodeApi.nvEncDestroyEncoder(encoder);
return result;
}
static void VideoCapture_Flush(VideoCapture* capture)
{
NV_ENC_LOCK_BITSTREAM bitstream =
{
.version = NV_ENC_LOCK_BITSTREAM_VER,
.outputBitstream = capture->output,
};
NVENCSTATUS err = NvEncodeApi.nvEncLockBitstream(capture->encoder, &bitstream);
if (err == NV_ENC_SUCCESS)
{
DWORD written;
BOOL ok = WriteFile(capture->write, bitstream.bitstreamBufferPtr, bitstream.bitstreamSizeInBytes, &written, NULL);
if (!ok)
{
Log("WriteFile failed, error = 0x%08x", GetLastError());
}
else if (written != bitstream.bitstreamSizeInBytes)
{
Log("WriteFile wrote only %u bytes (needed to write %u bytes)", written, bitstream.bitstreamSizeInBytes);
}
NvEncodeApi.nvEncUnlockBitstream(capture->encoder, capture->output);
}
else
{
Log("nvEncLockBitstream failed, error = %u", err);
}
}
static void UNITY_INTERFACE_API VideoCapture_Update(int id)
{
VideoCapture* capture = Captures + id;
ID3D11DeviceContext_CSSetShader(Context, FlipShader, NULL, 0);
ID3D11DeviceContext_CSSetShaderResources(Context, 0, 1, &capture->srView);
ID3D11DeviceContext_CSSetUnorderedAccessViews(Context, 0, 1, &capture->uaView, NULL);
ID3D11DeviceContext_Dispatch(Context, (capture->width + 7) / 8, (capture->height + 7) / 8, 1);
NV_ENC_MAP_INPUT_RESOURCE resource =
{
.version = NV_ENC_MAP_INPUT_RESOURCE_VER,
.registeredResource = capture->input,
};
AcquireSRWLockShared(&SrwLock);
NVENCSTATUS err = NvEncodeApi.nvEncMapInputResource(capture->encoder, &resource);
ReleaseSRWLockShared(&SrwLock);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncMapInputResource failed, error = %u", err);
return;
}
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
uint64_t timestamp;
if (capture->previous.QuadPart == 0)
{
timestamp = 0;
}
else
{
uint64_t delta = counter.QuadPart - capture->previous.QuadPart;
timestamp = capture->timestamp + delta * 10 * 1000 * 1000 / Frequency.QuadPart;
}
capture->previous = counter;
NV_ENC_PIC_PARAMS params =
{
.version = NV_ENC_PIC_PARAMS_VER,
.inputWidth = capture->width,
.inputHeight = capture->height,
// .encodePicFlags = 0, // NV_ENC_PIC_FLAG_FORCEINTRA
.frameIdx = capture->frame++,
.inputTimeStamp = timestamp,
.inputDuration = 10 * 1000 * 1000 / capture->framerate,
.inputBuffer = resource.mappedResource,
.outputBitstream = capture->output,
// .completionEvent = event,
.bufferFmt = resource.mappedBufferFmt,
.pictureStruct = NV_ENC_PIC_STRUCT_FRAME,
};
err = NvEncodeApi.nvEncEncodePicture(capture->encoder, ¶ms);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncEncodePicture failed, error = %u", err);
}
err = NvEncodeApi.nvEncUnmapInputResource(capture->encoder, resource.mappedResource);
if (err != NV_ENC_SUCCESS)
{
Log("nvEncUnmapInputResource failed, error = %u", err);
}
VideoCapture_Flush(capture);
}
UNITY_INTERFACE_EXPORT void VideoCapture_Stop(int id)
{
VideoCapture* capture = Captures + id;
{
NV_ENC_PIC_PARAMS params =
{
.version = NV_ENC_PIC_PARAMS_VER,
.inputWidth = capture->width,
.inputHeight = capture->height,
.encodePicFlags = NV_ENC_PIC_FLAG_EOS,
.outputBitstream = capture->output,
// .completionEvent = event,
};
NVENCSTATUS err = NvEncodeApi.nvEncEncodePicture(capture->encoder, ¶ms);
if (err == NV_ENC_SUCCESS)
{
VideoCapture_Flush(capture);
}
else
{
Log("nvEncEncodePicture failed, error = %u", err);
}
}
CloseHandle(capture->write);
WaitForSingleObject(capture->process, INFINITE);
CloseHandle(capture->process);
NvEncodeApi.nvEncDestroyBitstreamBuffer(capture->encoder, capture->output);
NvEncodeApi.nvEncUnregisterResource(capture->encoder, capture->input);
ID3D11UnorderedAccessView_Release(capture->uaView);
NvEncodeApi.nvEncDestroyEncoder(capture->encoder);
if (capture->srView) ID3D11ShaderResourceView_Release(capture->srView);
capture->encoder = NULL;
}
UNITY_INTERFACE_EXPORT void VideoCapture_Reset(int id, ID3D11Texture2D* texture)
{
VideoCapture* capture = Captures + id;
if (capture->srView)
{
ID3D11ShaderResourceView_Release(capture->srView);
capture->srView = NULL;
}
D3D11_SHADER_RESOURCE_VIEW_DESC desc =
{
.Format = DXGI_FORMAT_R8G8B8A8_UNORM,
.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D,
.Texture2D = { 0, 1 },
};
HRESULT hr = ID3D11Device_CreateShaderResourceView(Device, (ID3D11Resource*)texture, &desc, &capture->srView);
if (FAILED(hr))
{
Log("ID3D11Device_CreateShaderResourceView failed, error = 0x%08x", hr);
}
// TODO: maybe force next frame to be I-frame
}
UnityRenderingEvent UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API VideoCapture_GetRenderEventFunc(void)
{
return VideoCapture_Update;
}
static void UNITY_INTERFACE_API OnUnityGraphicsDeviceEvent(UnityGfxDeviceEventType event)
{
if (event == kUnityGfxDeviceEventInitialize)
{
UnityGfxRenderer renderer = UnityGraphics->GetRenderer();
if (renderer == kUnityGfxRendererD3D11)
{
IUnityGraphicsD3D11* d3d11 = UNITY_GET_INTERFACE(UnityInterfaces, IUnityGraphicsD3D11);
Device = d3d11->GetDevice();
ID3D11Device_GetImmediateContext(Device, &Context);
ID3D11Device_CreateComputeShader(Device, g_FlipKernel, sizeof(g_FlipKernel), NULL, &FlipShader);
QueryPerformanceCounter(&Frequency);
}
}
else if (event == kUnityGfxDeviceEventShutdown)
{
ID3D11ComputeShader_Release(FlipShader);
UnityGraphics->UnregisterDeviceEventCallback(OnUnityGraphicsDeviceEvent);
}
}
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* interfaces)
{
UnityInterfaces = interfaces;
UnityGraphics = UNITY_GET_INTERFACE(interfaces, IUnityGraphics);
UnityGraphics->RegisterDeviceEventCallback(OnUnityGraphicsDeviceEvent);
OnUnityGraphicsDeviceEvent(kUnityGfxDeviceEventInitialize);
}
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
{
UnityGraphics->UnregisterDeviceEventCallback(OnUnityGraphicsDeviceEvent);
}
BOOL WINAPI _DllMainCRTStartup(HINSTANCE instance, DWORD reason, LPVOID reserved)
{
if (reason == DLL_PROCESS_ATTACH)
{
DisableThreadLibraryCalls(instance);
}
return TRUE;
}
#pragma function(memset)
void* memset(void* dest, int c, size_t count)
{
__stosb((unsigned char*)dest, (unsigned char)c, count);
return dest;
}
|
vaind/objectbox-c | examples/c-gen/tasklist.obx.h | // Code generated by ObjectBox; DO NOT EDIT.
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "flatcc/flatcc.h"
#include "flatcc/flatcc_builder.h"
#include "objectbox.h"
/// Internal function used in other generated functions to put (write) explicitly typed objects
static obx_id tasklist_obx_h_put_object(OBX_box* box, void* object,
bool (*to_flatbuffer)(flatcc_builder_t*, const void*, void**, size_t*), OBXPutMode mode);
/// Internal function used in other generated functions to get (read) explicitly typed objects
static void* tasklist_obx_h_get_object(OBX_box* box, obx_id id, void* (*from_flatbuffer)(const void*, size_t));
typedef struct Task {
uint64_t id;
char* text;
uint64_t date_created;
uint64_t date_finished;
} Task;
enum Task_ {
Task_ENTITY_ID = 1,
Task_PROP_ID_id = 1,
Task_PROP_ID_text = 2,
Task_PROP_ID_date_created = 3,
Task_PROP_ID_date_finished = 4,
};
/// Write given object to the FlatBufferBuilder
static bool Task_to_flatbuffer(flatcc_builder_t* B, const Task* object, void** out_buffer, size_t* out_size);
/// Read an object from a valid FlatBuffer.
/// If the read object contains vectors or strings, those are allocated on heap and must be freed after use by calling Task_free_pointers().
/// Thus, when calling this function multiple times on the same object, ensure to call Task_free_pointers() before subsequent calls to avoid leaks.
/// @returns true if the object was deserialized successfully or false on (allocation) error in which case any memory
/// allocated by this function will also be freed before returning, allowing you to retry.
static bool Task_from_flatbuffer(const void* data, size_t size, Task* out_object);
/// Read an object from a valid FlatBuffer, allocating the object on heap.
/// The object must be freed after use by calling Task_free();
static Task* Task_new_from_flatbuffer(const void* data, size_t size);
/// Free memory allocated for vector and string properties, setting the freed pointers to NULL.
static void Task_free_pointers(Task* object);
/// Free Task* object pointer and all its property pointers (vectors and strings).
/// Equivalent to calling Task_free_pointers() followed by free();
static void Task_free(Task* object);
static bool Task_to_flatbuffer(flatcc_builder_t* B, const Task* object, void** out_buffer, size_t* out_size) {
assert(B);
assert(object);
assert(out_buffer);
assert(out_size);
flatcc_builder_reset(B);
flatcc_builder_start_buffer(B, 0, 0, 0);
flatcc_builder_ref_t offset_text = !object->text ? 0 : flatcc_builder_create_string_str(B, object->text);
if (flatcc_builder_start_table(B, 4) != 0) return false;
void* p;
flatcc_builder_ref_t* _p;
if (!(p = flatcc_builder_table_add(B, 0, 8, 8))) return false;
flatbuffers_uint64_write_to_pe(p, object->id);
if (offset_text) {
if (!(_p = flatcc_builder_table_add_offset(B, 1))) return false;
*_p = offset_text;
}
if (!(p = flatcc_builder_table_add(B, 2, 8, 8))) return false;
flatbuffers_uint64_write_to_pe(p, object->date_created);
if (!(p = flatcc_builder_table_add(B, 3, 8, 8))) return false;
flatbuffers_uint64_write_to_pe(p, object->date_finished);
flatcc_builder_ref_t ref;
if (!(ref = flatcc_builder_end_table(B))) return false;
if (!flatcc_builder_end_buffer(B, ref)) return false;
return (*out_buffer = flatcc_builder_finalize_aligned_buffer(B, out_size)) != NULL;
}
static bool Task_from_flatbuffer(const void* data, size_t size, Task* out_object) {
assert(data);
assert(size > 0);
assert(out_object);
const uint8_t* table = (const uint8_t*) data + __flatbuffers_uoffset_read_from_pe(data);
assert(table);
const flatbuffers_voffset_t* vt = (const flatbuffers_voffset_t*) (table - __flatbuffers_soffset_read_from_pe(table));
flatbuffers_voffset_t vs = __flatbuffers_voffset_read_from_pe(vt);
// variables reused when reading strings and vectors
flatbuffers_voffset_t offset;
const flatbuffers_uoffset_t* val;
size_t len;
out_object->id = (vs < sizeof(vt[0]) * (0 + 3)) ? 0 : flatbuffers_uint64_read_from_pe(table + __flatbuffers_voffset_read_from_pe(vt + 0 + 2));
if ((offset = (vs < sizeof(vt[0]) * (1 + 3)) ? 0 : __flatbuffers_voffset_read_from_pe(vt + 1 + 2))) {
val = (const flatbuffers_uoffset_t*)(table + offset + sizeof(flatbuffers_uoffset_t) + __flatbuffers_uoffset_read_from_pe(table + offset));
len = (size_t) __flatbuffers_uoffset_read_from_pe(val - 1);
out_object->text = (char*) malloc((len+1) * sizeof(char));
if (out_object->text == NULL) {
Task_free_pointers(out_object);
return false;
}
memcpy((void*)out_object->text, (const void*)val, len+1);
} else {
out_object->text = NULL;
}
out_object->date_created = (vs < sizeof(vt[0]) * (2 + 3)) ? 0 : flatbuffers_uint64_read_from_pe(table + __flatbuffers_voffset_read_from_pe(vt + 2 + 2));
out_object->date_finished = (vs < sizeof(vt[0]) * (3 + 3)) ? 0 : flatbuffers_uint64_read_from_pe(table + __flatbuffers_voffset_read_from_pe(vt + 3 + 2));
return true;
}
static Task* Task_new_from_flatbuffer(const void* data, size_t size) {
Task* object = (Task*) malloc(sizeof(Task));
if (object) {
if (!Task_from_flatbuffer(data, size, object)) {
free(object);
object = NULL;
}
}
return object;
}
static void Task_free_pointers(Task* object) {
if (object == NULL) return;
if (object->text) {
free(object->text);
object->text = NULL;
}
}
static void Task_free(Task* object) {
Task_free_pointers(object);
free(object);
}
/// Insert or update the given object in the database.
/// @param object (in & out) will be updated with a newly inserted ID if the one specified previously was zero. If an ID
/// was already specified (non-zero), it will remain unchanged.
/// @return object ID from the object param (see object param docs) or a zero on error. If a zero was returned, you can
/// check obx_last_error_*() to get the error details. In an unlikely event that those functions return no error
/// code/message, the error occurred in FlatBuffers serialization, e.g. due to memory allocation issues.
static obx_id Task_put(OBX_box* box, Task* object) {
obx_id id = tasklist_obx_h_put_object(box, object,
(bool (*)(flatcc_builder_t*, const void*, void**, size_t*)) Task_to_flatbuffer,
OBXPutMode_PUT);
if (id != 0) {
object->id = id; // update the ID property on new objects for convenience
}
return id;
}
/// Read an object from the database, returning a pointer.
/// @return an object pointer or NULL if an object with the given ID doesn't exist or any other error occurred. You can
/// check obx_last_error_*() if NULL is returned to get the error details. In an unlikely event that those functions
/// return no error code/message, the error occurred in FlatBuffers serialization, e.g. due to memory allocation issues.
/// @note: The returned object must be freed after use by calling Task_free();
static Task* Task_get(OBX_box* box, obx_id id) {
return (Task*) tasklist_obx_h_get_object(box, id, (void* (*) (const void*, size_t)) Task_new_from_flatbuffer);
}
static obx_id tasklist_obx_h_put_object(OBX_box* box, void* object,
bool (*to_flatbuffer)(flatcc_builder_t*, const void*, void**, size_t*), OBXPutMode mode) {
flatcc_builder_t builder;
flatcc_builder_init(&builder);
obx_id id = 0;
size_t size = 0;
void* buffer = NULL;
if (!to_flatbuffer(&builder, object, &buffer, &size)) {
obx_last_error_set(OBX_ERROR_STD_OTHER, 0, "FlatBuffer serialization failed");
} else {
id = obx_box_put_object4(box, buffer, size, mode); // 0 on error
}
flatcc_builder_clear(&builder);
if (buffer) flatcc_builder_aligned_free(buffer);
return id;
}
static void* tasklist_obx_h_get_object(OBX_box* box, obx_id id, void* (*from_flatbuffer)(const void*, size_t)) {
// We need an explicit TX - read data lifecycle is bound to the open TX.
OBX_txn* tx = obx_txn_read(obx_box_store(box));
if (!tx) return NULL;
void* result = NULL;
const void* data;
size_t size;
if (obx_box_get(box, id, &data, &size) == OBX_SUCCESS) {
result = from_flatbuffer(data, size);
if (result == NULL) {
obx_last_error_set(OBX_ERROR_STD_OTHER, 0, "FlatBuffer deserialization failed");
}
}
obx_txn_close(tx);
return result;
}
|
PaesslerAG/webweek-2018 | Sketch/MKRFOX1200_SDS011/sigfox_tools.h | <reponame>PaesslerAG/webweek-2018
#define UINT16_t_MAX 65536
#define INT16_t_MAX UINT16_t_MAX/2
int16_t convertToFloatToInt16(float value, long max, long min) {
float conversionFactor = (float) (INT16_t_MAX) / (float)(max - min);
return (int16_t)(value * conversionFactor);
}
uint16_t convertToFloatToUInt16(float value, long max, long min = 0) {
float conversionFactor = (float) (UINT16_t_MAX) / (float)(max - min);
return (uint16_t)(value * conversionFactor);
}
void printSigfoxInfo() {
String version = SigFox.SigVersion();
String ID = SigFox.ID();
String PAC = SigFox.PAC();
// Display module informations
Serial.println("MKRFox1200 Sigfox first configuration");
Serial.println("SigFox FW version " + version);
Serial.println("ID = " + ID);
Serial.println("PAC = " + PAC);
Serial.println("");
Serial.print("Module temperature: ");
Serial.println(SigFox.internalTemperature());
Serial.println("Register your board on https://backend.sigfox.com/activate with provided ID and PAC");
}
void sendSigfoxMessage() {
// Start the module
SigFox.begin();
// Wait at least 30ms after first configuration (100ms before)
delay(100);
// get the temperature value from the sigfox module
float temperature = SigFox.internalTemperature();
// convert the floating point value to an int16 value
msg.moduleTemperature = convertToFloatToInt16(temperature, 60, -60);
// Clears all pending interrupts
SigFox.status();
delay(1);
SigFox.beginPacket();
SigFox.write((uint8_t*)&msg, 12);
int ret = SigFox.endPacket();
SigFox.end();
if (DEBUG) {
Serial.println("Temperature: " + String(temperature));
if (ret > 0) {
Serial.println("Transmisson failed: " + String(ret));
} else {
Serial.println("Transmission: OKay");
}
}
}
|
streamx3/dr_stein | src/settings.h | <reponame>streamx3/dr_stein<gh_stars>0
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QMutex>
#include <QMutexLocker>
#include <QtGlobal>
#include <QSettings>
#include <QFile>
#ifndef Q_OS_WIN32
#include <unistd.h> // to use config in user's home folder
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
#include <string>
#endif
class Settings{
public:
Settings();
~Settings();
void lock();
void unlock();
QString getDiskName();
bool setDiskName(QString disk_name);
QString getImageName();
bool setImageName(QString image_name);
QString getImageMD5();
bool setImageMD5(QString md5);
void readConfigFile();
void writeConfigFile();
void setStringIfExists(QString option, QString *value);
private:
// For internal logic
QMutex m_qmutex;
QFile m_conf_file;
QSettings *mp_qsettings;
QVariant m_default_qvariant;
QString m_disk_name;
QString m_image_name;
QString m_image_md5;
bool m_db_connected;
bool m_remember_password;
/// SQL variables
QString m_db_address;
QString m_db_username;
QString m_db_password;
QString m_db_dbname;
QString m_db_tablename;
//QString m_db_table_prefix;
/// SQLite variables
QString m_db_filename;
};
#endif // SETTINGS_H
|
streamx3/dr_stein | src/mainwindow.h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTime>
#include "settings.h"
enum E_ACT{
E_ACT_UNKNOWN = 0,
E_ACT_RESTORE,
E_ACT_CLONE
};
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void push2browser(QString msg);
void update_input_status();
inline void update_pb(quint64 value, quint64 max);
QString md5sum(const char *filename);
private slots:
void on_pushButton_restore_clicked();
void on_pushButton_clone_clicked();
void on_pushButton_lock_clicked();
void on_pushButton_md5_clicked();
private:
QTime m_start_time;
Ui::MainWindow *ui;
Settings cfg;
bool m_disk_name_editable;
int m_block_size;
void __copy(E_ACT action);
inline void update_time(quint8 percent);
};
bool file_empty(const char *filename);
#endif // MAINWINDOW_H
|
msmania/chromium-debug | src/common.h | #define LOAD_FIELD_OFFSET(FIELD) \
field_name = FIELD; \
if (GetFieldOffset(type.c_str(), field_name, &offset) == 0) { \
offsets_[field_name] = offset; \
} \
else { \
dprintf("ERR> Symbol not found: %s::%s\n", type.c_str(), field_name); \
}
#define LOAD_MEMBER_POINTER(MEMBER) \
if (!ReadPointerEx(src, MEMBER)) { \
dprintf("ERR> Failed to load a pointer at %s\n", \
ptos(src, buf1, sizeof(buf1))); \
}
#define LOAD_MEMBER_VALUE(MEMBER) \
if (!ReadValue(src, MEMBER)) { \
dprintf("ERR> Failed to load a value at %s\n", \
ptos(src, buf1, sizeof(buf1))); \
}
#define ADD_CTOR(BASE, KEY, CLASS) \
ctors[#KEY] = []() -> BASE* {return new CLASS();}
typedef ULONG64 COREADDR;
LPCSTR ptos(ULONG64 p, LPSTR s, ULONG len);
FIELD_INFO GetFieldInfo(IN LPCSTR Type, IN LPCSTR Field);
const std::string &ResolveType(COREADDR addr);
class CPEImage {
private:
ULONG64 imagebase_;
WORD platform_;
IMAGE_DATA_DIRECTORY resource_dir_;
IMAGE_DATA_DIRECTORY import_dir_;
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms647001(v=vs.85).aspx
struct VS_VERSIONINFO {
WORD wLength;
WORD wValueLength;
WORD wType;
WCHAR szKey[16]; // L"VS_VERSION_INFO"
VS_FIXEDFILEINFO Value;
} version_;
bool Initialize(ULONG64 ImageBase);
ULONG ReadPointerEx(ULONG64 Address, PULONG64 Pointer) const;
public:
CPEImage(ULONG64 ImageBase);
virtual ~CPEImage();
bool IsInitialized() const;
bool Is64bit() const;
bool LoadVersion();
WORD GetPlatform() const;
void GetVersion(PDWORD FileVersionMS,
PDWORD FileVersionLS,
PDWORD ProductVersionMS,
PDWORD ProductVersionLS) const;
void DumpImportTable(LPCSTR DllName) const;
};
struct TARGETINFO {
std::string engine_;
bool is64bit_;
WORD version_;
WORD buildnum_;
TARGETINFO();
const char *engine() const;
};
class Object {
private:
static TARGETINFO targetinfo_;
protected:
COREADDR addr_;
public:
static COREADDR get_expression(const char *symbol);
static void InitializeTargetInfo();
static const TARGETINFO &target();
static bool ReadPointerEx(ULONG64 address, ULONG64 &pointer);
static COREADDR deref(ULONG64 address);
template<typename T>
static bool ReadValue(ULONG64 address, T &pointer) {
pointer = static_cast<T>(0);
ULONG cb = 0;
if (ReadMemory(address, &pointer, sizeof(T), &cb)) {
return true;
}
return false;
}
Object();
COREADDR addr() const { return addr_; }
};
template <typename T>
static void dump_arg(PCSTR args) {
const char delim[] = " ";
char args_copy[1024];
COREADDR exp = 0;
if (args && strcpy_s(args_copy, sizeof(args_copy), args) == 0) {
char *next_token = nullptr;
if (auto token = strtok_s(args_copy, delim, &next_token)) {
exp = GetExpression(token);
}
}
T t;
t.load(exp);
std::stringstream s;
t.dump(s);
dprintf(s.str().c_str());
}
|
mop/snip-fu | src/ext/ragel-parser.h | <gh_stars>1-10
#ifndef _PARSER_H_
#define _PARSER_H_
#include <glib.h>
enum {
ARRAY_SIZE = 2
};
typedef struct parse_input {
const char *data;
int data_length;
const char *start;
int start_length;
const char *end;
int end_length;
} parse_input;
typedef struct parse_data {
int depth;
GList *elements;
parse_input *input;
} parse_data;
void parser_free(parse_data *data);
parse_data *parser_execute(parse_input *input);
#endif
|
mop/snip-fu | src/ext/ragel-parser.c | <gh_stars>1-10
#line 1 "./ragel-parser.rl"
#include <glib.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include "ragel-parser.h"
/**
* This function is called when a snip-fu opening-tag is encountered.
* e.g. ${1:tag}
*/
static void push(parse_data *parse, int fpc);
/**
* This function is called when a regular opening tag (e.g. { ) is
* encountered.
*/
static void push_regular(parse_data *parse, int fpc);
/**
* This function is called when a closing-tag is encountered (})
*/
static void pop(parse_data *parse, int fpc);
/**
* This returns TRUE if the parse-stream contains a correct start-tag
*/
static int is_correct_start_tag(parse_data *parse, int fpc);
/**
* This returns TRUE if the parse-stream contains a correct end-tag
*/
static int is_correct_end_tag(parse_data *parse, int fpc);
#line 45 "./ragel-parser.rl"
#line 37 "./ragel-parser.c"
static const char _snippet_parser_actions[] = {
0, 1, 3, 1, 4, 1, 8, 1,
9, 2, 0, 5, 2, 1, 6, 2,
2, 7, 3, 1, 6, 2
};
static const char _snippet_parser_key_offsets[] = {
0, 8
};
static const char _snippet_parser_trans_keys[] = {
36, 37, 60, 62, 91, 93, 123, 125,
37, 60, 91, 123, 0
};
static const char _snippet_parser_single_lengths[] = {
8, 4
};
static const char _snippet_parser_range_lengths[] = {
0, 0
};
static const char _snippet_parser_index_offsets[] = {
0, 9
};
static const char _snippet_parser_trans_targs_wi[] = {
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
static const char _snippet_parser_trans_actions_wi[] = {
0, 18, 12, 15, 12, 15, 12, 15,
5, 9, 9, 9, 9, 7, 0
};
static const char _snippet_parser_to_state_actions[] = {
1, 0
};
static const char _snippet_parser_from_state_actions[] = {
3, 0
};
static const int snippet_parser_start = 0;
static const int snippet_parser_first_final = 0;
static const int snippet_parser_error = -1;
static const int snippet_parser_en_main = 0;
#line 48 "./ragel-parser.rl"
void push(parse_data *parse, int fpc)
{
if (!is_correct_start_tag(parse, fpc)) return;
parse->depth += 1;
if (parse->depth == 1) {
int *array = malloc(sizeof(int) * ARRAY_SIZE);
array[0] = fpc;
parse->elements = g_list_append(parse->elements, array);
}
}
void push_regular(parse_data *parse, int fpc)
{
if (!is_correct_start_tag(parse, fpc)) return;
if (parse->depth >= 1)
parse->depth += 1;
}
void pop(parse_data *parse, int fpc)
{
if (!is_correct_end_tag(parse, fpc)) return;
if (parse->depth == 1) {
GList *elem = g_list_last(parse->elements);
int *array = (int *)elem->data;
array[ARRAY_SIZE - 1] = fpc;
}
if (parse->depth > 0)
parse->depth -= 1;
}
int is_correct_start_tag(parse_data *parse, int fpc)
{
return strncmp(
&parse->input->data[fpc],
&parse->input->start[1],
parse->input->start_length - 1
) == 0;
}
int is_correct_end_tag(parse_data *parse, int fpc)
{
return strncmp(
&parse->input->data[fpc],
parse->input->end,
parse->input->end_length
) == 0;
}
parse_data* parser_execute(parse_input *input)
{
parse_data *parse = malloc(sizeof(*parse));
const char *p = input->data;
const char *pe = input->data + input->data_length;
const char *data = input->data;
parse->depth = 0;
parse->elements = NULL;
parse->input = input;
int cs, act = 0;
const char *tokstart, *tokend, *reg;
#line 153 "./ragel-parser.c"
{
cs = snippet_parser_start;
tokstart = 0;
tokend = 0;
act = 0;
}
#line 111 "./ragel-parser.rl"
#line 162 "./ragel-parser.c"
{
int _klen;
unsigned int _trans;
const char *_acts;
unsigned int _nacts;
const char *_keys;
if ( p == pe )
goto _out;
_resume:
_acts = _snippet_parser_actions + _snippet_parser_from_state_actions[cs];
_nacts = (unsigned int) *_acts++;
while ( _nacts-- > 0 ) {
switch ( *_acts++ ) {
case 4:
#line 1 "./ragel-parser.rl"
{tokstart = p;}
break;
#line 181 "./ragel-parser.c"
}
}
_keys = _snippet_parser_trans_keys + _snippet_parser_key_offsets[cs];
_trans = _snippet_parser_index_offsets[cs];
_klen = _snippet_parser_single_lengths[cs];
if ( _klen > 0 ) {
const char *_lower = _keys;
const char *_mid;
const char *_upper = _keys + _klen - 1;
while (1) {
if ( _upper < _lower )
break;
_mid = _lower + ((_upper-_lower) >> 1);
if ( (*p) < *_mid )
_upper = _mid - 1;
else if ( (*p) > *_mid )
_lower = _mid + 1;
else {
_trans += (_mid - _keys);
goto _match;
}
}
_keys += _klen;
_trans += _klen;
}
_klen = _snippet_parser_range_lengths[cs];
if ( _klen > 0 ) {
const char *_lower = _keys;
const char *_mid;
const char *_upper = _keys + (_klen<<1) - 2;
while (1) {
if ( _upper < _lower )
break;
_mid = _lower + (((_upper-_lower) >> 1) & ~1);
if ( (*p) < _mid[0] )
_upper = _mid - 2;
else if ( (*p) > _mid[1] )
_lower = _mid + 2;
else {
_trans += ((_mid - _keys)>>1);
goto _match;
}
}
_trans += _klen;
}
_match:
cs = _snippet_parser_trans_targs_wi[_trans];
if ( _snippet_parser_trans_actions_wi[_trans] == 0 )
goto _again;
_acts = _snippet_parser_actions + _snippet_parser_trans_actions_wi[_trans];
_nacts = (unsigned int) *_acts++;
while ( _nacts-- > 0 )
{
switch ( *_acts++ )
{
case 0:
#line 39 "./ragel-parser.rl"
{ push(parse, p - data); }
break;
case 1:
#line 40 "./ragel-parser.rl"
{ push_regular(parse, p - data); }
break;
case 2:
#line 41 "./ragel-parser.rl"
{ pop(parse, p - data); }
break;
case 5:
#line 39 "./ragel-parser.rl"
{tokend = p+1;}
break;
case 6:
#line 40 "./ragel-parser.rl"
{tokend = p+1;}
break;
case 7:
#line 41 "./ragel-parser.rl"
{tokend = p+1;}
break;
case 8:
#line 42 "./ragel-parser.rl"
{tokend = p+1;}
break;
case 9:
#line 42 "./ragel-parser.rl"
{tokend = p;p--;}
break;
#line 277 "./ragel-parser.c"
}
}
_again:
_acts = _snippet_parser_actions + _snippet_parser_to_state_actions[cs];
_nacts = (unsigned int) *_acts++;
while ( _nacts-- > 0 ) {
switch ( *_acts++ ) {
case 3:
#line 1 "./ragel-parser.rl"
{tokstart = 0;}
break;
#line 290 "./ragel-parser.c"
}
}
if ( ++p != pe )
goto _resume;
_out: {}
}
#line 112 "./ragel-parser.rl"
return parse;
}
void parser_free(parse_data *parser)
{
for (GList *i = parser->elements; i; i = i->next)
free(i->data); // free the array
g_list_free(parser->elements);
free(parser);
}
/*
def self.run_machine(data)
elements = []
depth = 0
%% write init;
%% write exec;
elements.map do |element|
start, stop = element
[start - 1, stop ]
end
end
*/
|
mop/snip-fu | src/ext/extension.c | #include <ruby.h>
#include <glib.h>
#include "ragel-parser.h"
VALUE TagParser = Qnil;
void Init_tag_parser();
static VALUE parse_tags(
VALUE self,
VALUE start_tag,
VALUE end_tag,
VALUE string
);
void Init_tag_parser()
{
TagParser = rb_define_module("TagParser");
rb_define_module_function(TagParser, "parse_tags", parse_tags, 3);
}
VALUE parse_tags(VALUE self, VALUE start_tag, VALUE end_tag, VALUE string)
{
VALUE str = StringValue(string);
VALUE start = StringValue(start_tag);
VALUE end = StringValue(end_tag);
parse_input input = (parse_input) {
RSTRING(str)->ptr, RSTRING(str)->len,
RSTRING(start)->ptr, RSTRING(start)->len,
RSTRING(end)->ptr, RSTRING(end)->len
};
parse_data *p = parser_execute(&input);
GList *list = p->elements;
VALUE array = rb_ary_new2(g_list_length(list));
for (GList *i = list; i; i = i->next) {
int *data = (int *)i->data;
VALUE pos = rb_ary_new2(ARRAY_SIZE);
rb_ary_push(pos, INT2NUM(data[0]));
rb_ary_push(pos, INT2NUM(data[1]));
rb_ary_push(array, pos);
}
parser_free(p);
return array;
}
|
OpenLENA/lena-web | web-core/web-cmx/src/mod_cmx.c | /* Copyright 2021 LENA Development Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* mod_cmx.c: LENA Monitoring Extension Module
*
*/
#define CMX_HANDLER "cmx-status"
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_main.h"
#include "apr_version.h"
#if APR_MAJOR_VERSION < 2
#include "apu_version.h"
#endif
#include "ap_mpm.h"
#include "util_script.h"
#include <time.h>
#include "scoreboard.h"
#if APR_HAVE_UNISTD_H
#include <unistd.h>
#endif
#define APR_WANT_STRFUNC
#include "apr_want.h"
#include "apr_strings.h"
#define CMX_STATUS_MAXLINE 64
#define CMX_KBYTE 1024
#define CMX_MBYTE 1048576L
#define CMX_GBYTE 1073741824L
#ifndef CMX_DEFAULT_TIME_FORMAT
#define CMX_DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
#endif
#define CMX_SERVER_DISABLED SERVER_NUM_STATUS
#define CMX_MOD_STATUS_NUM_STATUS (SERVER_NUM_STATUS+1)
#ifdef HAVE_TIMES
/* ugh... need to know if we're running with a pthread implementation
* such as linuxthreads that treats individual threads as distinct
* processes; that affects how we add up CPU time in a process
*/
#endif
static pid_t child_pid;
static char cmx_status_flags[CMX_MOD_STATUS_NUM_STATUS];
static int cmx_server_limit, cmx_thread_limit, cmx_threads_per_child, cmx_max_servers, cmx_is_async;
#include "jk_worker.h"
#include "jk_ajp_common.h"
#include "jk_lb_worker.h"
static jk_map_t *cmx_jk_map = NULL;
static char *cmx_jk_worker_file = NULL;
struct cmx_server_info
{
apr_time_t current_time;
apr_time_t restart_time;
double system_cpu_usage;
double user_cpu_usage;
unsigned long total_access;
apr_off_t total_traffic;
unsigned int max_threads;
unsigned int active_threads;
unsigned int idle_threads;
};
typedef struct cmx_server_info cmx_monitor_info_t;
struct cmx_was_info
{
char *jvm_route;
unsigned int state;
unsigned int active_connections;
unsigned int max_connections;
unsigned int idle_connections;
apr_off_t total_access;
apr_off_t total_error;
};
typedef struct cmx_was_info cmx_was_info_t;
/* Format the number of bytes nicely */
static void cmx_format_byte_out(request_rec *r, apr_off_t bytes)
{
if (bytes < (5 * CMX_KBYTE))
ap_rprintf(r, "%d B", (int) bytes);
else if (bytes < (CMX_MBYTE / 2))
ap_rprintf(r, "%.1f kB", (float) bytes / CMX_KBYTE);
else if (bytes < (CMX_GBYTE / 2))
ap_rprintf(r, "%.1f MB", (float) bytes / CMX_MBYTE);
else
ap_rprintf(r, "%.1f GB", (float) bytes / CMX_GBYTE);
}
static int cmx_cmp_module_name(const void *a_, const void *b_)
{
const module * const *a = a_;
const module * const *b = b_;
return strcmp((*a)->name, (*b)->name);
}
static apr_array_header_t *cmx_get_sorted_modules(apr_pool_t *p)
{
apr_array_header_t *arr = apr_array_make(p, 64, sizeof(module *));
module *modp, **entry;
for (modp = ap_top_module; modp; modp = modp->next) {
entry = &APR_ARRAY_PUSH(arr, module *);
*entry = modp;
}
qsort(arr->elts, arr->nelts, sizeof(module *), cmx_cmp_module_name);
return arr;
}
static void cmx_show_time(request_rec *r, apr_uint32_t tsecs)
{
int days, hrs, mins, secs;
secs = (int)(tsecs % 60);
tsecs /= 60;
mins = (int)(tsecs % 60);
tsecs /= 60;
hrs = (int)(tsecs % 24);
days = (int)(tsecs / 24);
if (days)
ap_rprintf(r, " %d day%s", days, days == 1 ? "" : "s");
if (hrs)
ap_rprintf(r, " %d hour%s", hrs, hrs == 1 ? "" : "s");
if (mins)
ap_rprintf(r, " %d minute%s", mins, mins == 1 ? "" : "s");
if (secs)
ap_rprintf(r, " %d second%s", secs, secs == 1 ? "" : "s");
}
static void cmx_show_header_html(request_rec *r)
{
ap_set_content_type(r, "text/html; charset=ISO-8859-1");
ap_rputs(DOCTYPE_XHTML_1_0T
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
"<head>\n"
" <title>LENA Web Monitoring Extension</title>\n" "</head>\n", r);
ap_rputs("<body><h1 style=\"text-align: center\">"
"LENA Web Information</h1>\n", r);
}
static void cmx_show_summary_html(request_rec *r)
{
server_rec *serv = r->server;
int max_daemons, forked, threaded;
ap_mpm_query(AP_MPMQ_MAX_DAEMON_USED, &max_daemons);
ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded);
ap_mpm_query(AP_MPMQ_IS_FORKED, &forked);
ap_rputs("<h2><a name=\"info\">Server Information</a></h2>", r);
ap_rprintf(r,
"<dl><dt><strong>Version:</strong> "
"<font size=\"+1\"><tt>%s</tt></font></dt>\n",
ap_get_server_description());
ap_rprintf(r,
"<dt><strong>Built:</strong> "
"<font size=\"+1\"><tt>%s</tt></font></dt>\n",
ap_get_server_built());
ap_rprintf(r,
"<dt><strong>Hostname/port:</strong> "
"<tt>%s:%u</tt></dt>\n",
ap_escape_html(r->pool, ap_get_server_name(r)),
ap_get_server_port(r));
ap_rprintf(r,
"<dt><strong>Timeouts:</strong> "
"<tt>connection: %d "
"keep-alive: %d</tt></dt>",
(int) (apr_time_sec(serv->timeout)),
(int) (apr_time_sec(serv->keep_alive_timeout)));
ap_rprintf(r, "<dt><strong>MPM Name:</strong> <tt>%s</tt></dt>\n",
ap_show_mpm());
ap_rprintf(r,
"<dt><strong>MPM Information:</strong> "
"<tt>Max Daemons: %d Threaded: %s Forked: %s</tt></dt>\n",
max_daemons, threaded ? "yes" : "no", forked ? "yes" : "no");
ap_rprintf(r,
"<dt><strong>Architecture:</strong> "
"<tt>%ld-bit</tt></dt>\n", 8 * (long) sizeof(void *));
ap_rprintf(r,
"<dt><strong>Engine Root:</strong> "
"<tt>%s</tt></dt>\n", ap_server_root);
ap_rprintf(r,
"<dt><strong>Config File:</strong> "
"<tt>%s</tt></dt>\n", ap_conftree->filename);
}
static void cmx_show_tail_html(request_rec *r)
{
ap_rputs(ap_psignature("", r), r);
ap_rputs("</body></html>\n", r);
}
static void cmx_show_modules_html(request_rec *r){
apr_array_header_t *modules = NULL;
int i;
module *modp = NULL;
modules = cmx_get_sorted_modules(r->pool);
ap_rputs("<h2><a name=\"modules\">Loaded Modules</a></h2>", r);
for (i = 0; i < modules->nelts; i++) {
modp = APR_ARRAY_IDX(modules, i, module *);
ap_rprintf(r, "<a>%s</a>", modp->name, modp->name);
if (i < modules->nelts) {
ap_rputs(", ", r);
}
}
}
static void cmx_show_server_status_html(request_rec *r){
const char *loc;
apr_time_t nowtime;
apr_uint32_t up_time;
ap_loadavg_t t;
int j, i, res, written;
int ready;
int busy;
unsigned long count;
unsigned long lres, my_lres, conn_lres;
apr_off_t bytes, my_bytes, conn_bytes;
apr_off_t bcount, kbcount;
long req_time;
int no_table_report;
worker_score *ws_record = apr_palloc(r->pool, sizeof *ws_record);
process_score *ps_record;
char *stat_buffer;
pid_t *pid_buffer, worker_pid;
int *thread_idle_buffer = NULL;
int *thread_busy_buffer = NULL;
clock_t tu, ts, tcu, tcs;
ap_generation_t mpm_generation, worker_generation;
#ifdef HAVE_TIMES
float tick;
int times_per_thread;
#endif
#ifdef HAVE_TIMES
times_per_thread = getpid() != child_pid;
#endif
ap_mpm_query(AP_MPMQ_GENERATION, &mpm_generation);
#ifdef HAVE_TIMES
#ifdef _SC_CLK_TCK
tick = sysconf(_SC_CLK_TCK);
#else
tick = HZ;
#endif
#endif
ready = 0;
busy = 0;
count = 0;
bcount = 0;
kbcount = 0;
no_table_report = 0;
pid_buffer = apr_palloc(r->pool, cmx_server_limit * sizeof(pid_t));
stat_buffer = apr_palloc(r->pool, cmx_server_limit * cmx_thread_limit * sizeof(char));
if (cmx_is_async) {
thread_idle_buffer = apr_palloc(r->pool, cmx_server_limit * sizeof(int));
thread_busy_buffer = apr_palloc(r->pool, cmx_server_limit * sizeof(int));
}
nowtime = apr_time_now();
tu = ts = tcu = tcs = 0;
if (!ap_exists_scoreboard_image()) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01237)
"Server status unavailable in inetd mode");
return;
}
for (i = 0; i < cmx_server_limit; ++i) {
#ifdef HAVE_TIMES
clock_t proc_tu = 0, proc_ts = 0, proc_tcu = 0, proc_tcs = 0;
clock_t tmp_tu, tmp_ts, tmp_tcu, tmp_tcs;
#endif
ps_record = ap_get_scoreboard_process(i);
if (cmx_is_async) {
thread_idle_buffer[i] = 0;
thread_busy_buffer[i] = 0;
}
for (j = 0; j < cmx_thread_limit; ++j) {
int indx = (i * cmx_thread_limit) + j;
ap_copy_scoreboard_worker(ws_record, i, j);
res = ws_record->status;
if ((i >= cmx_max_servers || j >= cmx_threads_per_child)
&& (res == SERVER_DEAD))
stat_buffer[indx] = cmx_status_flags[CMX_SERVER_DISABLED];
else
stat_buffer[indx] = cmx_status_flags[res];
if (!ps_record->quiescing
&& ps_record->pid) {
if (res == SERVER_READY) {
if (ps_record->generation == mpm_generation)
ready++;
if (cmx_is_async)
thread_idle_buffer[i]++;
}
else if (res != SERVER_DEAD &&
res != SERVER_STARTING &&
res != SERVER_IDLE_KILL) {
busy++;
if (cmx_is_async) {
if (res == SERVER_GRACEFUL)
thread_idle_buffer[i]++;
else
thread_busy_buffer[i]++;
}
}
}
/* XXX what about the counters for quiescing/seg faulted
* processes? should they be counted or not? GLA
*/
if (ap_extended_status) {
lres = ws_record->access_count;
bytes = ws_record->bytes_served;
if (lres != 0 || (res != SERVER_READY && res != SERVER_DEAD)) {
#ifdef HAVE_TIMES
tmp_tu = ws_record->times.tms_utime;
tmp_ts = ws_record->times.tms_stime;
tmp_tcu = ws_record->times.tms_cutime;
tmp_tcs = ws_record->times.tms_cstime;
if (times_per_thread) {
proc_tu += tmp_tu;
proc_ts += tmp_ts;
proc_tcu += tmp_tcu;
proc_tcs += tmp_tcs;
}
else {
if (tmp_tu > proc_tu ||
tmp_ts > proc_ts ||
tmp_tcu > proc_tcu ||
tmp_tcs > proc_tcs) {
proc_tu = tmp_tu;
proc_ts = tmp_ts;
proc_tcu = tmp_tcu;
proc_tcs = tmp_tcs;
}
}
#endif /* HAVE_TIMES */
count += lres;
bcount += bytes;
if (bcount >= CMX_KBYTE) {
kbcount += (bcount >> 10);
bcount = bcount & 0x3ff;
}
}
}
}
#ifdef HAVE_TIMES
tu += proc_tu;
ts += proc_ts;
tcu += proc_tcu;
tcs += proc_tcs;
#endif
pid_buffer[i] = ps_record->pid;
}
ap_rputs("<h2><a name=\"status\">Server Status</a></h2>", r);
/* up_time in seconds */
up_time = (apr_uint32_t) apr_time_sec(nowtime -
ap_scoreboard_image->global->restart_time);
ap_get_loadavg(&t);
ap_rvputs(r, "<dt>Current Time: ",
ap_ht_time(r->pool, nowtime, CMX_DEFAULT_TIME_FORMAT, 0),
"</dt>\n", NULL);
ap_rvputs(r, "<dt>Restart Time: ",
ap_ht_time(r->pool,
ap_scoreboard_image->global->restart_time,
CMX_DEFAULT_TIME_FORMAT, 0),
"</dt>\n", NULL);
ap_rprintf(r, "<dt>Parent Server Config. Generation: %d</dt>\n",
ap_state_query(AP_SQ_CONFIG_GEN));
ap_rprintf(r, "<dt>Parent Server MPM Generation: %d</dt>\n",
(int)mpm_generation);
ap_rputs("<dt>Server uptime: ", r);
cmx_show_time(r, up_time);
ap_rputs("</dt>\n", r);
ap_rprintf(r, "<dt>Server load: %.2f %.2f %.2f</dt>\n",
t.loadavg, t.loadavg5, t.loadavg15);
if (ap_extended_status) {
ap_rprintf(r, "<dt>Total accesses: %lu ", count);
ap_rprintf(r, " - Total traffic: %lu", kbcount);
ap_rputs("</dt>\n", r);
#ifdef HAVE_TIMES
/* Allow for OS/2 not having CPU stats */
ap_rprintf(r, "<dt>CPU Usage: u%g s%g cu%g cs%g",
tu / tick, ts / tick, tcu / tick, tcs / tick);
if (ts || tu || tcu || tcs)
ap_rprintf(r, " - %.3g%% CPU load</dt>\n",
(tu + ts + tcu + tcs) / tick / up_time * 100.);
#endif
if (up_time > 0) {
ap_rprintf(r, "<dt>%.3g requests/sec - ",
(float) count / (float) up_time);
cmx_format_byte_out(r, (unsigned long)(CMX_KBYTE * (float) kbcount
/ (float) up_time));
ap_rputs("/second - ", r);
}
if (count > 0) {
cmx_format_byte_out(r, (unsigned long)(CMX_KBYTE * (float) kbcount
/ (float) count));
ap_rputs("/request", r);
}
ap_rputs("</dt>\n", r);
} /* ap_extended_status */
ap_rprintf(r, "<dt>%d requests currently being processed, "
"%d idle workers</dt>\n", busy, ready);
ap_rputs("</dl>", r);
if (cmx_is_async) {
int write_completion = 0, lingering_close = 0, keep_alive = 0,
connections = 0;
/*
* These differ from 'busy' and 'ready' in how gracefully finishing
* threads are counted. XXX: How to make this clear in the html?
*/
int busy_workers = 0, idle_workers = 0;
ap_rputs("\n\n<table rules=\"all\" cellpadding=\"1%\">\n"
"<tr><th rowspan=\"2\">PID</th>"
"<th colspan=\"2\">Connections</th>\n"
"<th colspan=\"2\">Threads</th>"
"<th colspan=\"4\">Async connections</th></tr>\n"
"<tr><th>total</th><th>accepting</th>"
"<th>busy</th><th>idle</th><th>writing</th>"
"<th>keep-alive</th><th>closing</th></tr>\n", r);
for (i = 0; i < cmx_server_limit; ++i) {
ps_record = ap_get_scoreboard_process(i);
if (ps_record->pid) {
connections += ps_record->connections;
write_completion += ps_record->write_completion;
keep_alive += ps_record->keep_alive;
lingering_close += ps_record->lingering_close;
busy_workers += thread_busy_buffer[i];
idle_workers += thread_idle_buffer[i];
ap_rprintf(r, "<tr><td>%" APR_PID_T_FMT "</td><td>%u</td>"
"<td>%s</td><td>%u</td><td>%u</td>"
"<td>%u</td><td>%u</td><td>%u</td>"
"</tr>\n",
ps_record->pid, ps_record->connections,
ps_record->not_accepting ? "no" : "yes",
thread_busy_buffer[i], thread_idle_buffer[i],
ps_record->write_completion,
ps_record->keep_alive,
ps_record->lingering_close);
}
}
ap_rprintf(r, "<tr><td>Sum</td><td>%d</td><td> </td><td>%d</td>"
"<td>%d</td><td>%d</td><td>%d</td><td>%d</td>"
"</tr>\n</table>\n",
connections, busy_workers, idle_workers,
write_completion, keep_alive, lingering_close);
}
/* send the scoreboard 'table' out */
ap_rputs("<pre>", r);
written = 0;
for (i = 0; i < cmx_server_limit; ++i) {
for (j = 0; j < cmx_thread_limit; ++j) {
int indx = (i * cmx_thread_limit) + j;
if (stat_buffer[indx] != cmx_status_flags[CMX_SERVER_DISABLED]) {
ap_rputc(stat_buffer[indx], r);
if ((written % CMX_STATUS_MAXLINE == (CMX_STATUS_MAXLINE - 1)))
ap_rputs("\n", r);
written++;
}
}
}
ap_rputs("</pre>\n"
"<p>Scoreboard Key:<br />\n"
"\"<b><code>_</code></b>\" Waiting for Connection, \n"
"\"<b><code>S</code></b>\" Starting up, \n"
"\"<b><code>R</code></b>\" Reading Request,<br />\n"
"\"<b><code>W</code></b>\" Sending Reply, \n"
"\"<b><code>K</code></b>\" Keepalive (read), \n"
"\"<b><code>D</code></b>\" DNS Lookup,<br />\n"
"\"<b><code>C</code></b>\" Closing connection, \n"
"\"<b><code>L</code></b>\" Logging, \n"
"\"<b><code>G</code></b>\" Gracefully finishing,<br /> \n"
"\"<b><code>I</code></b>\" Idle cleanup of worker, \n"
"\"<b><code>.</code></b>\" Open slot with no current process<br />\n"
"<p />\n", r);
if (!ap_extended_status) {
int j;
int k = 0;
ap_rputs("PID Key: <br />\n"
"<pre>\n", r);
for (i = 0; i < cmx_server_limit; ++i) {
for (j = 0; j < cmx_thread_limit; ++j) {
int indx = (i * cmx_thread_limit) + j;
if (stat_buffer[indx] != '.') {
ap_rprintf(r, " %" APR_PID_T_FMT
" in state: %c ", pid_buffer[i],
stat_buffer[indx]);
if (++k >= 3) {
ap_rputs("\n", r);
k = 0;
} else
ap_rputs(",", r);
}
}
}
ap_rputs("\n"
"</pre>\n", r);
}
if (ap_extended_status) {
if (no_table_report)
ap_rputs("<hr /><h2>Server Details</h2>\n\n", r);
else
ap_rputs("\n\n<table border=\"0\"><tr>"
"<th>Srv</th><th>PID</th><th>Acc</th>"
"<th>M</th>"
#ifdef HAVE_TIMES
"<th>CPU\n</th>"
#endif
"<th>SS</th><th>Req</th>"
"<th>Conn</th><th>Child</th><th>Slot</th>"
"<th>Client</th><th>VHost</th>"
"<th>Request</th></tr>\n\n", r);
for (i = 0; i < cmx_server_limit; ++i) {
for (j = 0; j < cmx_thread_limit; ++j) {
ap_copy_scoreboard_worker(ws_record, i, j);
if (ws_record->access_count == 0 &&
(ws_record->status == SERVER_READY ||
ws_record->status == SERVER_DEAD)) {
continue;
}
ps_record = ap_get_scoreboard_process(i);
if (ws_record->start_time == 0L)
req_time = 0L;
else
req_time = (long)
((ws_record->stop_time -
ws_record->start_time) / 1000);
if (req_time < 0L)
req_time = 0L;
lres = ws_record->access_count;
my_lres = ws_record->my_access_count;
conn_lres = ws_record->conn_count;
bytes = ws_record->bytes_served;
my_bytes = ws_record->my_bytes_served;
conn_bytes = ws_record->conn_bytes;
if (ws_record->pid) { /* MPM sets per-worker pid and generation */
worker_pid = ws_record->pid;
worker_generation = ws_record->generation;
}
else {
worker_pid = ps_record->pid;
worker_generation = ps_record->generation;
}
if (no_table_report) {
if (ws_record->status == SERVER_DEAD)
ap_rprintf(r,
"<b>Server %d-%d</b> (-): %d|%lu|%lu [",
i, (int)worker_generation,
(int)conn_lres, my_lres, lres);
else
ap_rprintf(r,
"<b>Server %d-%d</b> (%"
APR_PID_T_FMT "): %d|%lu|%lu [",
i, (int) worker_generation,
worker_pid,
(int)conn_lres, my_lres, lres);
switch (ws_record->status) {
case SERVER_READY:
ap_rputs("Ready", r);
break;
case SERVER_STARTING:
ap_rputs("Starting", r);
break;
case SERVER_BUSY_READ:
ap_rputs("<b>Read</b>", r);
break;
case SERVER_BUSY_WRITE:
ap_rputs("<b>Write</b>", r);
break;
case SERVER_BUSY_KEEPALIVE:
ap_rputs("<b>Keepalive</b>", r);
break;
case SERVER_BUSY_LOG:
ap_rputs("<b>Logging</b>", r);
break;
case SERVER_BUSY_DNS:
ap_rputs("<b>DNS lookup</b>", r);
break;
case SERVER_CLOSING:
ap_rputs("<b>Closing</b>", r);
break;
case SERVER_DEAD:
ap_rputs("Dead", r);
break;
case SERVER_GRACEFUL:
ap_rputs("Graceful", r);
break;
case SERVER_IDLE_KILL:
ap_rputs("Dying", r);
break;
default:
ap_rputs("?STATE?", r);
break;
}
ap_rprintf(r, "] "
#ifdef HAVE_TIMES
"u%g s%g cu%g cs%g"
#endif
"\n %ld %ld (",
#ifdef HAVE_TIMES
ws_record->times.tms_utime / tick,
ws_record->times.tms_stime / tick,
ws_record->times.tms_cutime / tick,
ws_record->times.tms_cstime / tick,
#endif
(long)apr_time_sec(nowtime -
ws_record->last_used),
(long) req_time);
cmx_format_byte_out(r, conn_bytes);
ap_rputs("|", r);
cmx_format_byte_out(r, my_bytes);
ap_rputs("|", r);
cmx_format_byte_out(r, bytes);
ap_rputs(")\n", r);
ap_rprintf(r,
" <i>%s {%s}</i> <b>[%s]</b><br />\n\n",
ap_escape_html(r->pool,
ws_record->client),
ap_escape_html(r->pool,
ap_escape_logitem(r->pool,
ws_record->request)),
ap_escape_html(r->pool,
ws_record->vhost));
}
else { /* !no_table_report */
if (ws_record->status == SERVER_DEAD)
ap_rprintf(r,
"<tr><td><b>%d-%d</b></td><td>-</td><td>%d/%lu/%lu",
i, (int)worker_generation,
(int)conn_lres, my_lres, lres);
else
ap_rprintf(r,
"<tr><td><b>%d-%d</b></td><td>%"
APR_PID_T_FMT
"</td><td>%d/%lu/%lu",
i, (int)worker_generation,
worker_pid,
(int)conn_lres,
my_lres, lres);
switch (ws_record->status) {
case SERVER_READY:
ap_rputs("</td><td>_", r);
break;
case SERVER_STARTING:
ap_rputs("</td><td><b>S</b>", r);
break;
case SERVER_BUSY_READ:
ap_rputs("</td><td><b>R</b>", r);
break;
case SERVER_BUSY_WRITE:
ap_rputs("</td><td><b>W</b>", r);
break;
case SERVER_BUSY_KEEPALIVE:
ap_rputs("</td><td><b>K</b>", r);
break;
case SERVER_BUSY_LOG:
ap_rputs("</td><td><b>L</b>", r);
break;
case SERVER_BUSY_DNS:
ap_rputs("</td><td><b>D</b>", r);
break;
case SERVER_CLOSING:
ap_rputs("</td><td><b>C</b>", r);
break;
case SERVER_DEAD:
ap_rputs("</td><td>.", r);
break;
case SERVER_GRACEFUL:
ap_rputs("</td><td>G", r);
break;
case SERVER_IDLE_KILL:
ap_rputs("</td><td>I", r);
break;
default:
ap_rputs("</td><td>?", r);
break;
}
ap_rprintf(r,
"\n</td>"
#ifdef HAVE_TIMES
"<td>%.2f</td>"
#endif
"<td>%ld</td><td>%ld",
#ifdef HAVE_TIMES
(ws_record->times.tms_utime +
ws_record->times.tms_stime +
ws_record->times.tms_cutime +
ws_record->times.tms_cstime) / tick,
#endif
(long)apr_time_sec(nowtime -
ws_record->last_used),
(long)req_time);
ap_rprintf(r, "</td><td>%-1.1f</td><td>%-2.2f</td><td>%-2.2f\n",
(float)conn_bytes / CMX_KBYTE, (float) my_bytes / CMX_MBYTE,
(float)bytes / CMX_MBYTE);
ap_rprintf(r, "</td><td>%s</td><td nowrap>%s</td>"
"<td nowrap>%s</td></tr>\n\n",
ap_escape_html(r->pool,
ws_record->client),
ap_escape_html(r->pool,
ws_record->vhost),
ap_escape_html(r->pool,
ap_escape_logitem(r->pool,
ws_record->request)));
} /* no_table_report */
} /* for (j...) */
} /* for (i...) */
if (!no_table_report) {
ap_rputs("</table>\n \
<hr /> \
<table>\n \
<tr><th>Srv</th><td>Child Server number - generation</td></tr>\n \
<tr><th>PID</th><td>OS process ID</td></tr>\n \
<tr><th>Acc</th><td>Number of accesses this connection / this child / this slot</td></tr>\n \
<tr><th>M</th><td>Mode of operation</td></tr>\n"
#ifdef HAVE_TIMES
"<tr><th>CPU</th><td>CPU usage, number of seconds</td></tr>\n"
#endif
"<tr><th>SS</th><td>Seconds since beginning of most recent request</td></tr>\n \
<tr><th>Req</th><td>Milliseconds required to process most recent request</td></tr>\n \
<tr><th>Conn</th><td>Kilobytes transferred this connection</td></tr>\n \
<tr><th>Child</th><td>Megabytes transferred this child</td></tr>\n \
<tr><th>Slot</th><td>Total megabytes transferred this slot</td></tr>\n \
</table>\n", r);
}
} /* if (ap_extended_status) */
else {
ap_rputs("<hr />To obtain a full report with current status "
"information you need to use the "
"<code>ExtendedStatus On</code> directive.\n", r);
}
}
static apr_table_t* cmx_get_request_params(request_rec *r){
apr_table_t *params = apr_table_make(r->pool, 10);
char *args = apr_pstrdup(r->pool, r->args);
char *tok, *val;
while (args && *args) {
if ((val = ap_strchr(args, '='))) {
*val++ = '\0';
if ((tok = ap_strchr(val, '&')))
*tok++ = '\0';
apr_table_setn(params, args, val);
args = tok;
}
}
return params;
}
static int cmx_get_was_count(request_rec *r){
char **worker_list;
unsigned int num_of_workers=0;
int i;
int was_count_sum = 0;
//copy cmx_jk_map to cmx_jk_map_temp
jk_map_t *cmx_jk_map_temp;
jk_map_alloc(&cmx_jk_map_temp);
jk_map_copy(cmx_jk_map, cmx_jk_map_temp);
jk_get_worker_list(cmx_jk_map_temp, &worker_list, &num_of_workers);
for (i = 0; i < num_of_workers; i++) {
const char *type = jk_get_worker_type(cmx_jk_map_temp, worker_list[i]);
if (!strcmp(type, "lb")) {
jk_worker_t *w = wc_get_worker_for_name(worker_list[i], NULL);
lb_worker_t *worker= (lb_worker_t *) w->worker_private;
if (worker->lb_workers) {
was_count_sum += worker->num_of_workers;
}
}
}
//free cmx_jk_map_temp
jk_map_free(&cmx_jk_map_temp);
return was_count_sum;
}
static cmx_was_info_t* cmx_get_was_infos(request_rec *r, int was_count)
{
char **worker_list;
unsigned int num_of_workers=0;
int worker_idx = 0;
int i;
int idle_connections;
unsigned int ep_cache_sz;
cmx_was_info_t *was_infos = (cmx_was_info_t *)apr_palloc(r->pool, sizeof(cmx_was_info_t) * was_count );
//copy cmx_jk_map to cmx_jk_map_temp
jk_map_t *cmx_jk_map_temp;
jk_map_alloc(&cmx_jk_map_temp);
jk_map_copy(cmx_jk_map, cmx_jk_map_temp);
jk_get_worker_list(cmx_jk_map_temp, &worker_list, &num_of_workers);
for (i = 0; i < num_of_workers; i++) {
const char *type = jk_get_worker_type(cmx_jk_map_temp, worker_list[i]);
if (!strcmp(type, "lb")) {
jk_worker_t *w = wc_get_worker_for_name(worker_list[i], NULL);
lb_worker_t *worker= (lb_worker_t *) w->worker_private;
if (worker->lb_workers) {
int idx;
int state;
lb_sub_worker_t *lb_sub_worker;
ajp_worker_t *ajp_worker;
for (idx = 0; idx < worker->num_of_workers; idx++) {
lb_sub_worker = NULL;
ajp_worker = NULL;
state = -1;
lb_sub_worker = &worker->lb_workers[idx];
ajp_worker = (ajp_worker_t *) lb_sub_worker->worker->worker_private;
if (lb_sub_worker == NULL)
continue;
if (ajp_worker == NULL)
continue;
was_infos[worker_idx].jvm_route = lb_sub_worker->name;
was_infos[worker_idx].state = lb_sub_worker->s->state;
was_infos[worker_idx].total_access = ajp_worker->s->used;
was_infos[worker_idx].total_error = ajp_worker->s->errors;
was_infos[worker_idx].active_connections = ajp_worker->s->busy;
idle_connections = ajp_worker->s->connected - ajp_worker->s->busy;
idle_connections = idle_connections <= 0 ? 0 : idle_connections;
was_infos[worker_idx].idle_connections = idle_connections;
ep_cache_sz = ajp_worker->ep_cache_sz;
ep_cache_sz = ep_cache_sz <= 0 ? 128 : ep_cache_sz;
was_infos[worker_idx].max_connections = ep_cache_sz * cmx_max_servers;
worker_idx++;
}
}
}
}
//free cmx_jk_map_temp
jk_map_free(&cmx_jk_map_temp);
return was_infos;
}
static cmx_monitor_info_t* cmx_get_monitor_info(request_rec *r) {
const char *loc;
apr_time_t nowtime;
int j, i, res, written;
int ready;
int busy;
unsigned long count;
unsigned long lres, my_lres, conn_lres;
apr_off_t bytes, my_bytes, conn_bytes;
apr_off_t bcount, kbcount;
long req_time;
worker_score *ws_record = apr_palloc(r->pool, sizeof *ws_record);
process_score *ps_record;
char *stat_buffer;
pid_t *pid_buffer, worker_pid;
int *thread_idle_buffer = NULL;
int *thread_busy_buffer = NULL;
clock_t tu, ts, tcu, tcs;
ap_generation_t mpm_generation, worker_generation;
cmx_monitor_info_t *monitor_info;
#ifdef HAVE_TIMES
float tick;
int times_per_thread;
#endif
#ifdef HAVE_TIMES
times_per_thread = getpid() != child_pid;
#endif
ap_mpm_query(AP_MPMQ_GENERATION, &mpm_generation);
#ifdef HAVE_TIMES
#ifdef _SC_CLK_TCK
tick = sysconf(_SC_CLK_TCK);
#else
tick = HZ;
#endif
#endif
ready = 0;
busy = 0;
count = 0;
bcount = 0;
kbcount = 0;
pid_buffer = apr_palloc(r->pool, cmx_server_limit * sizeof(pid_t));
stat_buffer = apr_palloc(r->pool, cmx_server_limit * cmx_thread_limit * sizeof(char));
if (cmx_is_async) {
thread_idle_buffer = apr_palloc(r->pool, cmx_server_limit * sizeof(int));
thread_busy_buffer = apr_palloc(r->pool, cmx_server_limit * sizeof(int));
}
nowtime = apr_time_now();
tu = ts = tcu = tcs = 0;
if (!ap_exists_scoreboard_image()) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01237)
"Server status unavailable in inetd mode");
return NULL;
}
for (i = 0; i < cmx_server_limit; ++i) {
#ifdef HAVE_TIMES
clock_t proc_tu = 0, proc_ts = 0, proc_tcu = 0, proc_tcs = 0;
clock_t tmp_tu, tmp_ts, tmp_tcu, tmp_tcs;
#endif
ps_record = ap_get_scoreboard_process(i);
if (cmx_is_async) {
thread_idle_buffer[i] = 0;
thread_busy_buffer[i] = 0;
}
for (j = 0; j < cmx_thread_limit; ++j) {
int indx = (i * cmx_thread_limit) + j;
ap_copy_scoreboard_worker(ws_record, i, j);
res = ws_record->status;
if ((i >= cmx_max_servers || j >= cmx_threads_per_child)
&& (res == SERVER_DEAD))
stat_buffer[indx] = cmx_status_flags[CMX_SERVER_DISABLED];
else
stat_buffer[indx] = cmx_status_flags[res];
if (!ps_record->quiescing && ps_record->pid) {
if (res == SERVER_READY) {
if (ps_record->generation == mpm_generation)
ready++;
if (cmx_is_async)
thread_idle_buffer[i]++;
}
else if (res != SERVER_DEAD &&
res != SERVER_STARTING &&
res != SERVER_IDLE_KILL) {
busy++;
if (cmx_is_async) {
if (res == SERVER_GRACEFUL)
thread_idle_buffer[i]++;
else
thread_busy_buffer[i]++;
}
}
}
lres = ws_record->access_count;
bytes = ws_record->bytes_served;
if (lres != 0 || (res != SERVER_READY && res != SERVER_DEAD)) {
#ifdef HAVE_TIMES
tmp_tu = ws_record->times.tms_utime;
tmp_ts = ws_record->times.tms_stime;
tmp_tcu = ws_record->times.tms_cutime;
tmp_tcs = ws_record->times.tms_cstime;
if (times_per_thread) {
proc_tu += tmp_tu;
proc_ts += tmp_ts;
proc_tcu += tmp_tcu;
proc_tcs += tmp_tcs;
}
else {
if (tmp_tu > proc_tu ||
tmp_ts > proc_ts ||
tmp_tcu > proc_tcu ||
tmp_tcs > proc_tcs) {
proc_tu = tmp_tu;
proc_ts = tmp_ts;
proc_tcu = tmp_tcu;
proc_tcs = tmp_tcs;
}
}
#endif /* HAVE_TIMES */
count += lres;
bcount += bytes;
if (bcount >= CMX_KBYTE) {
kbcount += (bcount >> 10);
bcount = bcount & 0x3ff;
}
}
}
#ifdef HAVE_TIMES
tu += proc_tu;
ts += proc_ts;
tcu += proc_tcu;
tcs += proc_tcs;
#endif
pid_buffer[i] = ps_record->pid;
}
monitor_info = (cmx_monitor_info_t *) apr_palloc(r->pool, sizeof(cmx_monitor_info_t));
monitor_info->current_time = nowtime / 1000;
monitor_info->restart_time = ap_scoreboard_image->global->restart_time / 1000;
monitor_info->total_access = count;
monitor_info->total_traffic = kbcount;
monitor_info->max_threads = cmx_max_servers * cmx_threads_per_child;
monitor_info->active_threads = busy;
monitor_info->idle_threads = ready;
#ifdef HAVE_TIMES
monitor_info->system_cpu_usage = ts / tick;
monitor_info->user_cpu_usage = tu / tick;
#endif
return monitor_info;
}
static void cmx_show_monitor_json(request_rec *r){
cmx_monitor_info_t *monitor_info = cmx_get_monitor_info(r);
int was_count = cmx_get_was_count(r);
process_score *ps_record;
int process_infos_idx;
int process_count=0;
cmx_was_info_t* was_infos = cmx_get_was_infos(r, was_count);
ap_set_content_type(r, "application/json; charset=ISO-8859-1");
ap_rputs("{", r); /* start of json */
ap_rprintf(r, "\"currentTime\":\"%"APR_TIME_T_FMT"\""
",\"restartTime\":\"%"APR_TIME_T_FMT"\""
",\"systemCpuUsage\":\"%g\""
",\"userCpuUsage\":\"%g\""
",\"totalAccess\":\"%lu\""
",\"totalTraffic\":\"%lu\""
",\"maxThreads\":\"%d\""
",\"activeThreads\":\"%d\""
",\"idleThreads\":\"%d\""
, monitor_info->current_time
, monitor_info->restart_time
, monitor_info->system_cpu_usage
, monitor_info->user_cpu_usage
, monitor_info->total_access
, monitor_info->total_traffic
, monitor_info->max_threads
, monitor_info->active_threads
, monitor_info->idle_threads
);
ap_rputs(",\"wasInfos\":[", r); /* start of wasInfos */
if(was_infos){
int was_infos_idx;
for(was_infos_idx=0; was_infos_idx < was_count; was_infos_idx++)
{
if(was_infos_idx > 0){
ap_rputs(",", r);
}
ap_rprintf(r, "{"
"\"jvmRoute\":\"%s\""
",\"state\":\"%d\""
",\"maxConnections\":\"%d\""
",\"activeConnections\":\"%d\""
",\"idleConnections\":\"%d\""
",\"totalAccess\":\"%lu\""
",\"totalError\":\"%lu\""
"}"
,was_infos[was_infos_idx].jvm_route
,was_infos[was_infos_idx].state
,was_infos[was_infos_idx].max_connections
,was_infos[was_infos_idx].active_connections
,was_infos[was_infos_idx].idle_connections
,was_infos[was_infos_idx].total_access
,was_infos[was_infos_idx].total_error
);
}
}
ap_rputs("]", r); /* end of wasInfos */
ap_rputs(",\"processInfos\":[", r); /* start of processInfos */
for (process_infos_idx = 0; process_infos_idx < cmx_server_limit; process_infos_idx++) {
ps_record = ap_get_scoreboard_process(process_infos_idx);
if (ps_record->pid) {
if(process_count > 0){
ap_rputs(",", r);
}
ap_rprintf(r, "{"
"\"pid\":\"%d\""
/*
",\"connections\":\"%d\""
",\"writeCompletion\":\"%d\""
",\"keepAlive\":\"%d\""
",\"lingeringClose\":\"%d\""
*/
"}"
,ps_record->pid
/*
,ps_record->connections
,ps_record->write_completion
,ps_record->keep_alive
,ps_record->lingering_close
*/
);
process_count++;
}
}
ap_rputs("]", r); /* end of processInfos */
ap_rputs("}", r); /* end of json */
}
static void cmx_show_was_status_html(request_rec *r) {
int was_count = cmx_get_was_count(r);
int was_infos_idx;
cmx_was_info_t* was_infos = cmx_get_was_infos(r, was_count);
ap_rputs("<h2><a name=\"was-info\">Connected WAS Information</a></h2>", r);
ap_rputs("<table cellpadding=\"1%\">", r);
ap_rputs("<tr>"
"<th>JvmRoute</th>"
"<th>State</th>"
"<th>MaxConnections</th>"
"<th>activeConnections</th>"
"<th>idleConnections</th>"
"<th>totalAccess</th>"
"<th>totalError</th>"
"</tr>"
, r);
if(was_infos){
for(was_infos_idx=0; was_infos_idx < was_count; was_infos_idx++)
{
ap_rprintf(r, "<tr>"
"<td>%s</td>"
"<td>%d</td>"
"<td>%d</td>"
"<td>%d</td>"
"<td>%d</td>"
"<td>%d</td>"
"<td>%d</td>"
"</tr>"
,was_infos[was_infos_idx].jvm_route
,was_infos[was_infos_idx].state
,was_infos[was_infos_idx].max_connections
,was_infos[was_infos_idx].active_connections
,was_infos[was_infos_idx].idle_connections
,was_infos[was_infos_idx].total_access
,was_infos[was_infos_idx].total_error
);
}
}
ap_rputs("</table>", r);
}
static void cmx_show_not_support_html(request_rec *r) {
cmx_show_header_html(r);
ap_rputs("<h2><a name=\"notice\">Doesn't support this command and parameter.</a></h2>", r);
cmx_show_tail_html(r);
}
static void cmx_show_info_html(request_rec *r) {
cmx_show_header_html(r);
cmx_show_summary_html(r);
cmx_show_modules_html(r);
cmx_show_server_status_html(r);
cmx_show_was_status_html(r);
cmx_show_tail_html(r);
}
static int cmx_handler(request_rec *r) {
apr_table_t *params;
const char *cmd;
const char *format;
/* Determine if we are the handler for this request. */
if (r->handler && strcmp(r->handler, CMX_HANDLER)) {
return DECLINED;
}
params = cmx_get_request_params(r);
cmd = apr_table_get(params, "cmd") == NULL ? "info" : apr_table_get(params, "cmd");
format = apr_table_get(params, "format") == NULL ? "html" : apr_table_get(params, "format");
if (!strcmp(cmd, "monitor")){
if(!strcmp(format, "json")){
cmx_show_monitor_json(r);
}
else if(!strcmp(format, "html")){
cmx_show_not_support_html(r);
}
else{
cmx_show_not_support_html(r);
}
}
else if (!strcmp(cmd, "info")){
if(!strcmp(format, "html")){
cmx_show_info_html(r);
}
else{
cmx_show_not_support_html(r);
}
}
return OK;
}
static void cmx_jk_init(apr_pool_t *p, server_rec *s) {
if (cmx_jk_worker_file == NULL){
fprintf(stderr,"[error:mod_cmx] worker file name invalid.\n");
return;
}
if(jk_file_exists(cmx_jk_worker_file) != JK_TRUE){
fprintf(stderr,"[error:mod_cmx] worker file doesn't exist.\n");
return;
}
if (!cmx_jk_map){
jk_map_alloc(&cmx_jk_map);
jk_map_read_properties(cmx_jk_map, NULL, cmx_jk_worker_file, NULL, JK_MAP_HANDLE_DUPLICATES, NULL);
}
}
static void cmx_child_init(apr_pool_t *p, server_rec *s)
{
child_pid = getpid();
cmx_jk_init(p, s);
}
static int cmx_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) {
cmx_status_flags[SERVER_DEAD] = '.'; /* We don't want to assume these are in */
cmx_status_flags[SERVER_READY] = '_'; /* any particular order in scoreboard.h */
cmx_status_flags[SERVER_STARTING] = 'S';
cmx_status_flags[SERVER_BUSY_READ] = 'R';
cmx_status_flags[SERVER_BUSY_WRITE] = 'W';
cmx_status_flags[SERVER_BUSY_KEEPALIVE] = 'K';
cmx_status_flags[SERVER_BUSY_LOG] = 'L';
cmx_status_flags[SERVER_BUSY_DNS] = 'D';
cmx_status_flags[SERVER_CLOSING] = 'C';
cmx_status_flags[SERVER_GRACEFUL] = 'G';
cmx_status_flags[SERVER_IDLE_KILL] = 'I';
cmx_status_flags[CMX_SERVER_DISABLED] = ' ';
ap_mpm_query(AP_MPMQ_HARD_LIMIT_THREADS, &cmx_thread_limit);
ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &cmx_server_limit);
ap_mpm_query(AP_MPMQ_MAX_THREADS, &cmx_threads_per_child);
/* work around buggy MPMs */
if (cmx_threads_per_child == 0)
cmx_threads_per_child = 1;
ap_mpm_query(AP_MPMQ_MAX_DAEMONS, &cmx_max_servers);
ap_mpm_query(AP_MPMQ_IS_ASYNC, &cmx_is_async);
return OK;
}
static int cmx_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp) {
/* When mod_status is loaded, default our ExtendedStatus to 'on'
* other modules which prefer verbose scoreboards may play a similar game.
* If left to their own requirements, mpm modules can make do with simple
* scoreboard entries.
*/
ap_extended_status = 1;
return OK;
}
static void cmx_register_hooks(apr_pool_t *p) {
ap_hook_handler(cmx_handler, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_pre_config(cmx_pre_config, NULL, NULL, APR_HOOK_LAST);
ap_hook_post_config(cmx_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_child_init(cmx_child_init, NULL, NULL, APR_HOOK_MIDDLE);
}
static const char *jk_set_worker_file(cmd_parms * cmd, void *dummy, const char *worker_file) {
const char *err_string = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err_string != NULL) {
return err_string;
}
cmx_jk_worker_file = ap_server_root_relative(cmd->pool, worker_file);
if (cmx_jk_worker_file == NULL){
fprintf(stderr,"[info:mod_cmx] worker file name invalid.\n");
}
return NULL;
}
static const command_rec cmx_cmds[] = {
AP_INIT_TAKE1("JkWorkersFile", jk_set_worker_file, NULL, RSRC_CONF,
"The name of a worker file for the Tomcat servlet containers"),
{NULL}
};
module AP_MODULE_DECLARE_DATA cmx_module = {
STANDARD20_MODULE_STUFF,
NULL, /* per-directory config creator */
NULL, /* dir config merger */
NULL, /* server config creator */
NULL, /* server config merger */
cmx_cmds, /* command table */
cmx_register_hooks /* register hooks */
};
|
smwikipedia/EwokOS | kernel/include/hardware.h | #ifndef HARDWARE_H
#define HARDWARE_H
#include <types.h>
#include <mm/mmu.h>
extern char _fb_start[];
extern void hw_init();
extern uint32_t get_mmio_base_phy();
extern uint32_t get_mmio_mem_size();
extern uint32_t get_phy_ram_size();
extern void arch_set_kernel_vm(page_dir_entry_t* vm);
#endif
|
smwikipedia/EwokOS | rootfs/sbin/init/init.c | <reponame>smwikipedia/EwokOS
#include <types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <vfs/fs.h>
#include <kserv.h>
#include <syscall.h>
static int start_vfsd() {
printf("start vfs service ... ");
int pid = fork();
if(pid == 0) {
exec("/sbin/vfsd");
}
kserv_wait("kserv.vfsd");
printf("ok.\n");
return 0;
}
static int mount_root() {
printf("mount root fs from sdcard ...\n");
int pid = fork();
if(pid == 0) {
exec("/sbin/dev/sdcard");
}
kserv_wait("dev.sdcard");
printf("root mounted.\n");
return 0;
}
static int read_line(int fd, char* line, int sz) {
int i = 0;
while(i<sz) {
char c;
if(read(fd, &c, 1) <= 0) {
line[i] = 0;
return -1;
}
if(c == '\n') {
line[i] = 0;
break;
}
line[i++] = c;
}
return i;
}
static int run_init_procs(const char* fname) {
int fd = open(fname, 0);
if(fd < 0)
return -1;
char cmd[CMD_MAX];
int i = 0;
while(true) {
i = read_line(fd, cmd, CMD_MAX-1);
if(i < 0)
break;
if(i == 0)
continue;
int pid = fork();
if(pid == 0) {
exec(cmd);
}
}
close(fd);
return 0;
}
static void session_loop() {
while(1) {
int pid = fork();
if(pid == 0) {
exec("/sbin/session");
}
else {
wait(pid);
}
}
}
int main() {
if(getpid() > 0) {
printf("Panic: 'init' process can only run at boot time!\n");
return -1;
}
start_vfsd();
mount_root();
run_init_procs("/etc/init/init.dev");
run_init_procs("/etc/init/init.rd");
/*set uid to root*/
syscall2(SYSCALL_SET_UID, getpid(), 0);
/*run 2 session for uart0 and framebuffer based console0*/
int pid = fork();
if(pid == 0) {
setenv("STDIO_DEV", "/dev/console0");
init_stdio();
exec("/sbin/session");
return 0;
}
else {
setenv("STDIO_DEV", "/dev/tty0");
session_loop();
}
return 0;
}
|
smwikipedia/EwokOS | rootfs/lib/src/shm.c | #include <shm.h>
#include <syscall.h>
int32_t shm_alloc(uint32_t size) {
return syscall1(SYSCALL_SHM_ALLOC, (int32_t)size);
}
void shm_free(int32_t id) {
syscall1(SYSCALL_SHM_FREE, id);
}
void* shm_map(int32_t id) {
return (void*)syscall1(SYSCALL_SHM_MAP, id);
}
int32_t shm_unmap(int32_t id) {
return syscall1(SYSCALL_SHM_UNMAP, id);
}
|
smwikipedia/EwokOS | kernel/include/printk.h | <gh_stars>0
#ifndef PRINTK_H
#define PRINTK_H
void printk(const char *format, ...);
#endif
|
smwikipedia/EwokOS | kernel/include/semaphore.h | <reponame>smwikipedia/EwokOS<filename>kernel/include/semaphore.h<gh_stars>0
#ifndef SEMAPHORE_H
#define SEMAPHORE_H
#include <types.h>
int32_t semaphore_init(int32_t* s);
int32_t semaphore_close(int32_t* s);
int32_t semaphore_lock(int32_t* s);
int32_t semaphore_unlock(int32_t* s);
#endif
|
smwikipedia/EwokOS | kernel/src/dev/basic_dev.c | <gh_stars>0
#include <dev/basic_dev.h>
#include <proc.h>
#include <sconf.h>
/*some devices */
bool uart_init();
bool keyboard_init();
bool mouse_init();
bool sdc_init();
bool dev_init() {
if(!uart_init())
return false;
if(!keyboard_init())
return false;
if(!mouse_init())
return false;
if(!sdc_init())
return false;
return true;
}
bool fb_init(sconf_t* conf);
bool conf_dev_init(sconf_t* conf) {
if(!fb_init(conf))
return false;
return true;
}
/*some devices */
int32_t dev_fb_info(int16_t id, void* info);
/*******************/
int32_t dev_info(int32_t type_id, void* info) {
int16_t type, id;
type = (type_id & 0xffff0000) >> 16;
id = (type_id & 0xffff);
(void)id;
switch(type) {
case DEV_FRAME_BUFFER:
return dev_fb_info(id, info);
}
return -1;
}
/*some char devices*/
int32_t dev_keyboard_read(int16_t id, void* buf, uint32_t size);
int32_t dev_mouse_read(int16_t id, void* buf, uint32_t size);
int32_t dev_uart_read(int16_t id, void* buf, uint32_t size);
int32_t dev_uart_write(int16_t id, void* buf, uint32_t size);
int32_t dev_fb_write(int16_t id, void* buf, uint32_t size);
/*******************/
int32_t dev_char_read(int32_t type_id, void* buf, uint32_t size) {
if(_current_proc->owner > 0)
return -1;
int16_t type, id;
type = (type_id & 0xffff0000) >> 16;
id = (type_id & 0xffff);
switch(type) {
case DEV_KEYBOARD:
return dev_keyboard_read(id, buf, size);
case DEV_MOUSE:
return dev_mouse_read(id, buf, size);
case DEV_UART:
return dev_uart_read(id, buf, size);
}
return -1;
}
int32_t dev_char_write(int32_t type_id, void* buf, uint32_t size) {
if(_current_proc->owner > 0)
return -1;
int16_t type, id;
type = (type_id & 0xffff0000) >> 16;
id = (type_id & 0xffff);
(void)id;
switch(type) {
case DEV_UART:
return dev_uart_write(id, buf, size);
case DEV_FRAME_BUFFER:
return dev_fb_write(id, buf, size);
}
return -1;
}
/*some block devices*/
int32_t dev_sdc_read(int16_t id, uint32_t block);
int32_t dev_sdc_read_done(int16_t id, void* buf);
int32_t dev_sdc_write(int16_t id, uint32_t block, void* buf);
int32_t dev_sdc_write_done(int16_t id);
/********************/
int32_t dev_block_read(int32_t type_id, uint32_t block) {
if(_current_proc->owner > 0)
return -1;
int16_t type, id;
type = (type_id & 0xffff0000) >> 16;
id = (type_id & 0xffff);
switch(type) {
case DEV_SDC:
return dev_sdc_read(id, block);
}
return -1;
}
int32_t dev_block_read_done(int32_t type_id, void* buf) {
if(_current_proc->owner > 0)
return -1;
int16_t type, id;
type = (type_id & 0xffff0000) >> 16;
id = (type_id & 0xffff);
switch(type) {
case DEV_SDC:
return dev_sdc_read_done(id, buf);
}
return -1;
}
int32_t dev_block_write(int32_t type_id, uint32_t block, void* buf) {
if(_current_proc->owner > 0)
return -1;
int16_t type, id;
type = (type_id & 0xffff0000) >> 16;
id = (type_id & 0xffff);
(void)id;
switch(type) {
case DEV_SDC:
return dev_sdc_write(id, block, buf);
}
return -1;
}
int32_t dev_block_write_done(int32_t type_id) {
if(_current_proc->owner > 0)
return -1;
int16_t type, id;
type = (type_id & 0xffff0000) >> 16;
id = (type_id & 0xffff);
(void)id;
switch(type) {
case DEV_SDC:
return dev_sdc_write_done(id);
}
return -1;
}
|
smwikipedia/EwokOS | rootfs/dev/null/null.c | #include <dev/devserv.h>
#include <unistd.h>
int main() {
device_t dev = {0};
dev_run(&dev, "dev.null", 0, "/dev/null", true);
return 0;
}
|
smwikipedia/EwokOS | rootfs/lib/src/package.c | #include "package.h"
#include "kstring.h"
#include "stdlib.h"
package_t* pkg_new(int32_t id, uint32_t type, void* data, uint32_t size, int32_t pid) {
package_t* pkg = (package_t*)malloc(sizeof(package_t) + size);
if(pkg == NULL)
return NULL;
pkg->id = id;
pkg->pid = pid;
pkg->size = 0;
pkg->type = type;
void* p = get_pkg_data(pkg);
if(size > 0 && data != NULL)
memcpy(p, data, size);
pkg->size = size;
return pkg;
}
void pkg_free(package_t* pkg) {
if(pkg != NULL)
free(pkg);
}
|
smwikipedia/EwokOS | kernel/arch/versatilepb/src/irq.c | <filename>kernel/arch/versatilepb/src/irq.c
#include <irq.h>
#include <mm/mmu.h>
#include <timer.h>
/* memory mapping for the prime interrupt controller */
#define PIC ((volatile uint32_t*)(MMIO_BASE+0x00140000))
/* interrupt controller register offsets */
#define PIC_STATUS 0
#define PIC_INTACK 3
#define PIC_INT_ENABLE 4
/* memory mapping for the slave interrupt controller */
#define SIC ((volatile uint32_t*)(MMIO_BASE+0x00003000))
/* interrupt controller register offsets */
#define SIC_STATUS 0
#define SIC_INT_ENABLE 2
#define PINT_TIMER0 (1 << 4)
#define PINT_UART0 (1 << 12)
#define PINT_SIC (1 << 31)
#define SINT_KEY (1 << 3)
#define SINT_MOUSE (1 << 4)
#define SINT_SDC (1 << 22)
void irq_init() {
PIC[PIC_INT_ENABLE] |= PINT_TIMER0; //timer 0,1
PIC[PIC_INT_ENABLE] |= PINT_UART0; //uart0
PIC[PIC_INT_ENABLE] |= PINT_SIC; //SIC on
SIC[SIC_INT_ENABLE] |= SINT_KEY; //keyboard.
SIC[SIC_INT_ENABLE] |= SINT_MOUSE; //mouse.
SIC[SIC_INT_ENABLE] |= SINT_SDC; //SD card.
}
void keyboard_handle();
void mouse_handle();
void uart_handle();
void sdc_handle();
void irq_handle() {
uint32_t pic_status = PIC[PIC_STATUS];
uint32_t sic_status = SIC[SIC_STATUS];
uint32_t irq = PIC[PIC_INTACK] & 0x3ff;
PIC[PIC_INT_ENABLE] = 0x0;
if((pic_status & PINT_TIMER0) != 0) {
timer_handle();
}
if((pic_status & PINT_UART0) != 0) {
uart_handle();
}
if((pic_status & PINT_SIC) != 0) {
if((sic_status & SINT_KEY) != 0) {
keyboard_handle();
}
if((sic_status & SINT_MOUSE) != 0) {
mouse_handle();
}
if((sic_status & SINT_SDC) != 0) {
sdc_handle();
}
}
PIC[PIC_INT_ENABLE] = irq;
}
|
smwikipedia/EwokOS | rootfs/lib/src/kserv.c | #include "kserv.h"
#include <ipc.h>
#include <syscall.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
bool kserv_run(const char* reg_name, kserv_func_t servFunc, void* p) {
if(syscall1(SYSCALL_KSERV_REG, (int)reg_name) != 0) {
return false;
}
while(true) {
package_t* pkg = ipc_roll();
if(pkg != NULL) {
servFunc(pkg, p);
free(pkg);
}
else
sleep(0);
}
return true;
}
int kserv_get_pid(const char* reg_name) {
return syscall1(SYSCALL_KSERV_GET, (int)reg_name);
}
void kserv_wait(const char* reg_name) {
while(kserv_get_pid(reg_name) < 0)
sleep(0);
}
|
smwikipedia/EwokOS | rootfs/lib/include/vfs/vfs.h | <reponame>smwikipedia/EwokOS<gh_stars>0
#ifndef VFS_NODE_H
#define VFS_NODE_H
#include <fsinfo.h>
#define VFS_DIR_SIZE 0xffffffff
uint32_t vfs_add(uint32_t node, const char* name, uint32_t size, void* data);
int32_t vfs_del(uint32_t node);
int32_t vfs_node_by_name(const char* fname, fs_info_t* info);
uint32_t vfs_mount(const char* fname, const char* devName, int32_t devIndex, bool isFile);
int32_t vfs_unmount(uint32_t node);
fs_info_t* vfs_kids(uint32_t node, uint32_t* num);
#endif
|
smwikipedia/EwokOS | kernel/arch/raspi2/src/spi.c | <gh_stars>0
/*----------------------------------------------------------------------------*/
/**
* - for accessing spi
* = this is using spi0 (spi-specific interface)
* = bcm2835 has 2 more mini-spi interfaces (spi1/spi2)
* $ part of auxiliary peripheral (along with mini-uart)
* $ NOT using these
**/
#include <mm/mmu.h>
#include <dev/gpio.h>
#include <dev/spi.h>
#define SPI0_OFFSET 0x00204000
#define SPI1_OFFSET 0x00215080
#define SPI2_OFFSET 0x002150C0
#define SPI_BASE (MMIO_BASE|SPI0_OFFSET)
#define SPI_CS_REG (SPI_BASE+0x00)
#define SPI_FIFO_REG (SPI_BASE+0x04)
#define SPI_CLK_REG (SPI_BASE+0x08)
#define SPI_DLEN_REG (SPI_BASE+0x0C)
#define SPI_LTOH_REG (SPI_BASE+0x10)
#define SPI_DC_REG (SPI_BASE+0x14)
/* control status bits */
#define SPI_CNTL_CSPOL2 0x00800000
#define SPI_CNTL_CSPOL1 0x00400000
#define SPI_CNTL_CSPOL0 0x00200000
#define SPI_STAT_RXFULL 0x00100000
#define SPI_STAT_RXREAD 0x00080000
#define SPI_STAT_TXDATA 0x00040000
#define SPI_STAT_RXDATA 0x00020000
#define SPI_STAT_TXDONE 0x00010000
#define SPI_CNTL_READEN 0x00001000
#define SPI_CNTL_ADCS 0x00000800
#define SPI_CNTL_INTRXR 0x00000400
#define SPI_CNTL_INTRDN 0x00000200
#define SPI_CNTL_DMA_EN 0x00000100
#define SPI_CNTL_TRXACT 0x00000080
#define SPI_CNTL_CSPOL 0x00000040
#define SPI_CNTL_CLMASK 0x00000030
#define SPI_CNTL_CLR_RX 0x00000020
#define SPI_CNTL_CLR_TX 0x00000010
#define SPI_CNTL_CPOL 0x00000008
#define SPI_CNTL_CPHA 0x00000004
#define SPI_CNTL_CSMASK 0x00000003
#define SPI_CNTL_CS0 0x00000000
#define SPI_CNTL_CS1 0x00000001
#define SPI_CNTL_CS2 0x00000002
static uint32_t spi_which = SPI_SELECT_DEFAULT;
void spi_init(int32_t clk_divide) {
uint32_t data = SPI_CNTL_CLMASK; /* clear both rx/tx fifo */
/* clear spi fifo */
put32(SPI_CS_REG,data);
/* set largest clock divider */
clk_divide &= SPI_CLK_DIVIDE_MASK; /* 16-bit value */
put32(SPI_CLK_REG,clk_divide); /** 0=65536, power of 2, rounded down */
/* setup spi pins (ALTF0) */
gpio_config(SPI_SCLK,GPIO_ALTF0);
gpio_config(SPI_MOSI,GPIO_ALTF0);
gpio_config(SPI_MISO,GPIO_ALTF0);
gpio_config(SPI_CE0N,GPIO_ALTF0);
gpio_config(SPI_CE1N,GPIO_ALTF0);
}
void spi_select(uint32_t which) {
switch (which) {
case SPI_SELECT_0:
case SPI_SELECT_1:
spi_which = which;
break;
default:
spi_which = SPI_SELECT_DEFAULT;
}
}
void spi_activate(uint32_t enable) {
uint32_t data = SPI_CNTL_TRXACT;
if (enable) {
/* activate transfer on selected channel 0 or 1 */
put32(SPI_CS_REG,data|(spi_which>>1));
}
else {
/* de-activate transfer */
put32(SPI_CS_REG,get32(SPI_CS_REG)&~SPI_CNTL_TRXACT);
}
}
uint32_t spi_transfer(uint32_t data) {
/* wait if fifo is full */
while (!(get32(SPI_CS_REG)&SPI_STAT_TXDATA));
/* write a byte */
put32(SPI_FIFO_REG,data&0xff);
/* wait until done */
while (!(get32(SPI_CS_REG)&SPI_STAT_TXDONE));
/* should get a byte? */
while (!(get32(SPI_CS_REG)&SPI_STAT_RXDATA));
/* read a byte */
return get32(SPI_FIFO_REG)&0xff;
}
|
smwikipedia/EwokOS | rootfs/lib/src/sconf.c | <reponame>smwikipedia/EwokOS
#include <sconf.h>
#include <vfs/fs.h>
#include <stdlib.h>
sconf_t* sconf_load(const char* fname) {
int32_t size;
char* str = fs_read_file(fname, &size);
if(str == NULL || size == 0)
return NULL;
sconf_t* ret = sconf_parse(str, malloc);
free(str);
return ret;
}
|
smwikipedia/EwokOS | lib/src/sconf_parse.c | #include <sconf.h>
#include <kstring.h>
static inline bool is_space(char c) {
return (c == ' ' || c == '\t' || c == '\r' || c == '\n');
}
static inline void trim_right(char* s, int32_t i) {
i--;
while(i >= 0) {
if(is_space(s[i]))
s[i--] = 0;
else
break;
}
}
sconf_t* sconf_parse(const char* str, malloc_func_t mlc) {
if(str == NULL || str[0] == 0)
return NULL;
sconf_t *conf = (sconf_t*)mlc(sizeof(sconf_t));
if(conf == NULL)
return NULL;
int32_t i = 0;
int32_t it = 0; /*item index*/
uint8_t stat = 0; /*0 for name; 1 for value; 2 for comment*/
sconf_item_t* item = &conf->items[0];
while(it < S_CONF_ITEM_MAX) {
char c = *str;
str++;
if(c == 0) {
it++;
break;
}
if(i == 0 && is_space(c)) {
continue;
}
else if(c == '#') { //comment
if(stat == 1) {
item->value[i] = 0;
trim_right(item->value, i);
it++;
item = &conf->items[it];
}
stat = 2;
continue;
}
else if(stat == 0) {/*read name*/
if(c == '=') {
item->name[i] = 0;
i = 0;
stat = 1;
continue;
}
else if(is_space(c)) {
continue;
}
else if(i < S_CONF_NAME_MAX) {
item->name[i] = c;
i++;
}
}
else if(stat == 1) { /*read value*/
if(c == '\n') {
item->value[i] = 0;
trim_right(item->value, i);
i = 0;
stat = 0;
it++;
item = &conf->items[it];
continue;
}
if(i < S_CONF_VALUE_MAX) {
item->value[i] = c;
i++;
}
}
else { //comment
if(c == '\n') {
i = 0;
stat = 0;
}
}
}
if(it < S_CONF_ITEM_MAX)
conf->items[it].name[0] = 0;
return conf;
}
void sconf_free(sconf_t* conf, free_func_t fr) {
if(conf != NULL)
fr(conf);
}
const char* sconf_get(sconf_t *conf, const char*name) {
if(name == NULL || conf == NULL)
return "";
int32_t i = 0;
while(i < S_CONF_ITEM_MAX) {
sconf_item_t* item = &conf->items[i++];
if(item->name[0] == 0)
return "";
if(strcmp(item->name, name) == 0)
return item->value;
}
return "";
}
|
smwikipedia/EwokOS | rootfs/lib/include/dev/devserv.h | #ifndef DEVSERV_H
#define DEVSERV_H
#include <types.h>
#include <device.h>
typedef struct {
int32_t (*mount)(uint32_t node, int32_t index);
int32_t (*unmount)(uint32_t node);
int32_t (*open)(uint32_t node, int32_t flags);
int32_t (*close)(uint32_t node);
int32_t (*add)(uint32_t node, const char* name);
int32_t (*write)(uint32_t node, void* buf, uint32_t size, int32_t seek);
int32_t (*read)(uint32_t node, void* buf, uint32_t size, int32_t seek);
int32_t (*dma)(uint32_t node, uint32_t *size);
int32_t (*flush)(uint32_t node);
void* (*ctrl)(uint32_t node, int32_t cmd, void* data, uint32_t size, int32_t* ret);
} device_t;
void dev_run(device_t* dev, const char* devName, uint32_t index, const char* nodeName, bool file);
#endif
|
smwikipedia/EwokOS | rootfs/lib/include/stdio.h | <reponame>smwikipedia/EwokOS<filename>rootfs/lib/include/stdio.h<gh_stars>0
#ifndef STDIO_H
#define STDIO_H
#include <vprintf.h>
extern int32_t _stdin;
extern int32_t _stdout;
void init_stdio();
void putch(int c);
int getch();
void printf(const char *format, ...);
#endif
|
smwikipedia/EwokOS | rootfs/lib/include/graph/graph.h | <reponame>smwikipedia/EwokOS
#ifndef GRAPH_H
#define GRAPH_H
#include <graph/font.h>
typedef struct Graph {
uint32_t *buffer;
uint32_t w;
uint32_t h;
int32_t fd;
int32_t shm_id;
} graph_t;
uint32_t rgb(uint32_t r, uint32_t g, uint32_t b);
uint32_t rgb_int(uint32_t c);
graph_t* graph_open(const char* fname);
void graph_flush(graph_t* g);
void graph_close(graph_t* g);
void pixel(graph_t* g, int32_t x, int32_t y, uint32_t color);
void clear(graph_t* g, uint32_t color);
void box(graph_t* g, int32_t x, int32_t y, uint32_t w, uint32_t h, uint32_t color);
void fill(graph_t* g, int32_t x, int32_t y, uint32_t w, uint32_t h, uint32_t color);
void line(graph_t* g, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t color);
void draw_char(graph_t* g, int32_t x, int32_t y, char c, font_t* font, uint32_t color);
void draw_text(graph_t* g, int32_t x, int32_t y, const char* str, font_t* font, uint32_t color);
#endif
|
smwikipedia/EwokOS | rootfs/sbin/login/userman.c | <gh_stars>0
#include <userman.h>
#include <ipc.h>
#include <kstring.h>
#include <syscall.h>
#include <stdlib.h>
#include <proto.h>
static int _usermanPid = -1;
#define CHECK_KSERV_USERMAN \
if(_usermanPid < 0) \
_usermanPid = syscall1(SYSCALL_KSERV_GET, (int)"kserv.userman"); \
if(_usermanPid < 0) \
return -1;
int usermanAuth(const char* name, const char* passwd) {
int uid = -1;
CHECK_KSERV_USERMAN
proto_t* proto = proto_new(NULL, 0);
proto_add_str(proto, name);
proto_add_str(proto, passwd);
package_t* pkg = ipc_req(_usermanPid, 0, 0, proto->data, proto->size, true);
proto_free(proto);
if(pkg == NULL)
return -1;
uid = *(int*)get_pkg_data(pkg);
free(pkg);
return uid;
}
|
smwikipedia/EwokOS | rootfs/bin/uname/uname.c | #include <stdio.h>
#include <unistd.h>
#include <kstring.h>
int main() {
init_cmain_arg();
const char* arg = read_cmain_arg();
arg = read_cmain_arg();
if(arg == NULL)
printf("Ewok\n");
else if(strcmp(arg, "-a") == 0)
printf("Ewok micro-kernel OS, ARM A-Core, V 0.01\n");
return 0;
}
|
smwikipedia/EwokOS | rootfs/lib/include/graph/font.h | <filename>rootfs/lib/include/graph/font.h
#ifndef FONT_H
#define FONT_H
#include <types.h>
typedef struct {
int32_t idx;
uint32_t w, h;
const void *data;
int32_t pref;
} font_t;
font_t* get_font(const char* name);
#endif
|
smwikipedia/EwokOS | lib/include/fsinfo.h | <gh_stars>0
#ifndef FSINFO_H
#define FSINFO_H
#include <types.h>
#define FS_TYPE_DIR 0x0
#define FS_TYPE_FILE 0x01
typedef struct {
uint32_t id; //vfs treeNode id
uint32_t node; //node of vfstree
uint32_t size; //file size or children num of dir
uint32_t type; //file or dir
int32_t owner; //user owner
char name[NAME_MAX]; //node name
uint32_t dev_index; //index for same type device
int32_t dev_serv_pid; //device kernel service proc id
void* data;
} fs_info_t;
typedef struct FSNode {
char name[NAME_MAX];
int32_t mount;
uint32_t size;
uint32_t type;
int32_t owner;
void* data;
} fs_node_t;
#define FSN(n) ((fs_node_t*)((n)->data))
#endif
|
smwikipedia/EwokOS | rootfs/bin/cat/cat.c | <reponame>smwikipedia/EwokOS
#include <unistd.h>
#include <cmain.h>
#include <stdio.h>
#include <vfs/fs.h>
#include <kstring.h>
#include <stdlib.h>
void gen_fname(char* fname, const char* arg) {
if(arg[0] == '/') {
strcpy(fname, arg);
}
else {
char pwd[NAME_MAX];
getcwd(pwd, NAME_MAX);
if(pwd[1] == 0) /*root*/
snprintf(fname, NAME_MAX-1, "/%s", arg);
else
snprintf(fname, NAME_MAX-1, "%s/%s", pwd, arg);
}
}
int main() {
char fname_r[NAME_MAX];
char fname_w[NAME_MAX];
init_cmain_arg();
const char* arg = read_cmain_arg();
arg = read_cmain_arg();
if(arg == NULL)
return -1;
gen_fname(fname_r, arg);
int fd_r = open(fname_r, 0);
if(fd_r < 0)
return -1;
int fd_w = 0;
arg = read_cmain_arg();
if(arg != NULL) {
gen_fname(fname_w, arg);
int fd_w = open(fname_w, 0);
if(fd_w < 0) {
close(fd_r);
return -1;
}
}
while(true) {
char buf[128+1];
int sz = read(fd_r, buf, 128);
if(sz <= 0)
break;
buf[sz] = 0;
write(fd_w, buf, sz);
}
close(fd_r);
close(fd_w);
return 0;
}
|
smwikipedia/EwokOS | kernel/src/syscalls.c | #include <syscallcode.h>
#include <system.h>
#include <syscalls.h>
#include <types.h>
#include <proc.h>
#include <kernel.h>
#include <kstring.h>
#include <mm/trunkmalloc.h>
#include <mm/kmalloc.h>
#include <mm/shm.h>
#include <ipc.h>
#include <types.h>
#include <kserv.h>
#include <fsinfo.h>
#include <scheduler.h>
#include <hardware.h>
#include <semaphore.h>
#include <dev/basic_dev.h>
static int32_t syscall_dev_info(int32_t arg0, int32_t arg1) {
return dev_info(arg0, (void*)arg1);
}
static int32_t syscall_dev_char_read(int32_t arg0, int32_t arg1, int32_t arg2) {
return dev_char_read(arg0, (void*)arg1, (uint32_t)arg2);
}
static int32_t syscall_dev_char_write(int32_t arg0, int32_t arg1, int32_t arg2) {
return dev_char_write(arg0, (void*)arg1, (uint32_t)arg2);
}
static int32_t syscall_dev_block_read(int32_t arg0, int32_t arg1) {
return dev_block_read(arg0, arg1);
}
static int32_t syscall_dev_block_read_done(int32_t arg0, int32_t arg1) {
return dev_block_read_done(arg0, (void*)arg1);
}
static int32_t syscall_dev_block_write(int32_t arg0, int32_t arg1, int32_t arg2) {
return dev_block_write(arg0, (uint32_t)arg1, (void*)arg2);
}
static int32_t syscall_dev_block_write_done(int32_t arg0) {
return dev_block_write_done(arg0);
}
static int32_t syscall_shm_alloc(int arg0) {
return shm_alloc((uint32_t)arg0);
}
static int32_t syscall_shm_map(int arg0) {
return (int32_t)shm_proc_map(_current_proc->pid, arg0);
}
static int32_t syscall_shm_free(int arg0) {
shm_free(arg0);
return 0;
}
static int32_t syscall_shm_unmap(int arg0) {
return shm_proc_unmap(_current_proc->pid, arg0);
}
static int32_t syscall_exec_elf(int32_t arg0, int32_t arg1, int32_t arg2) {
const char*cmd = (const char*)arg0;
const char*p = (const char*)arg1;
if(p == NULL || cmd == NULL)
return -1;
strncpy(_current_proc->cmd, cmd, CMD_MAX);
if(!proc_load(_current_proc, p, (uint32_t)arg2)) {
return -1;
}
proc_start(_current_proc);
return 0;
}
static int32_t syscall_fork(void) {
process_t* proc = kfork(TYPE_PROC);
if(proc == NULL)
return -1;
return proc->pid;
}
static int32_t syscall_getpid(void) {
return _current_proc->pid;
}
static int32_t syscall_exit(int32_t arg0) {
(void)arg0;
proc_exit(_current_proc);
return 0;
}
static int32_t syscall_sleep_msec(int32_t arg0) {
proc_sleep_msec((uint32_t)arg0);
return 0;
}
static int32_t syscall_get_env(int32_t arg0, int32_t arg1, int32_t arg2) {
const char* v = proc_get_env((const char*)arg0);
strncpy((char*)arg1, v, arg2);
return 0;
}
static int32_t syscall_get_env_name(int32_t arg0, int32_t arg1, int32_t arg2) {
const char* n = proc_get_env_name(arg0);
if(n[0] == 0)
return -1;
strncpy((char*)arg1, n, arg2);
return 0;
}
static int32_t syscall_get_env_value(int32_t arg0, int32_t arg1, int32_t arg2) {
const char* v = proc_get_env_value(arg0);
strncpy((char*)arg1, v, arg2);
return 0;
}
static int32_t syscall_set_env(int32_t arg0, int32_t arg1) {
return proc_set_env((const char*)arg0, (const char*)arg1);
}
static int32_t syscall_thread(int32_t arg0, int32_t arg1) {
process_t* proc = kfork(TYPE_THREAD);
if(proc == NULL)
return -1;
proc->context[RESTART_ADDR] = (uint32_t)arg0;
proc->context[R0] = (uint32_t)arg1;
return proc->pid;
}
static int32_t syscall_wait(int32_t arg0) {
return proc_wait(arg0);
}
static int32_t syscall_pmalloc(int32_t arg0) {
char* p = (char*)pmalloc((uint32_t)arg0);
return (int)p;
}
static int32_t syscall_pfree(int32_t arg0) {
char* p = (char*)arg0;
pfree(p);
return 0;
}
static int32_t syscall_ipc_open(int32_t arg0, int32_t arg1) {
return ipc_open(arg0, arg1);
}
static int32_t syscall_ipc_ready() {
return ipc_ready();
}
static int32_t syscall_ipc_close(int32_t arg0) {
return ipc_close(arg0);
}
static int32_t syscall_ipc_write(int32_t arg0, int32_t arg1, int32_t arg2) {
return ipc_write(arg0, (void*)arg1, arg2);
}
static int32_t syscall_ipc_read(int32_t arg0, int32_t arg1, int32_t arg2) {
return ipc_read(arg0, (void*)arg1, arg2);
}
static int32_t syscall_ipc_ring(int32_t arg0) {
return ipc_ring(arg0);
}
static int32_t syscall_ipc_peer(int32_t arg0) {
return ipc_peer(arg0);
}
static int32_t syscall_pf_open(int32_t arg0, int32_t arg1) {
return kf_open((fs_info_t*)arg0, arg1);
}
static int32_t syscall_pf_close(int32_t arg0) {
kf_close(arg0);
return 0;
}
static int32_t syscall_pf_seek(int32_t arg0, int32_t arg1) {
process_t* proc = _current_proc;
if(proc == NULL)
return -1;
int32_t fd = arg0;
if(fd < 0 || fd >= FILE_MAX)
return -1;
kfile_t* kf = proc->space->files[fd].kf;
if(kf == NULL || kf->node_info.node == 0)
return -1;
proc->space->files[fd].seek = arg1;
return arg1;
}
static int32_t syscall_pf_get_seek(int32_t arg0) {
process_t* proc = _current_proc;
if(proc == NULL)
return -1;
int32_t fd = arg0;
if(fd < 0 || fd >= FILE_MAX)
return -1;
kfile_t* kf = proc->space->files[fd].kf;
if(kf == NULL || kf->node_info.node == 0)
return -1;
return proc->space->files[fd].seek;
}
static int32_t syscall_pf_node_by_fd(int32_t arg0, int32_t arg1) {
return kf_node_info_by_fd(arg0, (fs_info_t*)arg1);
}
static int32_t syscall_pf_node_by_addr(int32_t arg0, int32_t arg1) {
return kf_node_info_by_addr((uint32_t)arg0, (fs_info_t*)arg1);
}
static int32_t syscall_pf_node_update(int32_t arg0, int32_t arg1) {
return kf_node_info_update((uint32_t)arg0, (fs_info_t*)arg1);
}
static int32_t syscall_pf_get_ref(int32_t arg0, int32_t arg1) {
return kf_get_ref(arg0, arg1);
}
static int32_t syscall_kserv_reg(int32_t arg0) {
return kserv_reg((const char*)arg0);
}
static int32_t syscall_kserv_get(int32_t arg0) {
return kserv_get((const char*)arg0);
}
static int32_t syscall_get_cwd(int32_t arg0, int32_t arg1) {
char* pwd = (char*)arg0;
strncpy(pwd, _current_proc->pwd,
arg1 < NAME_MAX ? arg1: NAME_MAX);
return (int)pwd;
}
static int32_t syscall_set_cwd(int32_t arg0) {
const char* pwd = (const char*)arg0;
strncpy(_current_proc->pwd, pwd, NAME_MAX);
return 0;
}
static int32_t syscall_get_cmd(int32_t arg0, int32_t arg1) {
char* cmd = (char*)arg0;
strncpy(cmd, _current_proc->cmd, arg1);
return arg0;
}
static int32_t syscall_set_uid(int32_t arg0, int32_t arg1) {
if(arg1 < 0 || _current_proc->owner > 0) {/*current process not kernel proc*/
return -1;
}
process_t* proc = proc_get(arg0);
if(proc == NULL) {
return -1;
}
proc->owner = arg1;
return 0;
}
static int32_t syscall_get_uid(int32_t arg0) {
process_t* proc = proc_get(arg0);
if(proc == NULL)
return -1;
return proc->owner;
}
static int32_t syscall_semaphore_init(int32_t arg0) {
return semaphore_init((int32_t*)arg0);
}
static int32_t syscall_semaphore_close(int32_t arg0) {
return semaphore_close((int32_t*)arg0);
}
static int32_t syscall_semaphore_lock(int32_t arg0) {
return semaphore_lock((int32_t*)arg0);
}
static int32_t syscall_semaphore_unlock(int32_t arg0) {
return semaphore_unlock((int32_t*)arg0);
}
static int32_t syscall_system_cmd(int32_t arg0, int32_t arg1, int32_t arg2) {
//arg0: command id; arg1,arg2: command args
return system_cmd(arg0, arg1, arg2);
}
static int32_t (*const _syscallHandler[])() = {
[SYSCALL_DEV_INFO] = syscall_dev_info,
[SYSCALL_DEV_CHAR_READ] = syscall_dev_char_read,
[SYSCALL_DEV_CHAR_WRITE] = syscall_dev_char_write,
[SYSCALL_DEV_BLOCK_READ] = syscall_dev_block_read,
[SYSCALL_DEV_BLOCK_READ_DONE] = syscall_dev_block_read_done,
[SYSCALL_DEV_BLOCK_WRITE] = syscall_dev_block_write,
[SYSCALL_DEV_BLOCK_WRITE_DONE] = syscall_dev_block_write_done,
[SYSCALL_SHM_ALLOC] = syscall_shm_alloc,
[SYSCALL_SHM_FREE] = syscall_shm_free,
[SYSCALL_SHM_MAP] = syscall_shm_map,
[SYSCALL_SHM_UNMAP] = syscall_shm_unmap,
[SYSCALL_FORK] = syscall_fork,
[SYSCALL_GETPID] = syscall_getpid,
[SYSCALL_EXEC_ELF] = syscall_exec_elf,
[SYSCALL_WAIT] = syscall_wait,
[SYSCALL_EXIT] = syscall_exit,
[SYSCALL_SLEEP_MSEC] = syscall_sleep_msec,
[SYSCALL_GET_ENV] = syscall_get_env,
[SYSCALL_GET_ENV_NAME] = syscall_get_env_name,
[SYSCALL_GET_ENV_VALUE] = syscall_get_env_value,
[SYSCALL_SET_ENV] = syscall_set_env,
[SYSCALL_THREAD] = syscall_thread,
[SYSCALL_PMALLOC] = syscall_pmalloc,
[SYSCALL_PFREE] = syscall_pfree,
[SYSCALL_GET_CMD] = syscall_get_cmd,
[SYSCALL_IPC_OPEN] = syscall_ipc_open,
[SYSCALL_IPC_CLOSE] = syscall_ipc_close,
[SYSCALL_IPC_WRITE] = syscall_ipc_write,
[SYSCALL_IPC_READY] = syscall_ipc_ready,
[SYSCALL_IPC_READ] = syscall_ipc_read,
[SYSCALL_IPC_RING] = syscall_ipc_ring,
[SYSCALL_IPC_PEER] = syscall_ipc_peer,
[SYSCALL_PFILE_GET_SEEK] = syscall_pf_get_seek,
[SYSCALL_PFILE_SEEK] = syscall_pf_seek,
[SYSCALL_PFILE_OPEN] = syscall_pf_open,
[SYSCALL_PFILE_CLOSE] = syscall_pf_close,
[SYSCALL_PFILE_NODE_BY_FD] = syscall_pf_node_by_fd,
[SYSCALL_PFILE_NODE_BY_ADDR] = syscall_pf_node_by_addr,
[SYSCALL_PFILE_NODE_UPDATE] = syscall_pf_node_update,
[SYSCALL_PFILE_GET_REF] = syscall_pf_get_ref,
[SYSCALL_KSERV_REG] = syscall_kserv_reg,
[SYSCALL_KSERV_GET] = syscall_kserv_get,
[SYSCALL_GET_CWD] = syscall_get_cwd,
[SYSCALL_SET_CWD] = syscall_set_cwd,
[SYSCALL_SET_UID] = syscall_set_uid,
[SYSCALL_GET_UID] = syscall_get_uid,
[SYSCALL_SEMAPHORE_LOCK] = syscall_semaphore_lock,
[SYSCALL_SEMAPHORE_UNLOCK] = syscall_semaphore_unlock,
[SYSCALL_SEMAPHORE_INIT] = syscall_semaphore_init,
[SYSCALL_SEMAPHORE_CLOSE] = syscall_semaphore_close,
[SYSCALL_SYSTEM_CMD] = syscall_system_cmd
};
/* kernel side of system calls. */
int32_t handle_syscall(int32_t code, int32_t arg0, int32_t arg1, int32_t arg2) {
return _syscallHandler[code](arg0, arg1, arg2);
}
|
smwikipedia/EwokOS | kernel/arch/raspi2/src/keyboard.c | #include <types.h>
#include <mm/mmu.h>
#include <dev/keyboard.h>
#include <printk.h>
#include <system.h>
#include <proc.h>
#include <dev/basic_dev.h>
//0 1 2 3 4 5 6 7 8 9 A B C D E F
const char _ltab[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 'q', '1', 0, 0, 0, 'z', 's', 'a', 'w', '2', 0,
0, 'c', 'x', 'd', 'e', '4', '3', 0, 0, ' ', 'v', 'f', 't', 'r', '5', 0,
0, 'n', 'b', 'h', 'g', 'y', '6', 0, 0, 0, 'm', 'j', 'u', '7', '8', 0,
0, ',', 'k', 'i', 'o', '0', '9', 0, 0, '.', '/', 'l', ';', 'p', '-', 0,
0, 0, '\'', 0, '[', '=', 0, 0, 0, 0, '\r', ']', 0, '\\', 0, 0,
0, 0, 0, 0, 0, 0, '\b', 0, 0, 0, 0, 0, 0, 0, 0, 0
};
const char _utab[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 'Q', '!', 0, 0, 0, 'Z', 'S', 'A', 'W', '@', 0,
0, 'C', 'X', 'D', 'E', '$', '#', 0, 0, ' ', 'V', 'F', 'T', 'R', '%', 0,
0, 'N', 'B', 'H', 'G', 'Y', '^', 0, 0, 0, 'M', 'J', 'U', '&', '*', 0,
0, '<', 'K', 'I', 'O', ')', '(', 0, 0, '>', '?', 'L', ':', 'P', '_', 0,
0, 0, '"', 0, '{', '+', 0, 0, 0, 0, '\r','}', 0, '|', 0, 0,
0, 0, 0, 0, 0, 0, '\b', 0, 0, 0, 0, 0, 0, 0, 0, 0
};
#define KCNTL 0x00
#define KSTAT 0x04
#define KDATA 0x08
#define KCLK 0x0C
#define KISTA 0x10
#define KEYBOARD_BASE (MMIO_BASE+0x6000)
void keyboard_init() {
*(uint8_t*)(KEYBOARD_BASE + KCNTL) = 0x10; // bit4=Enable bit0=INT on
*(uint8_t*)(KEYBOARD_BASE + KCLK) = 8;
}
static uint8_t _held[128] = {0};
#define KEYB_BUF_SIZE 16
static char _buffer_data[KEYB_BUF_SIZE];
static dev_buffer_t _keyb_buffer = { _buffer_data, KEYB_BUF_SIZE, 0, 0 };
static int32_t _keyb_lock = 0;
void keyboard_handle() {
uint8_t scode;
char c = 0;
scode = *(uint8_t*)(KEYBOARD_BASE + KDATA);
if (scode == 0xF0) // key release
return;
if (_held[scode] == 1 && scode) { // next scan code following key release
_held[scode] = 0;
return;
}
_held[scode] = 1;
if(scode == 0x12 || scode == 0x59 || scode == 0x14)
return;
if(_held[0x14] == 1 && _ltab[scode] == 'c') { // if control held and 'c' pressed
return;
}
else if(_held[0x14] == 1 && _ltab[scode] == 'd') {// if control held and 'd' pressed
c = 0x04;
}
else if (_held[0x12] == 1 || _held[0x59] == 1) { // If shift key held
c = _utab[scode];
}
else { // No significant keys held
c = _ltab[scode];
}
if(c == 0)
return;
CRIT_IN(_keyb_lock)
dev_buffer_push(&_keyb_buffer, c, true);
CRIT_OUT(_keyb_lock)
//proc_wake((int32_t)&_keyb_buffer);
}
int32_t dev_keyboard_read(int16_t id, void* buf, uint32_t size) {
(void)id;
CRIT_IN(_keyb_lock)
int32_t sz = size < _keyb_buffer.size ? size:_keyb_buffer.size;
char* p = (char*)buf;
int32_t i = 0;
while(i < sz) {
char c;
if(dev_buffer_pop(&_keyb_buffer, &c) != 0)
break;
p[i] = c;
i++;
}
CRIT_OUT(_keyb_lock)
//if(i == 0)
// proc_sleep((int32_t)&_keyb_buffer);
return i;
}
|
smwikipedia/EwokOS | kernel/include/ipc.h | #ifndef KMESSAGE_H
#define KMESSAGE_H
#include <types.h>
/*init ipcernel ipc channel*/
void ipc_init();
/*open ipcernel ipc channel*/
int32_t ipc_open(int32_t pid, uint32_t buf_size);
/*close ipcernel ipc channel*/
int32_t ipc_close(int32_t id);
/*return size sent, 0 means closed, < 0 means retry. */
int32_t ipc_write(int32_t id, void* data, uint32_t size);
/*return size read, 0 means closed, < 0 means retry. */
int32_t ipc_read(int32_t id, void* data, uint32_t size);
/*switch ring*/
int32_t ipc_ring(int32_t id);
/*get peer pid of channel*/
int32_t ipc_peer(int32_t id);
/*get ready to read id of current proc*/
int32_t ipc_ready();
/*close all channel of current proc*/
void ipc_close_all(int32_t pid);
#endif
|
smwikipedia/EwokOS | kernel/arch/raspi2/src/gpio.c | <reponame>smwikipedia/EwokOS<filename>kernel/arch/raspi2/src/gpio.c
#include <mm/mmu.h>
#include <system.h>
#define GPIO_OFFSET 0x00200000
#define GPIO_BASE (MMIO_BASE|GPIO_OFFSET)
#include <dev/gpio.h>
#define GPIO_FSEL (GPIO_BASE+0x00)
#define GPIO_FSET (GPIO_BASE+0x1C)
#define GPIO_FCLR (GPIO_BASE+0x28)
#define GPIO_FGET (GPIO_BASE+0x34)
#define GPIO_EVDS (GPIO_BASE+0x40)
#define GPIO_EREN (GPIO_BASE+0x4C)
#define GPIO_EFEN (GPIO_BASE+0x58)
#define GPIO_LHEN (GPIO_BASE+0x64)
#define GPIO_LLEN (GPIO_BASE+0x70)
#define GPIO_AREN (GPIO_BASE+0x7C)
#define GPIO_AFEN (GPIO_BASE+0x88)
#define GPIO_FPUD (GPIO_BASE+0x94)
#define GPIO_SELECT_BITS 3
#define GPIO_SELECT 0x07
#define GPIO_DATA_OFFSET 20
#define GPIO_DATA_DECADE (GPIO_BASE+(2<<2))
/** 0010_0100_1001_0010_0100_1001 */
#define GPIO_DATA_OUTPUT 0x00249249
#define GPIO_DATA_DOMASK 0x00FFFFFF
void gpio_init(void) {
/* nothing to do? will be deprecated? */
}
void gpio_config(int32_t gpio_num, int32_t gpio_sel) {
uint32_t raddr = GPIO_FSEL+((gpio_num/10)<<2);
uint32_t shift = (gpio_num%10)*GPIO_SELECT_BITS;
uint32_t value = gpio_sel << shift;
uint32_t mask = GPIO_SELECT << shift;
uint32_t data = get32(raddr);
data &= ~mask;
data |= value;
put32(raddr,data);
}
void gpio_set(int32_t gpio_num) {
put32(GPIO_FSET+((gpio_num/32)<<2),1<<(gpio_num%32));
}
void gpio_clr(int32_t gpio_num) {
put32(GPIO_FCLR+((gpio_num/32)<<2),1<<(gpio_num%32));
}
void gpio_write(int32_t gpio_num, int32_t value) {
if(value) gpio_set(gpio_num);
else gpio_clr(gpio_num);
}
uint32_t gpio_read(int32_t gpio_num) {
return get32(GPIO_FGET+((gpio_num/32)<<2))&(1<<(gpio_num%32));
}
void gpio_toggle(int32_t gpio_num) {
if(gpio_read(gpio_num)) gpio_clr(gpio_num);
else gpio_set(gpio_num);
}
#define GPIO_PULL_WAIT 150
void gpio_pull(int32_t gpio_num, int32_t pull_dir) {
uint32_t shift = (gpio_num%32);
uint32_t index = (gpio_num/32)+1;
put32(GPIO_FPUD,pull_dir&GPIO_PULL_MASK);
loopd(GPIO_PULL_WAIT); /* setup time: 150 cycles? */
put32(GPIO_FPUD+(index<<2),1<<shift); /* enable ppud clock */
loopd(GPIO_PULL_WAIT); /* hold time: 150 cycles? */
put32(GPIO_FPUD,GPIO_PULL_NONE);
put32(GPIO_FPUD+(index<<2),0); /* disable ppud clock */
}
void gpio_init_data(int32_t gpio_sel) {
uint32_t conf = get32(GPIO_DATA_DECADE);
conf &= ~GPIO_DATA_DOMASK;
if(gpio_sel==GPIO_OUTPUT)
conf |= GPIO_DATA_OUTPUT;
put32(GPIO_DATA_DECADE,conf);
}
void gpio_put_data(uint32_t data) {
put32(GPIO_FSET,(data&0xff)<<GPIO_DATA_OFFSET);
put32(GPIO_FCLR,(~data&0xff)<<GPIO_DATA_OFFSET);
}
uint32_t gpio_get_data(void) {
uint32_t data = get32(GPIO_FGET);
return (data>>GPIO_DATA_OFFSET)&0xff;
}
void gpio_setevent(int32_t gpio_num,int32_t events) {
uint32_t shift = (gpio_num%32);
uint32_t index = (gpio_num/32);
uint32_t mask = 1 << shift;
uint32_t data;
/* clear by default, set only if requested */
/* enable rising edge detect status */
data = get32(GPIO_EREN+(index<<2));
data &= ~mask;
if(events&GPIO_EVENT_EDGER) data |= mask;
put32((GPIO_EREN+(index<<2)),data);
/* enable falling edge detect status */
data = get32(GPIO_EFEN+(index<<2));
data &= ~mask;
if(events&GPIO_EVENT_EDGEF) data |= mask;
put32((GPIO_EFEN+(index<<2)),data);
/* enable high level detect status */
data = get32(GPIO_LHEN+(index<<2));
data &= ~mask;
if(events&GPIO_EVENT_LVLHI) data |= mask;
put32((GPIO_LHEN+(index<<2)),data);
/* enable low level detect status */
data = get32(GPIO_LLEN+(index<<2));
data &= ~mask;
if(events&GPIO_EVENT_LVLLO) data |= mask;
put32((GPIO_LLEN+(index<<2)),data);
/* enable asynchronous rising edge detect status */
data = get32(GPIO_AREN+(index<<2));
data &= ~mask;
if(events&GPIO_EVENT_AEDGR) data |= mask;
put32((GPIO_AREN+(index<<2)),data);
/* enable asynchronous falling edge detect status */
data = get32(GPIO_AFEN+(index<<2));
data &= ~mask;
if(events&GPIO_EVENT_AEDGF) data |= mask;
put32((GPIO_AFEN+(index<<2)),data);
}
void gpio_rstevent(int32_t gpio_num) {
put32(GPIO_EVDS+((gpio_num/32)<<2),1<<(gpio_num%32));
}
uint32_t gpio_chkevent(int32_t gpio_num) {
uint32_t mask = 1 << (gpio_num%32);
return get32(GPIO_EVDS+((gpio_num/32)<<2))&mask;
}
|
smwikipedia/EwokOS | kernel/src/kfile.c | <reponame>smwikipedia/EwokOS
#include <kfile.h>
#include <kstring.h>
#include <system.h>
#include <proc.h>
#include <mm/kmalloc.h>
#define OPEN_MAX 128
static kfile_t _files[OPEN_MAX]; //file info caches
static int32_t _p_lock = 0;
void kf_init() {
uint32_t i = 0;
while(i < OPEN_MAX) {
_files[i].node_info.node = 0;
i++;
}
}
//get file info cache by node addr
static inline kfile_t* get_file(uint32_t node_addr, bool add) {
uint32_t i = 0;
int32_t at = -1;
while(i < OPEN_MAX) {
if(_files[i].node_info.node == 0)
at = i; //first free file item
else if(_files[i].node_info.node == node_addr)
return &_files[i];
i++;
}
if(at < 0 || !add)
return NULL;
_files[at].node_info.node = node_addr;
_files[at].ref_r = 0;
_files[at].ref_w = 0;
return &_files[at];
}
int32_t kf_get_ref(uint32_t node_addr, uint32_t wr) {
CRIT_IN(_p_lock)
int32_t ret = -1;
kfile_t* kf = get_file(node_addr, false);
if(kf != NULL) {
if(wr == 0)//read mode
ret = kf->ref_r;
else if(wr == 1)//write mode
ret = kf->ref_w;
else //all ref
ret = kf->ref_w + kf->ref_r;
}
CRIT_OUT(_p_lock)
return ret;
}
void kf_unref(kfile_t* kf, uint32_t wr) {
if(kf == NULL)
return;
CRIT_IN(_p_lock)
if(wr == 0) {//read mode
if(kf->ref_r > 0)
kf->ref_r--;
}
else {
if(kf->ref_w > 0)
kf->ref_w--;
}
if((kf->ref_w + kf->ref_r) == 0) { // close when ref cleared.
kf->node_info.node = 0;
}
CRIT_OUT(_p_lock)
}
void kf_ref(kfile_t* kf, uint32_t wr) {
if(kf == NULL)
return;
CRIT_IN(_p_lock)
if(wr == 0) //read mode
kf->ref_r++;
else
kf->ref_w++;
CRIT_OUT(_p_lock)
}
//open file will get file id for this process, and cache the file info
int32_t kf_open(fs_info_t* info, int32_t wr) {
process_t* proc = _current_proc;
if(proc == NULL)
return -1;
CRIT_IN(_p_lock)
kfile_t* kf = get_file(info->node, true);
if(kf == NULL) {
CRIT_OUT(_p_lock)
return -1;
}
kf_ref(kf, wr);
memcpy(&kf->node_info, info, sizeof(fs_info_t));
int32_t i;
for(i=0; i<FILE_MAX; i++) {
if(proc->space->files[i].kf == NULL) {
proc->space->files[i].kf = kf;
proc->space->files[i].wr = wr;
proc->space->files[i].seek = 0;
break;
}
}
if(i >= FILE_MAX) {
kf_unref(kf, wr);
i = -1;
}
CRIT_OUT(_p_lock)
return i;
}
void kf_close(int32_t fd) {
process_t* proc = _current_proc;
if(proc == NULL || fd < 0 || fd >= FILE_MAX)
return;
CRIT_IN(_p_lock)
kf_unref(proc->space->files[fd].kf, proc->space->files[fd].wr);
proc->space->files[fd].kf = NULL;
proc->space->files[fd].wr = 0;
proc->space->files[fd].seek = 0;
CRIT_OUT(_p_lock)
}
int32_t kf_node_info_by_fd(int32_t fd, fs_info_t* info) {
CRIT_IN(_p_lock)
int32_t ret = -1;
process_t* proc = _current_proc;
if(proc == NULL || fd < 0 || fd>= FILE_MAX) {
CRIT_OUT(_p_lock)
return ret;
}
kfile_t* kf = proc->space->files[fd].kf;
if(kf != NULL) {
memcpy(info, &kf->node_info, sizeof(fs_info_t));
ret = 0;
}
CRIT_OUT(_p_lock)
return ret;
}
int32_t kf_node_info_by_addr(uint32_t node_addr, fs_info_t* info) {
CRIT_IN(_p_lock)
int32_t ret = -1;
kfile_t* kf = get_file(node_addr, false);
if(kf != NULL) {
memcpy(info, &kf->node_info, sizeof(fs_info_t));
ret = 0;
}
CRIT_OUT(_p_lock)
return ret;
}
int32_t kf_node_info_update(uint32_t node_addr, fs_info_t* info) {
CRIT_IN(_p_lock)
int32_t ret = -1;
kfile_t* kf = get_file(node_addr, false);
if(kf != NULL) {
memcpy(&kf->node_info, info, sizeof(fs_info_t));
ret = 0;
}
CRIT_OUT(_p_lock)
return ret;
}
|
smwikipedia/EwokOS | rootfs/lib/src/cmain.c | <gh_stars>0
#include <cmain.h>
#include <syscall.h>
#include <stdio.h>
#include <unistd.h>
static char _cmd[256] = { 0 };
static int _offCmd = 0;
void init_cmain_arg() {
_offCmd = 0;
syscall2(SYSCALL_GET_CMD, (int)_cmd, 256);
}
const char* read_cmain_arg() {
const char* p = NULL;
bool quotes = false;
while(_cmd[_offCmd] != 0) {
char c = _cmd[_offCmd];
_offCmd++;
if(quotes) {
if(c == '"') {
_cmd[_offCmd-1] = 0;
return p;
}
continue;
}
if(c == ' ') {
if(p == NULL) {
continue;
}
else {
_cmd[_offCmd-1] = 0;
return p;
}
}
else if(p == NULL) {
if(c == '"') {
quotes = true;
_offCmd++;
}
p = _cmd + _offCmd - 1;
}
}
return p;
}
void _start() {
init_stdio();
int ret = main();
exit(ret);
}
|
smwikipedia/EwokOS | lib/include/procinfo.h | <reponame>smwikipedia/EwokOS
#ifndef PROC_INFO_H
#define PROC_INFO_H
#include <types.h>
typedef struct {
int32_t pid;
int32_t father_pid;
int32_t owner;
int32_t state;
uint32_t start_sec;
uint32_t heap_size;
char cmd[CMD_MAX];
} proc_info_t;
#endif
|
smwikipedia/EwokOS | rootfs/lib/include/kserv.h | #ifndef KSERV_H
#define KSERV_H
#include "package.h"
typedef void (*kserv_func_t) (package_t* pkg, void *p);
bool kserv_run(const char* reg_name, kserv_func_t servFunc, void* p);
int kserv_get_pid(const char* reg_name);
void kserv_wait(const char* reg_name);
#endif
|
smwikipedia/EwokOS | rootfs/bin/uid/uid.c | <reponame>smwikipedia/EwokOS<filename>rootfs/bin/uid/uid.c
#include <unistd.h>
#include <stdio.h>
#include <syscall.h>
int main() {
int uid = syscall1(SYSCALL_GET_UID, getpid());
printf("%d\n", uid);
return 0;
}
|
smwikipedia/EwokOS | kernel/arch/versatilepb/src/mouse.c | #include <types.h>
#include <mm/mmu.h>
#include <system.h>
#include <proc.h>
#include <basic_math.h>
#include <dev/basic_dev.h>
#define MOUSE_CR 0x00
#define MOUSE_STAT 0x04
#define MOUSE_DATA 0x08
#define MOUSE_CLKDIV 0x0C
#define MOUSE_IIR 0x10
#define MOUSE_CR_TYPE (1 << 5)
#define MOUSE_CR_RXINTREN (1 << 4)
#define MOUSE_CR_TXINTREN (1 << 3)
#define MOUSE_CR_EN (1 << 2)
#define MOUSE_CR_FD (1 << 1)
#define MOUSE_CR_FC (1 << 0)
#define MOUSE_STAT_TXEMPTY (1 << 6)
#define MOUSE_STAT_TXBUSY (1 << 5)
#define MOUSE_STAT_RXFULL (1 << 4)
#define MOUSE_STAT_RXBUSY (1 << 3)
#define MOUSE_STAT_RXPARITY (1 << 2)
#define MOUSE_STAT_IC (1 << 1)
#define MOUSE_STAT_ID (1 << 0)
#define MOUSE_IIR_TXINTR (1 << 1)
#define MOUSE_IIR_RXINTR (1 << 0)
#define MOUSE_BASE (MMIO_BASE+0x7000)
static inline bool kmi_write(uint8_t data) {
int32_t timeout = 1000;
while((get8(MOUSE_BASE+MOUSE_STAT) & MOUSE_STAT_TXEMPTY) == 0 && timeout--);
if(timeout) {
put8(MOUSE_BASE+MOUSE_DATA, data);
while((get8(MOUSE_BASE+MOUSE_STAT) & MOUSE_STAT_RXFULL) == 0);
if(get8(MOUSE_BASE+MOUSE_DATA) == 0xfa)
return true;
else
return false;
}
return false;
}
static inline bool kmi_read(uint8_t * data) {
if( (get8(MOUSE_BASE+MOUSE_STAT) & MOUSE_STAT_RXFULL)) {
*data = get8(MOUSE_BASE+MOUSE_DATA);
return true;
}
return false;
}
bool mouse_init() {
uint8_t data;
uint32_t divisor = 1000;
put8(MOUSE_CLKDIV, divisor);
put8(MOUSE_BASE+MOUSE_CR, MOUSE_CR_EN);
//reset mouse, and wait ack and pass/fail code
if(! kmi_write(0xff) )
return false;
if(! kmi_read(&data))
return false;
if(data != 0xaa)
return false;
// enable scroll wheel
kmi_write(0xf3);
kmi_write(200);
kmi_write(0xf3);
kmi_write(100);
kmi_write(0xf3);
kmi_write(80);
kmi_write(0xf2);
kmi_read(&data);
kmi_read(&data);
// set sample rate, 100 samples/sec
kmi_write(0xf3);
kmi_write(100);
// set resolution, 4 counts per mm, 1:1 scaling
kmi_write(0xe8);
kmi_write(0x02);
kmi_write(0xe6);
//enable data reporting
kmi_write(0xf4);
// clear a receive buffer
kmi_read(&data);
kmi_read(&data);
kmi_read(&data);
kmi_read(&data);
/* re-enables mouse */
put8(MOUSE_BASE+MOUSE_CR, MOUSE_CR_EN|MOUSE_CR_RXINTREN);
return true;
}
#define MOUSE_BUF_SIZE 4 //16*sizeof(mouse_raw_event_t))
static char _buffer_data[MOUSE_BUF_SIZE];
static dev_buffer_t _mouse_buffer = { _buffer_data, MOUSE_BUF_SIZE, 0, 0 };
static int32_t _mouse_lock = 0;
int32_t dev_mouse_read(int16_t id, void* buf, uint32_t size) {
(void)id;
if(mod_u32(size, 4) != 0)
return -1;
CRIT_IN(_mouse_lock)
int32_t sz = size < _mouse_buffer.size ? size:_mouse_buffer.size;
char* p = (char*)buf;
int32_t i = 0;
while(i < sz) {
char c;
if(dev_buffer_pop(&_mouse_buffer, &c) != 0) {
CRIT_OUT(_mouse_lock)
return -1;
}
p[i] = c;
i++;
}
CRIT_OUT(_mouse_lock)
return i;
}
void mouse_handle() {
CRIT_IN(_mouse_lock)
static uint8_t packet[4], index = 0;
static uint8_t btn_old = 0;
uint8_t btndown, btnup, btn;
uint8_t status;
int32_t rx, ry, rz;
status = get8(MOUSE_BASE + MOUSE_IIR);
while(status & MOUSE_IIR_RXINTR) {
packet[index] = get8(MOUSE_BASE + MOUSE_DATA);
index = (index + 1) & 0x3;
if(index == 0) {
btn = packet[0] & 0x7;
btndown = (btn ^ btn_old) & btn;
btnup = (btn ^ btn_old) & btn_old;
btn_old = btn;
if(packet[0] & 0x10)
rx = (int8_t)(0xffffff00 | packet[1]); //nagtive
else
rx = (int8_t)packet[1];
if(packet[0] & 0x20)
ry = -(int8_t)(0xffffff00 | packet[2]); //nagtive
else
ry = -(int8_t)packet[2];
rz = (int8_t)(packet[3] & 0xf);
if(rz == 0xf)
rz = -1;
btndown = (btndown << 1 | btnup);
dev_buffer_push(&_mouse_buffer, (char)btndown, true);
dev_buffer_push(&_mouse_buffer, (char)rx, true);
dev_buffer_push(&_mouse_buffer, (char)ry, true);
dev_buffer_push(&_mouse_buffer, (char)rz, true);
}
status = get8(MOUSE_BASE + MOUSE_IIR);
}
CRIT_OUT(_mouse_lock)
}
|
smwikipedia/EwokOS | kernel/include/elf.h | #ifndef ELF_H
#define ELF_H
#include <types.h>
#define ELF_MAGIC 0x464C457FU
enum elf_type {
ELFTYPE_NONE = 0,
ELFTYPE_RELOCATABLE = 1,
ELFTYPE_EXECUTABLE = 2
};
struct elf_header {
uint32_t magic;
char elf[12];
uint16_t type;
uint16_t machine;
uint32_t version;
uint32_t entry;
uint32_t phoff;
uint32_t shoff;
uint32_t flags;
uint16_t ehsize;
uint16_t phentsize;
uint16_t phnum;
uint16_t shentsize;
uint16_t shnum;
uint16_t shstrndx;
};
struct elf_program_header {
uint32_t type;
uint32_t off;
uint32_t vaddr;
uint32_t paddr;
uint32_t filesz;
uint32_t memsz;
uint32_t flags;
uint32_t align;
};
#endif
|
smwikipedia/EwokOS | rootfs/sbin/vfsd/fstree.c | <filename>rootfs/sbin/vfsd/fstree.c
#include <fstree.h>
#include <kstring.h>
#include <fsinfo.h>
#include <stdlib.h>
static uint32_t _node_id_counter = 0;
void fs_tree_node_init(tree_node_t* node) {
tree_node_init(node);
node->id = _node_id_counter++;
node->data = malloc(sizeof(fs_node_t));
fs_node_t* fn = (fs_node_t*)node->data;
fn->name[0] = 0;
fn->mount = 0;
fn->type = 0;
fn->owner = 0;
fn->data = NULL;
}
tree_node_t* fs_new_node() {
tree_node_t* ret = (tree_node_t*)malloc(sizeof(tree_node_t));
fs_tree_node_init(ret);
return ret;
}
tree_node_t* fs_tree_simple_get(tree_node_t* father, const char* name) {
if(father == NULL || strchr(name, '/') != NULL)
return NULL;
tree_node_t* node = father->fChild;
while(node != NULL) {
const char* n = FSN(node)->name;
if(strcmp(n, name) == 0) {
return node;
}
node = node->next;
}
return NULL;
}
tree_node_t* fs_tree_get(tree_node_t* father, const char* name) {
if(father == NULL)
return NULL;
if(name[0] == '/') {
/*go to root*/
while(father->father != NULL)
father = father->father;
name = name+1;
if(name[0] == 0)
return father;
}
tree_node_t* node = father;
char n[NAME_MAX+1];
int j = 0;
for(int i=0; i<NAME_MAX; i++) {
n[i] = name[i];
if(n[i] == 0) {
return fs_tree_simple_get(node, n+j);
}
if(n[i] == '/') {
n[i] = 0;
node = fs_tree_simple_get(node, n+j);
if(node == NULL)
return NULL;
j= i+1;
}
}
return NULL;
}
tree_node_t* fs_tree_simple_add(tree_node_t* father, const char* name) {
tree_node_t* node = fs_new_node();
fs_node_t* data = FSN(node);
if(node == NULL ||
data->type != FS_TYPE_DIR ||
strchr(name, '/') != NULL)
return NULL;
strncpy(data->name, name, NAME_MAX);
tree_add(father, node);
return node;
}
|
smwikipedia/EwokOS | rootfs/sbin/vfsd/vfsd.c | <gh_stars>0
#include <kserv.h>
#include <unistd.h>
#include <stdio.h>
#include <ipc.h>
#include <proto.h>
#include <vfs/vfs.h>
#include <vfs/vfscmd.h>
#include <fstree.h>
#include <kstring.h>
#include <stdlib.h>
#include <syscall.h>
typedef struct {
char dev_name[DEV_NAME_MAX];
int32_t dev_index;
int32_t dev_serv_pid;
tree_node_t* old;
} _mountT;
#define DEV_VFS "dev.vfs"
#define MOUNT_MAX 32
static _mountT _mounts[MOUNT_MAX];
static tree_node_t* _root = NULL;
static bool check_access(tree_node_t* node, bool wr) {
(void)wr;
if(node == NULL)
return false;
return true;
}
static void fsnode_init() {
for(int i=0; i<MOUNT_MAX; i++) {
memset(&_mounts[i], 0, sizeof(_mountT));
}
//strcpy(_mounts[0].dev_name, DEV_VFS);
_root = NULL;
}
static tree_node_t* fsnode_add(tree_node_t* nodeTo, const char* name, uint32_t size, int32_t pid, void* data) {
int32_t owner = syscall1(SYSCALL_GET_UID, pid);
if(!check_access(nodeTo, true))
return NULL;
tree_node_t* ret = fs_tree_simple_get(nodeTo, name);
if(ret != NULL)
return ret;
ret = fs_tree_simple_add(nodeTo, name);
if(size != VFS_DIR_SIZE)
FSN(ret)->type = FS_TYPE_FILE;
else
FSN(ret)->type = FS_TYPE_DIR;
FSN(ret)->size = size;
FSN(ret)->mount = FSN(nodeTo)->mount;
FSN(ret)->owner = owner;
FSN(ret)->data = data;
return ret;
}
static int32_t fsnode_del(tree_node_t* node) {
if(!check_access(node, true))
return -1;
tree_del(node, free);
return 0;
}
static int32_t fsnode_node_info(tree_node_t* node, fs_info_t* info) {
if(!check_access(node, false))
return -1;
if(FSN(node)->type == FS_TYPE_DIR)
info->size = node->size;
else
info->size = FSN(node)->size;
info->id = node->id;
info->node = (uint32_t)node;
info->type = FSN(node)->type;
info->owner = FSN(node)->owner;
info->dev_index = _mounts[FSN(node)->mount].dev_index;
info->dev_serv_pid = _mounts[FSN(node)->mount].dev_serv_pid;
strcpy(info->name, FSN(node)->name);
info->data = FSN(node)->data;
return 0;
}
static tree_node_t* get_node_by_name(const char* fname) {
return fs_tree_get(_root, fname);
}
static tree_node_t* build_nodes(const char* fname, int32_t owner) {
if(_root == NULL)
return NULL;
tree_node_t* father = _root;
if(fname[0] == '/')
fname = fname+1;
tree_node_t* node = father;
char n[NAME_MAX+1];
int j = 0;
for(int i=0; i<NAME_MAX; i++) {
n[i] = fname[i];
if(n[i] == 0) {
if(i == 0)
return node;
else
return fsnode_add(node, n+j, VFS_DIR_SIZE, owner, NULL);
}
if(n[i] == '/') {
n[i] = 0;
node = fsnode_add(node, n+j, VFS_DIR_SIZE, owner, NULL);
if(node == NULL)
return NULL;
j= i+1;
}
}
return NULL;
}
static tree_node_t* fsnode_mount(const char* fname, const char* dev_name,
int32_t dev_index, bool isFile, int32_t pid) {
int32_t owner = syscall1(SYSCALL_GET_UID, pid);
tree_node_t* to = build_nodes(fname, owner);
int32_t i;
for(i=0; i<MOUNT_MAX; i++) {
if(_mounts[i].dev_name[0] == 0) {
strcpy(_mounts[i].dev_name, dev_name);
_mounts[i].dev_index = dev_index;
_mounts[i].dev_serv_pid = pid;
_mounts[i].old = to; //save the old node.
break;
}
}
if(i >= MOUNT_MAX)
return NULL;
tree_node_t* node = fs_new_node();
if(node == NULL)
return NULL;
if(_root == NULL)
_root = node;
FSN(node)->owner = owner;
FSN(node)->mount = i;
strcpy(FSN(node)->name, FSN(to)->name);
//replace the old node
if(to != NULL) {
node->father = to->father;
node->prev = to->prev;
if(node->prev != NULL)
node->prev->next = node;
if(node->next != NULL)
node->next->prev = node;
if(node->father->fChild == to)
node->father->fChild = node;
if(node->father->eChild == to)
node->father->eChild = node;
}
if(isFile)
FSN(node)->type = FS_TYPE_FILE;
else
FSN(node)->type = FS_TYPE_DIR;
return node;
}
static int32_t fsnode_unmount(tree_node_t* node) {
if(!check_access(node, true) || node == _root) //can not umount root
return -1;
tree_node_t* old = _mounts[FSN(node)->mount].old;
tree_node_t* father = node->father;
tree_del(node, free);
if(old != NULL && father != NULL)
tree_add(father, old);
return 0;
}
static void do_add(package_t* pkg) {
proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size);
uint32_t node = (uint32_t)proto_read_int(proto);
const char* name = proto_read_str(proto);
uint32_t size = (uint32_t)proto_read_int(proto);
void* data = (void*)proto_read_int(proto);
tree_node_t* ret = fsnode_add((tree_node_t*)node, name, size, pkg->pid, data);
ipc_send(pkg->id, pkg->type, &ret, 4);
}
static void do_del(package_t* pkg) {
uint32_t node = *(uint32_t*)get_pkg_data(pkg);
if(fsnode_del((tree_node_t*)node) != 0)
ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0);
else
ipc_send(pkg->id, pkg->type, NULL, 0);
}
static void do_info(package_t* pkg) {
uint32_t node = *(uint32_t*)get_pkg_data(pkg);
fs_info_t info;
if(node == 0 || fsnode_node_info((tree_node_t*)node, &info) != 0)
ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0);
else
ipc_send(pkg->id, pkg->type, &info, sizeof(fs_info_t));
}
static void do_node_by_name(package_t* pkg) {
proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size);
const char* name = proto_read_str(proto);
proto_free(proto);
fs_info_t info;
tree_node_t* node = get_node_by_name(name);
if(node == NULL || fsnode_node_info(node, &info) != 0)
ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0);
else
ipc_send(pkg->id, pkg->type, &info, sizeof(fs_info_t));
}
static void do_kids(package_t* pkg) {
tree_node_t* node = (tree_node_t*)(*(int32_t*)get_pkg_data(pkg));
if(node == NULL || node->size == 0) {
ipc_send(pkg->id, pkg->type, NULL, 0);
return;
}
uint32_t size = sizeof(fs_info_t) * node->size;
fs_info_t* ret = (fs_info_t*)malloc(size);
memset(ret, 0, size);
uint32_t i;
tree_node_t* n = node->fChild;
for(i=0; i<node->size; i++) {
if(n == NULL)
break;
fsnode_node_info(n, &ret[i]);
n = n->next;
}
ipc_send(pkg->id, pkg->type, ret, size);
free(ret);
}
static void do_mount(package_t* pkg) {
proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size);
const char* fname = proto_read_str(proto);
const char* dev_name = proto_read_str(proto);
int32_t dev_index = proto_read_int(proto);
int32_t isFile = proto_read_int(proto);
proto_free(proto);
tree_node_t* node = fsnode_mount(fname, dev_name, dev_index, isFile, pkg->pid);
ipc_send(pkg->id, pkg->type, &node, 4);
}
static void do_unmount(package_t* pkg) {
tree_node_t* node = (tree_node_t*)(*(int32_t*)get_pkg_data(pkg));
fsnode_unmount(node);
ipc_send(pkg->id, pkg->type, NULL, 0);
}
static void handle(package_t* pkg, void* p) {
(void)p;
switch(pkg->type) {
case VFS_CMD_ADD:
do_add(pkg);
break;
case VFS_CMD_DEL:
do_del(pkg);
break;
case VFS_CMD_INFO:
do_info(pkg);
break;
case VFS_CMD_NODE_BY_NAME:
do_node_by_name(pkg);
break;
case VFS_CMD_KIDS:
do_kids(pkg);
break;
case VFS_CMD_MOUNT:
do_mount(pkg);
break;
case VFS_CMD_UNMOUNT:
do_unmount(pkg);
break;
}
}
int main() {
if(kserv_get_pid("kserv.vfsd") >= 0) {
printf("panic: 'kserv.vfsd' process has been running already!\n");
return -1;
}
fsnode_init();
if(!kserv_run("kserv.vfsd", handle, NULL)) {
return -1;
}
return 0;
}
|
smwikipedia/EwokOS | rootfs/lib/include/vfs/fs.h | #ifndef FS_H
#define FS_H
#include <fsinfo.h>
enum {
FS_OPEN = 0,
FS_CLOSE,
FS_WRITE,
FS_READ,
FS_CTRL,
FS_FLUSH,
FS_DMA,
FS_ADD
};
int fs_open(const char* name, int32_t flags);
int fs_close(int fd);
int fs_info(int fd, fs_info_t* info);
int fs_ninfo(uint32_t node_addr, fs_info_t* info);
int fs_finfo(const char* name, fs_info_t* info);
fs_info_t* fs_kids(int fd, uint32_t *num);
int fs_read(int fd, char* buf, uint32_t size);
int fs_ctrl(int fd, int32_t cmd, void* input, uint32_t isize, void* output, uint32_t osize);
int fs_getch(int fd);
int fs_putch(int fd, int c);
int fs_write(int fd, const char* buf, uint32_t size);
int fs_add(int dirFD, const char* name);
int32_t fs_flush(int fd);
int32_t fs_dma(int fd, uint32_t* size);
int32_t fs_inited();
char* fs_read_file(const char* fname, int32_t *size);
#endif
|
smwikipedia/EwokOS | lib/include/vprintf.h | #ifndef VPRINTF_H
#define VPRINTF_H
#include <stdarg.h>
#include <types.h>
typedef void (*outc_func_t)(char c, void* p);
void v_printf(outc_func_t outc, void* p, const char* format, va_list ap);
int32_t snprintf(char *target, int32_t size, const char *format, ...);
#endif
|
smwikipedia/EwokOS | rootfs/lib/src/stdlib.c | #include <stdlib.h>
#include <syscall.h>
void* malloc(uint32_t size) {
char* p = (char*)syscall1(SYSCALL_PMALLOC, size);
return (void*)p;
}
void free(void* p) {
syscall1(SYSCALL_PFREE, (int)p);
}
int32_t atoi_base(const char *s, int32_t b) {
int32_t i, result, x, error;
for (i = result = error = 0; s[i]!='\0'; i++, result += x) {
if (b==2) {
if (!(s[i]>47&&s[i]<50)){ //rango
error = 1;
}
else {
x = s[i] - '0';
result *= b;
}
}
else if (b==8) {
if (i==0 && s[i]=='0'){
x=0;
}
else if (!(s[i]>47&&s[i]<56)) { //rango
error = 1;
}
else {
x = s[i] - '0';
result *= b;
}
}
else if (b==10) {
if (!(s[i]>47&&s[i]<58)) { //rango
error = 1;
}
else {
x = s[i] - '0';
result *= b;
}
}
else if (b==16) {
if((i==0 && s[i]=='0')||(i==1 && (s[i]=='X'||s[i]=='x'))) {
x = 0;
}
else if (!((s[i]>47 && s[i]<58) || ((s[i]>64 && s[i]<71) || (s[i]>96 && s[i]<103)) )) { //rango
error = 1;
}
else {
x = (s[i]>64 && s[i]<71)? s[i]-'7': s[i] - '0';
x = (s[i]>96 && s[i]<103)? s[i]-'W': x;
result *= b;
}
}
}
if (error)
return 0;
else
return result;
}
int32_t atoi(const char *str) {
return atoi_base(str, 10);
}
const char* getenv(const char* name) {
static char ret[64];
syscall3(SYSCALL_GET_ENV, (int32_t)name, (int32_t)ret, 63);
return ret;
}
int32_t setenv(const char* name, const char* value) {
return syscall2(SYSCALL_SET_ENV, (int32_t)name, (int32_t)value);
}
|
smwikipedia/EwokOS | rootfs/lib/src/thread.c | #include <thread.h>
#include <syscall.h>
int32_t thread_raw(thread_func_t func, void* p) {
return syscall2(SYSCALL_THREAD, (int32_t)func, (int32_t)p);
}
|
smwikipedia/EwokOS | kernel/src/mm/kmalloc.c | #include <mm/kmalloc.h>
#include <mm/trunkmalloc.h>
#include <mm/mmu.h>
#include <kernel.h>
#include <printk.h>
static malloc_t _kmalloc;
static uint32_t _kmalloc_mem_tail;
static void km_shrink(void* arg, int32_t pages) {
(void)arg;
_kmalloc_mem_tail -= pages * PAGE_SIZE;
}
static bool km_expand(void* arg, int32_t pages) {
(void)arg;
uint32_t to = _kmalloc_mem_tail + (pages * PAGE_SIZE);
if(to > (KMALLOC_BASE + KMALLOC_SIZE))
return false;
_kmalloc_mem_tail = to;
return true;
}
static void* km_get_mem_tail(void* arg) {
(void)arg;
return (void*)_kmalloc_mem_tail;
}
void km_init() {
_kmalloc_mem_tail = KMALLOC_BASE;
_kmalloc.expand = km_expand;
_kmalloc.shrink = km_shrink;
_kmalloc.get_mem_tail = km_get_mem_tail;
}
void *km_alloc(uint32_t size) {
void *ret = trunk_malloc(&_kmalloc, size);
if(ret == NULL) {
printk("Panic: km_alloc failed!\n");
}
return ret;
}
void km_free(void* p) {
if(p == NULL)
return;
trunk_free(&_kmalloc, p);
}
|
smwikipedia/EwokOS | rootfs/lib/src/unistd.c | #include <unistd.h>
#include <vfs/fs.h>
#include <syscall.h>
#include <kstring.h>
#include <stdio.h>
#include <stdlib.h>
#include <procinfo.h>
#include <ext2.h>
int fork() {
return syscall0(SYSCALL_FORK);
}
int getpid() {
return syscall0(SYSCALL_GETPID);
}
char* from_sd(const char *filename, int32_t* sz);
static char* read_from_sd(const char* fname, int32_t *size) {
char* p = from_sd(fname, size);
return p;
}
int exec(const char* cmd_line) {
char* img = NULL;
int32_t size;
char cmd[CMD_MAX];
int i;
for(i=0; i<CMD_MAX-1; i++) {
cmd[i] = cmd_line[i];
if(cmd[i] == 0 || cmd[i] == ' ')
break;
}
cmd[i] = 0;
if(fs_inited() < 0) {
img = read_from_sd(cmd, &size);
}
else {
img = fs_read_file(cmd, &size);
}
if(img == NULL) {
printf("'%s' dosn't exist!\n", cmd);
return -1;
}
int res = syscall3(SYSCALL_EXEC_ELF, (int)cmd_line, (int)img, size);
free(img);
return res;
}
void exit(int code) {
syscall1(SYSCALL_EXIT, code);
}
void wait(int pid) {
syscall1(SYSCALL_WAIT, pid);
}
char* getcwd(char* buf, uint32_t size) {
return (char*)syscall2(SYSCALL_GET_CWD, (int)buf, (int)size);
}
int chdir(const char* dir) {
return syscall1(SYSCALL_SET_CWD, (int)dir);
}
int getuid() {
return syscall1(SYSCALL_GET_UID, getpid());
}
static inline unsigned int msleep(unsigned int msecs) {
return syscall1(SYSCALL_SLEEP_MSEC, msecs);
}
unsigned int usleep(unsigned int usecs) {
return syscall1(SYSCALL_SLEEP_MSEC, usecs/1000);
}
unsigned int sleep(unsigned int secs) {
return msleep(secs*1000);
}
/*io functions*/
int open(const char* fname, int mode) {
return fs_open(fname, mode);
}
int write(int fd, const void* buf, uint32_t size) {
return fs_write(fd, buf, size);
}
int read(int fd, void* buf, uint32_t size) {
return fs_read(fd, buf, size);
}
void close(int fd) {
fs_close(fd);
}
|
smwikipedia/EwokOS | rootfs/lib/include/vfs/vfscmd.h | #ifndef VFSCMD_H
#define VFSCMD_H
enum {
VFS_CMD_ADD = 0,
VFS_CMD_DEL,
VFS_CMD_INFO,
VFS_CMD_NODE_BY_FD,
VFS_CMD_NODE_BY_NAME,
VFS_CMD_KIDS,
VFS_CMD_MOUNT,
VFS_CMD_UNMOUNT
};
#endif
|
smwikipedia/EwokOS | rootfs/lib/include/semaphore.h | #ifndef SEMAPHORE_H
#define SEMAPHORE_H
#include <types.h>
typedef int32_t semaphore_t;
int32_t semaphore_init(semaphore_t* s);
int32_t semaphore_close(semaphore_t* s);
int32_t semaphore_lock(semaphore_t* s);
int32_t semaphore_unlock(semaphore_t* s);
#endif
|
smwikipedia/EwokOS | kernel/src/system.c | #include <system.h>
#include <types.h>
#include <mm/kalloc.h>
#include <proc.h>
#include <kstring.h>
#include <hardware.h>
#include <timer.h>
inline void loopd(uint32_t times) {
while(times > 0)
times--;
}
static int32_t get_procs_num() {
int32_t res = 0;
for(int32_t i=0; i<PROCESS_COUNT_MAX; i++) {
if(_process_table[i].state != UNUSED &&
(_current_proc->owner == 0 ||
_process_table[i].owner == _current_proc->owner)) {
res++;
}
}
return res;
}
static proc_info_t* get_procs(int32_t *num) {
*num = get_procs_num();
if(*num == 0)
return NULL;
/*need to be freed later used!*/
proc_info_t* procs = (proc_info_t*)pmalloc(sizeof(proc_info_t)*(*num));
if(procs == NULL)
return NULL;
int32_t j = 0;
for(int32_t i=0; i<PROCESS_COUNT_MAX && j<(*num); i++) {
if(_process_table[i].state != UNUSED &&
(_current_proc->owner == 0 ||
_process_table[i].owner == _current_proc->owner)) {
procs[j].pid = _process_table[i].pid;
procs[j].father_pid = _process_table[i].father_pid;
procs[j].owner = _process_table[i].owner;
procs[j].state = _process_table[i].state;
procs[j].start_sec = _process_table[i].start_sec;
procs[j].heap_size = _process_table[i].space->heap_size;
strcpy(procs[j].cmd, _process_table[i].cmd);
j++;
}
}
*num = j;
return procs;
}
static int32_t kill_proc(int32_t pid) {
process_t* proc = proc_get(pid);
if(proc == NULL)
return -1;
if(_current_proc->owner != proc->owner && _current_proc->owner > 0)
return -1;
proc_exit(proc);
return 0;
}
int32_t system_cmd(int32_t cmd, int32_t arg0, int32_t arg1) {
int32_t ret = -1;
switch(cmd) {
case 0: //get total mem size
ret = (int32_t)get_phy_ram_size();
break;
case 1: //get free mem size
ret = (int32_t)get_free_mem_size();
break;
case 2: //get procs
ret = (int32_t)get_procs((int32_t*)arg0);
break;
case 3: //kill proc
ret = (int32_t)kill_proc(arg0);
break;
case 4: //get cpu tick
cpu_tick((uint32_t*)arg0, (uint32_t*)arg1);
ret = 0;
break;
default:
break;
}
return ret;
}
|
smwikipedia/EwokOS | rootfs/lib/src/vfs/vfs.c | #include <vfs/vfs.h>
#include <vfs/vfscmd.h>
#include <kserv.h>
#include <proto.h>
#include <stdlib.h>
#include <ipc.h>
#include <package.h>
#define VFS_NAME "kserv.vfsd"
inline uint32_t vfs_add(uint32_t node, const char* name, uint32_t size, void* data) {
int32_t serv_pid = kserv_get_pid(VFS_NAME);
if(serv_pid < 0)
return 0;
proto_t* proto = proto_new(NULL, 0);
proto_add_int(proto, (int32_t)node);
proto_add_str(proto, name);
proto_add_int(proto, (int32_t)size);
proto_add_int(proto, (int32_t)data);
package_t* pkg = ipc_req(serv_pid, 0, VFS_CMD_ADD, proto->data, proto->size, true);
proto_free(proto);
if(pkg == NULL || pkg->type == PKG_TYPE_ERR) {
if(pkg != NULL) free(pkg);
return 0;
}
uint32_t ret = *(uint32_t*)get_pkg_data(pkg);
free(pkg);
return ret;
}
inline int32_t vfs_del(uint32_t node) {
int32_t serv_pid = kserv_get_pid(VFS_NAME);
if(serv_pid < 0)
return -1;
package_t* pkg = ipc_req(serv_pid, 0, VFS_CMD_DEL, &node, 4, true);
if(pkg == NULL || pkg->type == PKG_TYPE_ERR) {
if(pkg != NULL) free(pkg);
return -1;
}
free(pkg);
return 0;
}
inline int32_t vfs_node_by_name(const char* fname, fs_info_t* info) {
int32_t serv_pid = kserv_get_pid(VFS_NAME);
if(serv_pid < 0)
return -1;
proto_t* proto = proto_new(NULL, 0);
proto_add_str(proto, fname);
package_t* pkg = ipc_req(serv_pid, 0, VFS_CMD_NODE_BY_NAME, proto->data, proto->size, true);
proto_free(proto);
if(pkg == NULL || pkg->type == PKG_TYPE_ERR) {
if(pkg != NULL) free(pkg);
return -1;
}
memcpy(info, get_pkg_data(pkg), sizeof(fs_info_t));
free(pkg);
return 0;
}
inline uint32_t vfs_mount(const char* fname, const char* devName, int32_t devIndex, bool isFile) {
int32_t serv_pid = kserv_get_pid(VFS_NAME);
if(serv_pid < 0)
return 0;
proto_t* proto = proto_new(NULL, 0);
proto_add_str(proto, fname);
proto_add_str(proto, devName);
proto_add_int(proto, devIndex);
proto_add_int(proto, (int32_t)isFile);
package_t* pkg = ipc_req(serv_pid, 0, VFS_CMD_MOUNT, proto->data, proto->size, true);
proto_free(proto);
if(pkg == NULL || pkg->type == PKG_TYPE_ERR) {
if(pkg != NULL) free(pkg);
return 0;
}
uint32_t node = *(uint32_t*)get_pkg_data(pkg);
free(pkg);
return node;
}
inline int32_t vfs_unmount(uint32_t node) {
int32_t serv_pid = kserv_get_pid(VFS_NAME);
if(serv_pid < 0)
return -1;
package_t* pkg = ipc_req(serv_pid, 0, VFS_CMD_UNMOUNT, &node, 4, true);
if(pkg == NULL || pkg->type == PKG_TYPE_ERR) {
if(pkg != NULL) free(pkg);
return -1;
}
free(pkg);
return 0;
}
fs_info_t* vfs_kids(uint32_t node, uint32_t* num) {
*num = 0;
int32_t serv_pid = kserv_get_pid(VFS_NAME);
if(serv_pid < 0)
return NULL;
package_t* pkg = ipc_req(serv_pid, 0, VFS_CMD_KIDS, &node, 4, true);
if(pkg == NULL || pkg->type == PKG_TYPE_ERR || pkg->size == 0) {
if(pkg != NULL) free(pkg);
return NULL;
}
fs_info_t* ret = (fs_info_t*)malloc(pkg->size);
memcpy(ret, get_pkg_data(pkg), pkg->size);
*num = pkg->size / sizeof(fs_info_t);
free(pkg);
return ret;
}
|
smwikipedia/EwokOS | kernel/arch/raspi2/src/mailbox.c | <reponame>smwikipedia/EwokOS
#include "mailbox.h"
#include "mm/mmu.h"
#include "hardware.h"
#define MAILBOX_OFFSET 0x0000B880
#define MAILBOX_BASE (MMIO_BASE | MAILBOX_OFFSET)
#define MAIL0_BASE (MAILBOX_BASE+0x00)
#define MAIL0_READ (MAILBOX_BASE+0x00)
#define MAIL0_POLL (MAILBOX_BASE+0x10)
#define MAIL0_SEND_ID (MAILBOX_BASE+0x14)
#define MAIL0_STATUS (MAILBOX_BASE+0x18)
#define MAIL0_CONFIG (MAILBOX_BASE+0x1C)
#define MAIL0_WRITE (MAILBOX_BASE+0x20)
/* MAIL0_WRITE IS ACTUALLY MAIL1_BASE/MAIL1_READ? */
#define MAIL1_BASE (MAILBOX_BASE+0x20)
#define MAIL1_READ (MAILBOX_BASE+0x20)
#define MAIL1_POLL (MAILBOX_BASE+0x30)
#define MAIL1_SEND_ID (MAILBOX_BASE+0x34)
#define MAIL1_STATUS (MAILBOX_BASE+0x38)
#define MAIL1_CONFIG (MAILBOX_BASE+0x3C)
#define MAIL_CHANNEL_MASK 0x0000000F
#define MAIL_CH_POWER 0x00000000
#define MAIL_CH_FBUFF 0x00000001
#define MAIL_CH_VUART 0x00000002
#define MAIL_CH_VCHIQ 0x00000003
#define MAIL_CH_LEDS 0x00000004
#define MAIL_CH_BUTTS 0x00000005
#define MAIL_CH_TOUCH 0x00000006
#define MAIL_CH_NOUSE 0x00000007
#define MAIL_CH_TAGAV 0x00000008
#define MAIL_CH_TAGVA 0x00000009
/**
0: Power management
1: Framebuffer
2: Virtual UART
3: VCHIQ
4: LEDs
5: Buttons
6: Touch screen
7: <NOT USED?>
8: Property tags (ARM -> VC)
9: Property tags (VC -> ARM)
**/
#define TAGS_STATUS_REQUEST 0x00000000
#define TAGS_STATUS_SUCCESS 0x80000000
#define TAGS_STATUS_FAILURE 0x80000001
#define TAGS_END 0x00000000
#define TAGS_MASK_SET 0x00008000
#define TAGS_REQUESTS 0x00000000
#define TAGS_RESPONSE 0x80000000
/** number of 32-bit buffer allocated for tags response */
#define TAGS_RESPONSE_SIZE 2
/** VideoCore */
#define TAGS_FIRMWARE_REVISION 0x00000001
#define TAGS_SET_CURSOR_INFO (0x00000010|TAGS_MASK_SET)
#define TAGS_SET_CURSOR_STATE (0x00000011|TAGS_MASK_SET)
/** Hardware */
#define TAGS_BOARD_MODEL 0x00010001
#define TAGS_BOARD_REVISION 0x00010002
#define TAGS_BOARD_MAC_ADDR 0x00010003
#define TAGS_BOARD_SERIAL 0x00010004
#define TAGS_ARM_MEMORY 0x00010005
#define TAGS_VC_MEMORY 0x00010006
#define TAGS_CLOCKS 0x00010007
#define TAGS_POWER_STATE 0x00020001
#define TAGS_TIMING 0x00020002
#define TAGS_SET_POWER_STATE (TAGS_POWER_STATE|TAGS_MASK_SET)
#define TAGS_CLOCK_STATE 0x00030001
#define TAGS_CLOCK_RATE 0x00030002
#define TAGS_VOLTAGE 0x00030003
#define TAGS_MAX_CLOCK_RATE 0x00030004
#define TAGS_MAX_VOLTAGE 0x00030005
#define TAGS_TEMPERATURE 0x00030006
#define TAGS_MIN_CLOCK_RATE 0x00030007
#define TAGS_MIN_VOLTAGE 0x00030008
#define TAGS_TURBO 0x00030009
#define TAGS_MAX_TEMPERATURE 0x0003000a
#define TAGS_STC 0x0003000b
#define TAGS_ALLOCATE_MEMORY 0x0003000c
#define TAGS_LOCK_MEMORY 0x0003000d
#define TAGS_UNLOCK_MEMORY 0x0003000e
#define TAGS_RELEASE_MEMORY 0x0003000f
#define TAGS_EXECUTE_CODE 0x00030010
#define TAGS_EXECUTE_QPU 0x00030011
#define TAGS_ENABLE_QPU 0x00030012
#define TAGS_X_RES_MEM_HANDLE 0x00030014
#define TAGS_EDID_BLOCK 0x00030020
#define TAGS_CUSTOMER_OTP 0x00030021
#define TAGS_DOMAIN_STATE 0x00030030
#define TAGS_GPIO_STATE 0x00030041
#define TAGS_GPIO_CONFIG 0x00030043
#define TAGS_SET_CLOCK_STATE (TAGS_CLOCK_STATE|TAGS_MASK_SET)
#define TAGS_SET_CLOCK_RATE (TAGS_CLOCK_RATE|TAGS_MASK_SET)
#define TAGS_SET_VOLTAGE (TAGS_VOLTAGE|TAGS_MASK_SET)
#define TAGS_SET_TURBO (TAGS_TURBO|TAGS_MASK_SET)
#define TAGS_SET_CUSTOMER_OTP (TAGS_CUSTOMER_OTP|TAGS_MASK_SET)
#define TAGS_SET_DOMAIN_STATE (TAGS_DOMAIN_STATE|TAGS_MASK_SET)
#define TAGS_SET_GPIO_STATE (TAGS_GPIO_STATE|TAGS_MASK_SET)
#define TAGS_SET_SDHOST_CLOCK (0x00038042|TAGS_MASK_SET)
#define TAGS_SET_GPIO_CONFIG (TAGS_GPIO_CONFIG|TAGS_MASK_SET)
#define TAGS_FB_ALLOCATE 0x00040001
#define TAGS_FB_BLANK 0x00040002
#define TAGS_FB_PHYS_DIMS 0x00040003
#define TAGS_FB_VIRT_DIMS 0x00040004
#define TAGS_FB_DEPTH 0x00040005
#define TAGS_FB_PIXEL_ORDER 0x00040006
#define TAGS_FB_ALPHA_MODE 0x00040007
#define TAGS_FB_PITCH 0x00040008
#define TAGS_FB_VIROFFSET 0x00040009
#define TAGS_FB_OVERSCAN 0x0004000a
#define TAGS_FB_PALETTE 0x0004000b
#define TAGS_FB_TOUCHBUF 0x0004000f
#define TAGS_FB_GPIOVIRTBUF 0x00040010
#define TAGS_FBT_PHYS_DIMS 0x00044003
#define TAGS_FBT_VIRT_DIMS 0x00044004
#define TAGS_FBT_DEPTH 0x00044005
#define TAGS_FBT_PIXEL_ORDER 0x00044006
#define TAGS_FBT_ALPHA_MODE 0x00044007
#define TAGS_FBT_VIROFFSET 0x00044009
#define TAGS_FBT_OVERSCAN 0x0004400a
#define TAGS_FBT_PALETTE 0x0004400b
#define TAGS_FBT_VSYNC 0x0004400e
#define TAGS_FB_RELEASE (TAGS_FB_ALLOCATE|TAGS_MASK_SET)
#define TAGS_FB_SET_PHYS_DIMS (TAGS_FB_PHYS_DIMS|TAGS_MASK_SET)
#define TAGS_FB_SET_VIRT_DIMS (TAGS_FB_VIRT_DIMS|TAGS_MASK_SET)
#define TAGS_FB_SET_DEPTH (TAGS_FB_DEPTH|TAGS_MASK_SET)
#define TAGS_FB_SET_PIXEL_ORDER (TAGS_FB_PIXEL_ORDER|TAGS_MASK_SET)
#define TAGS_FB_SET_ALPHA_MODE (TAGS_FBT_ALPHA_MODE|TAGS_MASK_SET)
#define TAGS_FB_SET_VIROFFSET (TAGS_FB_VIROFFSET|TAGS_MASK_SET)
#define TAGS_FB_SET_OVERSCAN (TAGS_FB_OVERSCAN|TAGS_MASK_SET)
#define TAGS_FB_SET_PALETTE (TAGS_FB_PALETTE|TAGS_MASK_SET)
#define TAGS_FB_SET_TOUCHBUF (0x0004801f|TAGS_MASK_SET)
#define TAGS_FB_SET_GPIOVIRTBUF (0x00048020|TAGS_MASK_SET)
#define TAGS_FB_SET_VSYNC (0x0004800e|TAGS_MASK_SET)
#define TAGS_FB_SET_BACKLIGHT (0x0004800f|TAGS_MASK_SET)
#define TAGS_VCHIQ_INIT (0x00048010|TAGS_MASK_SET)
#define TAGS_COMMAND_LINE 0x00050001
#define TAGS_DMA_CHANNELS 0x00060001
#define INFO_STATUS_OK 0
#define INFO_STATUS_UNKNOWN_ERROR_ 1
#define INFO_STATUS_INVALID_BUFFER 2
#define INFO_STATUS_REQUEST_FAILED 3
#define INFO_STATUS_REQUEST_ERROR_ 4
#define INFO_STATUS_READING_TAGS 5
void __mem_barrier();
/**
* Mailbox (MB) 0: VC -> ARM, MB 1: ARM->VC
* - write to MB1, read from MB0!
**/
#define MAIL_STATUS_FULL 0x80000000
#define MAIL_STATUS_EMPTY 0x40000000
void mailboxInit(void) {
/* nothing to do! */
}
unsigned int mailboxRead(unsigned int channel) {
unsigned int value;
while(true) {
/* wait if mailbox is empty */
while(get32(MAIL0_STATUS) & MAIL_STATUS_EMPTY);
/* get value@channel */
value = get32(MAIL0_BASE);
/* check if the expected channel */
if ((value & MAIL_CHANNEL_MASK)==channel) break;
/* if not, data lost? should we store it somewhere? */
}
/* return address only */
value &= ~MAIL_CHANNEL_MASK;
return value;
}
void mailboxWrite(unsigned int channel,unsigned int value) {
/* merge value/channel data */
value &= ~MAIL_CHANNEL_MASK;
value |= (channel & MAIL_CHANNEL_MASK);
/* wait if mailbox is full */
while (get32(MAIL1_STATUS) & MAIL_STATUS_FULL);
/* read-write barrier */
__mem_barrier();
/* send it to MB1! */
put32(MAIL1_BASE, value);
}
/* for a 1kb mailbox buffer size */
#define MAIL_BUFFER_SIZE 256
volatile unsigned int mbbuff[MAIL_BUFFER_SIZE] __attribute__((aligned(16)));
int tags_init(volatile unsigned int* buff) {
int size = 1;
buff[size++] = TAGS_STATUS_REQUEST;
buff[size++] = TAGS_END;
buff[0] = size*sizeof(unsigned int);
return size;
}
int tags_insert(volatile unsigned int* buff, int size, unsigned int tags_id, int tags_buff_count) {
size--; /* override previous tags_end! */
buff[size++] = tags_id;
buff[size++] = tags_buff_count*sizeof(unsigned int);
buff[size++] = TAGS_REQUESTS;
while (tags_buff_count>0) {
buff[size++] = 0x00000000;
tags_buff_count--;
}
/* place terminating tags */
buff[size++] = TAGS_END;
/* update size */
buff[0] = size*sizeof(unsigned int);
return size;
}
int tags_isinfo(volatile unsigned int* buff, int size, unsigned int tags_id, int tags_needed, volatile TagsHeadT** pptag) {
TagsHeadT* ptag = (TagsHeadT*)&buff[size];
unsigned int test = ptag->req_res&TAGS_RESPONSE;
unsigned int temp = ptag->req_res&~TAGS_RESPONSE;
unsigned int vbufsize = tags_needed*sizeof(unsigned int);
size += (ptag->vbuf_size/sizeof(unsigned int))+3;
if (ptag->tags_id!=tags_id||ptag->vbuf_size<vbufsize||!test||temp>vbufsize)
*pptag = 0x0;
else
*pptag = ptag;
return size;
}
unsigned int* mailboxGetBoardInfo(TagsInfoT* info) {
volatile TagsHeadT *ptag;
unsigned int temp = (unsigned int)mbbuff, test;
int size, read;
/* for DEBUG! */
info->buff = mbbuff;
/* configure buffer for request */
size = tags_init(mbbuff);
/* tag to request firmware revision */
size = tags_insert(mbbuff,size,TAGS_FIRMWARE_REVISION,TAGS_RESPONSE_SIZE);
/* tag to request board model */
size = tags_insert(mbbuff,size,TAGS_BOARD_MODEL,TAGS_RESPONSE_SIZE);
/* tag to request board revision */
size = tags_insert(mbbuff,size,TAGS_BOARD_REVISION,TAGS_RESPONSE_SIZE);
/* tag to request board mac addr */
size = tags_insert(mbbuff,size,TAGS_BOARD_MAC_ADDR,TAGS_RESPONSE_SIZE);
/* tag to request board serial num */
size = tags_insert(mbbuff,size,TAGS_BOARD_SERIAL,TAGS_RESPONSE_SIZE);
/* tag to request arm memory */
size = tags_insert(mbbuff,size,TAGS_ARM_MEMORY,TAGS_RESPONSE_SIZE);
/* tag to request videocore memory */
size = tags_insert(mbbuff,size,TAGS_VC_MEMORY,TAGS_RESPONSE_SIZE);
/* prepare address */
temp = P2V(temp);
/* mail it! */
__mem_barrier();
mailboxWrite(MAIL_CH_TAGAV, temp);
__mem_barrier();
test = mailboxRead(MAIL_CH_TAGAV);
__mem_barrier();
/* validate response */
if (test!=temp) {
info->test = test;
info->temp = temp;
info->info_status = INFO_STATUS_INVALID_BUFFER;
return 0x0;
}
/* DEBUG */
info->test = mbbuff[0];
info->temp = mbbuff[1];
read = 2;
/* get request status */
switch(info->temp) {
case TAGS_STATUS_SUCCESS:
info->info_status = INFO_STATUS_READING_TAGS;
break;
case TAGS_STATUS_FAILURE:
info->info_status = INFO_STATUS_REQUEST_FAILED;
return 0x0;
default:
info->info_status = INFO_STATUS_REQUEST_ERROR_;
return 0x0;
}
/* get firmware revision */
read = tags_isinfo(mbbuff,read,TAGS_FIRMWARE_REVISION,1,&ptag);
if (!ptag) return 0x0;
info->vc_revision = ptag->vbuffer[0];
/* get board model */
read = tags_isinfo(mbbuff,read,TAGS_BOARD_MODEL,1,&ptag);
if (!ptag) return 0x0;
info->board_model = ptag->vbuffer[0];
/* get board revision */
read = tags_isinfo(mbbuff,read,TAGS_BOARD_REVISION,1,&ptag);
if (!ptag) return 0x0;
info->board_revision = ptag->vbuffer[0];
/* get board mac addr */
read = tags_isinfo(mbbuff,read,TAGS_BOARD_MAC_ADDR,2,&ptag);
if (!ptag) return 0x0;
/** need to convert network byte order to little endian! */
info->board_mac_addrh = ptag->vbuffer[0];
info->board_mac_addrl = ptag->vbuffer[1];
/* get board serial num */
read = tags_isinfo(mbbuff,read,TAGS_BOARD_SERIAL,2,&ptag);
if (!ptag) return 0x0;
info->board_serial_l = ptag->vbuffer[0];
info->board_serial_h = ptag->vbuffer[1];
/* get arm memory */
read = tags_isinfo(mbbuff,read,TAGS_ARM_MEMORY,2,&ptag);
if (!ptag) return 0x0;
info->memory_arm_base = ptag->vbuffer[0];
info->memory_arm_size = ptag->vbuffer[1];
/* get vc memory */
read = tags_isinfo(mbbuff,read,TAGS_VC_MEMORY,2,&ptag);
if (!ptag) return 0x0;
info->memory_vc_base = ptag->vbuffer[0];
info->memory_vc_size = ptag->vbuffer[1];
/* return pointer to buffer on success */
info->info_status = INFO_STATUS_OK;
return (unsigned int*)mbbuff;
}
unsigned int* mailboxGetVideoInfo(TagsInfoT* info) {
volatile TagsHeadT *ptag;
unsigned int temp = (unsigned int)mbbuff, test;
int size, read;
/* for DEBUG! */
info->buff = mbbuff;
/* configure buffer for request */
size = tags_init(mbbuff);
/* tag to request physical display dimension */
size = tags_insert(mbbuff,size,TAGS_FB_PHYS_DIMS,TAGS_RESPONSE_SIZE);
/* tag to request virtual display dimension */
size = tags_insert(mbbuff,size,TAGS_FB_VIRT_DIMS,TAGS_RESPONSE_SIZE);
/* tag to request depth (bits-per-pixel) */
size = tags_insert(mbbuff,size,TAGS_FB_DEPTH,TAGS_RESPONSE_SIZE);
/* tag to request pixel order */
size = tags_insert(mbbuff,size,TAGS_FB_PIXEL_ORDER,TAGS_RESPONSE_SIZE);
/* tag to request alpha mode */
size = tags_insert(mbbuff,size,TAGS_FB_ALPHA_MODE,TAGS_RESPONSE_SIZE);
/* tag to request pitch */
size = tags_insert(mbbuff,size,TAGS_FB_PITCH,TAGS_RESPONSE_SIZE);
/* tag to request virtual offset */
size = tags_insert(mbbuff,size,TAGS_FB_VIROFFSET,TAGS_RESPONSE_SIZE);
/* prepare address */
temp = P2V(temp);
/* mail it! */
__mem_barrier();
mailboxWrite(MAIL_CH_TAGAV, temp);
__mem_barrier();
test = mailboxRead(MAIL_CH_TAGAV);
__mem_barrier();
/* validate response */
if (test!=temp) {
info->test = test;
info->temp = temp;
info->info_status = INFO_STATUS_INVALID_BUFFER;
return 0x0;
}
/* DEBUG */
info->test = mbbuff[0];
info->temp = mbbuff[1];
read = 2;
/* get request status */
switch(info->temp) {
case TAGS_STATUS_SUCCESS:
info->info_status = INFO_STATUS_READING_TAGS;
break;
case TAGS_STATUS_FAILURE:
info->info_status = INFO_STATUS_REQUEST_FAILED;
return 0x0;
default:
info->info_status = INFO_STATUS_REQUEST_ERROR_;
return 0x0;
}
/* get physical dimension */
read = tags_isinfo(mbbuff,read,TAGS_FB_PHYS_DIMS,2,&ptag);
if (!ptag) return 0x0;
info->fb_width = ptag->vbuffer[0];
info->fb_height = ptag->vbuffer[1];
/* get virtual dimension */
read = tags_isinfo(mbbuff,read,TAGS_FB_VIRT_DIMS,2,&ptag);
if (!ptag) return 0x0;
info->fb_vwidth = ptag->vbuffer[0];
info->fb_vheight = ptag->vbuffer[1];
/* get depth */
read = tags_isinfo(mbbuff,read,TAGS_FB_DEPTH,1,&ptag);
if (!ptag) return 0x0;
info->fb_depth = ptag->vbuffer[0];
/* get pixel order */
read = tags_isinfo(mbbuff,read,TAGS_FB_PIXEL_ORDER,1,&ptag);
if (!ptag) return 0x0;
info->fb_pixel_order = ptag->vbuffer[0]; /** 0x0:BGR , 0x1:RGB */
/* get apha mode */
read = tags_isinfo(mbbuff,read,TAGS_FB_ALPHA_MODE,1,&ptag);
if (!ptag) return 0x0;
/** 0x0:enabled(0=opaque) , 0x1:reversed(0=transparent), 0x2:ignored */
info->fb_alpha_mode = ptag->vbuffer[0];
/* get pitch */
read = tags_isinfo(mbbuff,read,TAGS_FB_PITCH,1,&ptag);
if (!ptag) return 0x0;
info->fb_pitch = ptag->vbuffer[0];
/* get virtual offsets */
read = tags_isinfo(mbbuff,read,TAGS_FB_VIROFFSET,2,&ptag);
if (!ptag) return 0x0;
info->fb_vx_offset = ptag->vbuffer[0];
info->fb_vy_offset = ptag->vbuffer[1];
/* return pointer to buffer on success */
info->info_status = INFO_STATUS_OK;
return (unsigned int*)mbbuff;
}
|
smwikipedia/EwokOS | kernel/include/mm/shm.h | <filename>kernel/include/mm/shm.h<gh_stars>0
#ifndef SHAREMEM_H
#define SHAREMEM_H
#include <types.h>
void shm_init();
int32_t shm_alloc(uint32_t size);
void* shm_raw(int32_t id);
void shm_free(int32_t id);
void* shm_proc_map(int32_t pid, int32_t id);
int32_t shm_proc_unmap(int32_t pid, int32_t id);
void shm_proc_free(int32_t pid);
#endif
|
smwikipedia/EwokOS | kernel/arch/raspi2/src/fb.c | <reponame>smwikipedia/EwokOS<gh_stars>0
#include "mailbox.h"
#include "dev/fb.h"
#include "kstring.h"
void __mem_barrier();
#define VIDEO_FB_CHANNEL MAIL_CH_FBUFF
#define VIDEO_INIT_RETRIES 3
#define VIDEO_INITIALIZED 0
#define VIDEO_ERROR_RETURN 1
#define VIDEO_ERROR_POINTER 2
#define MAIL_CH_FBUFF 0x00000001
int32_t videoInit(fb_info_t *p_fbinfo) {
uint32_t init = VIDEO_INIT_RETRIES;
uint32_t test, addr = ((uint32_t)p_fbinfo);
while(init>0) {
__mem_barrier();
mailboxWrite(VIDEO_FB_CHANNEL,addr);
__mem_barrier();
test = mailboxRead(VIDEO_FB_CHANNEL);
__mem_barrier();
if (test)
test = VIDEO_ERROR_RETURN;
else if(p_fbinfo->pointer == 0x0)
test = VIDEO_ERROR_POINTER;
else {
test = VIDEO_INITIALIZED; break;
}
init--;
}
return test;
}
static fb_info_t _fb_info __attribute__((aligned(16)));
bool fb_init() {
TagsInfoT info;
mailboxGetVideoInfo(&info);
/** initialize fbinfo */
_fb_info.height = info.fb_height;
_fb_info.width = info.fb_width;
_fb_info.vheight = info.fb_height;
_fb_info.vwidth = info.fb_width;
_fb_info.pitch = 0;
_fb_info.depth = 32;
_fb_info.xoffset = 0;
_fb_info.yoffset = 0;
_fb_info.pointer = 0;
_fb_info.size = 0;
if(videoInit(&_fb_info) == 0)
return true;
return false;
}
int32_t dev_fb_info(int16_t id, void* info) {
(void)id;
fb_info_t* fb_info = (fb_info_t*)info;
memcpy(fb_info, &_fb_info, sizeof(fb_info_t));
return 0;
}
int32_t dev_fb_write(int16_t id, void* buf, uint32_t size) {
(void)id;
uint32_t sz = (_fb_info.depth/8) * _fb_info.width * _fb_info.height;
if(size > sz)
size = sz;
memcpy((void*)_fb_info.pointer, buf, size);
return (int32_t)size;
}
|
smwikipedia/EwokOS | kernel/include/mm/kalloc.h | #ifndef KALLOC_H
#define KALLOC_H
#include <types.h>
typedef struct PageList {
struct PageList *next;
} page_list_t;
/* exported function declarations */
void kalloc_init(uint32_t start, uint32_t end);
void *kalloc();
void kfree(void *page);
void *kalloc1k();
void kfree1k(void *page);
uint32_t get_free_mem_size(void);
#endif
|
smwikipedia/EwokOS | rootfs/dev/sdcard/sdcard.c | #include <unistd.h>
#include <stdlib.h>
#include <kstring.h>
#include <dev/devserv.h>
#include <vfs/vfs.h>
#include <vfs/fs.h>
#include <syscall.h>
#include <ext2.h>
#include <device.h>
static int32_t _iblock = 12;
static int32_t _typeid = dev_typeid(DEV_SDC, 0);
static int32_t read_block(int32_t block, char* buf) {
if(syscall2(SYSCALL_DEV_BLOCK_READ, _typeid, block) < 0)
return -1;
int32_t res = -1;
while(true) {
res = syscall2(SYSCALL_DEV_BLOCK_READ_DONE, _typeid, (int32_t)buf);
if(res == 0)
break;
sleep(0);
}
return 0;
}
typedef struct {
INODE node;
void* data;
} ext2_node_data_t;
static inline INODE* get_node(int32_t me, uint16_t iblk, char* buf) {
read_block(iblk+(me/8), buf); // read block inode of me
return (INODE *)buf + (me % 8);
}
static int32_t add_nodes(INODE *ip, uint16_t iblk, uint32_t node) {
int32_t i;
char c, *cp;
DIR *dp;
char* buf1 = (char*)malloc(SDC_BLOCK_SIZE);
char* buf2 = (char*)malloc(SDC_BLOCK_SIZE);
for (i=0; i<12; i++){
if ( ip->i_block[i] ){
read_block(ip->i_block[i], buf1);
dp = (DIR *)buf1;
cp = buf1;
if(dp->inode == 0)
continue;
while (cp < &buf1[SDC_BLOCK_SIZE]){
c = dp->name[dp->name_len]; // save last byte
dp->name[dp->name_len] = 0;
if(strcmp(dp->name, ".") != 0 && strcmp(dp->name, "..") != 0) {
int32_t me = dp->inode - 1;
INODE* ip_node = get_node(me, iblk, buf2);
ext2_node_data_t* data = (ext2_node_data_t*)malloc(sizeof(ext2_node_data_t));
data->data = NULL;
memcpy(&data->node, ip_node, sizeof(INODE));
if(dp->file_type == 2) {//director
uint32_t node_add = vfs_add(node, dp->name, VFS_DIR_SIZE, data);
add_nodes(&data->node, iblk, node_add);
}
else if(dp->file_type == 1) { //file
vfs_add(node, dp->name, data->node.i_size, data);
}
}
//add node
dp->name[dp->name_len] = c; // restore that last byte
cp += dp->rec_len;
dp = (DIR *)cp;
}
}
}
free(buf1);
free(buf2);
return 0;
}
static int32_t sdcard_mount(uint32_t node, int32_t index) {
(void)index;
GD *gp;
INODE *ip;
char* buf = (char*)malloc(SDC_BLOCK_SIZE);
/* read blk#2 to get group descriptor 0 */
read_block(2, buf);
gp = (GD *)buf;
_iblock = (uint16_t)gp->bg_inode_table;
read_block(_iblock, buf); // read first inode block
ip = (INODE *)buf + 1; // ip->root inode #2
add_nodes(ip, _iblock, node);
free(buf);
return 0;
}
static char* ext2_read(INODE* ip, int32_t* sz) {
*sz = ip->i_size;
int32_t blk12 = ip->i_block[12];
int32_t mlc_size = ALIGN_UP(*sz, SDC_BLOCK_SIZE);
char* addr = (char *)malloc(mlc_size);
char* ret = addr;
uint32_t *up;
/* read indirect block into b2 */
int32_t i, count = 0;
for (i=0; i<12 && count<(*sz); i++){
if (ip->i_block[i] == 0)
break;
if(read_block(ip->i_block[i], addr) != 0) {
free(addr);
return NULL;
}
addr += SDC_BLOCK_SIZE;
count += SDC_BLOCK_SIZE;
}
if (blk12) { // only if file has indirect blocks
char* buf = (char*)malloc(SDC_BLOCK_SIZE);
read_block(blk12, buf);
up = (uint32_t *)buf;
while(*up && count<(*sz)){
if(read_block(*up, addr) != 0) {
free(addr);
free(buf);
return NULL;
}
addr += SDC_BLOCK_SIZE;
up++;
count += SDC_BLOCK_SIZE;
}
free(buf);
}
return ret;
}
int32_t sdcard_open(uint32_t node, int32_t flags) {
(void)flags;
fs_info_t info;
if(fs_ninfo(node, &info) != 0 || info.data == NULL)
return -1;
if(info.type == FS_TYPE_DIR)
return 0;
ext2_node_data_t* data = (ext2_node_data_t*)info.data;
int32_t fsize = 0;
const char* p = NULL;
if(data->data != NULL) {
fsize = data->node.i_size;
p = (const char*)data->data;
}
else {
p = ext2_read(&data->node, &fsize);
if(p == NULL || fsize == 0)
return -1;
data->data = (void*)p;
}
return 0;
}
int32_t sdcard_close(uint32_t node) {
fs_info_t info;
if(fs_ninfo(node, &info) != 0 || info.data == NULL)
return -1;
if(info.type == FS_TYPE_DIR)
return 0;
if(syscall2(SYSCALL_PFILE_GET_REF, node, 2) > 1) //1 ref left for this closing fd
return 0;
ext2_node_data_t* data = (ext2_node_data_t*)info.data;
if(data->data != NULL) {
free(data->data);
data->data = NULL;
}
return 0;
}
int32_t sdcard_read(uint32_t node, void* buf, uint32_t size, int32_t seek) {
fs_info_t info;
if(fs_ninfo(node, &info) != 0 || info.data == NULL)
return -1;
ext2_node_data_t* data = (ext2_node_data_t*)info.data;
int32_t fsize = 0;
const char* p = NULL;
if(data->data == NULL) {
return -1;
}
fsize = data->node.i_size;
p = (const char*)data->data;
int32_t rest_size = fsize - seek; /*seek*/
if(rest_size <= 0) {
return 0;
}
if(size > (uint32_t)rest_size)
size = rest_size;
memcpy(buf, p+seek, size);
return size;
}
int main() {
device_t dev = {0};
dev.mount = sdcard_mount;
dev.open = sdcard_open;
dev.read = sdcard_read;
dev.close = sdcard_close;
//dev_run(&dev, "dev.sdcard", 0, "/sdcard", false);
dev_run(&dev, "dev.sdcard", 0, "/", false);
return 0;
}
|
smwikipedia/EwokOS | rootfs/lib/include/shm.h | #ifndef SHAREMEM_H
#define SHAREMEM_H
#include <types.h>
int32_t shm_alloc(uint32_t size);
void shm_free(int32_t id);
void* shm_map(int32_t id);
int32_t shm_unmap(int32_t id);
#endif
|
smwikipedia/EwokOS | lib/include/basic_math.h | <filename>lib/include/basic_math.h
#ifndef BASIC_MATH_H
#define BASIC_MATH_H
#include <types.h>
uint32_t div_u32(uint32_t v, uint32_t by);
uint32_t mod_u32(uint32_t v, uint32_t by);
#endif
|
smwikipedia/EwokOS | kernel/include/kernel.h | #ifndef KERNEL_H
#define KERNEL_H
#include <mm/mmu.h>
extern char _kernel_start[];
extern char _kernel_end[];
extern char _init_stack_top[];
extern char _irq_stack_top[];
extern page_dir_entry_t* _kernel_vm;
void set_kernel_vm(page_dir_entry_t* vm);
void set_allocable_vm(page_dir_entry_t* vm);
#endif
|
smwikipedia/EwokOS | kernel/src/scheduler.c | <gh_stars>0
#include <proc.h>
#include <scheduler.h>
void schedule(void) {
if(_current_proc->state == READY) { //current process ready to run
_current_proc->state = RUNNING;
proc_start(_current_proc);
return;
}
//current process is runing, switch to next one.
process_t* head_proc = _current_proc;
process_t* proc = _current_proc->next;
while(head_proc != proc) {
proc_sleep_check(proc);
if(proc->state == READY) {
if(head_proc->state == RUNNING) //current process running.
head_proc->state = READY;
proc->state = RUNNING; //run next one.
proc_start(proc);
return;
}
else if(proc->state == TERMINATED) {
process_t* tmp = proc;
proc = proc->next;
proc_free(tmp);
}
else
proc = proc->next;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.